import React, { useState } from 'react';
import { Button, Divider, Form, Input, Checkbox, Col, Row, Modal, Select } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { jsonToArray } from '@/utils/utils';
import { layout, typeOptions, boolOptions, infoOptions } from '../staticData/index';
import style from '../style/info.less';
import MealSection from './MealSection';
import MealLimit from './MealLimit';

const CheckboxGroup = Checkbox.Group;
const { confirm } = Modal;
const CustomerInfo = props => {
  const [form] = Form.useForm();
  const [meals, setMeals] = useState({});
  const [mealTypes, setMealTypes] = useState([]);

  // 关闭分组信息弹窗
  const handleCancel = () => {
    props.handleClose(false);
  };

  // 添加/保存分组
  const handleConfirm = async () => {
    const res = await form.validateFields();
    console.log('res :>> ', res);
  };

  // 风险提示
  const checkConfirm = () => {
    const mt = '';
    return new Promise((resolve, reject) => {
      confirm({
        title: '风险提示',
        icon: <ExclamationCircleOutlined />,
        content: `确定关闭${mt}餐品类型？此餐品类型下关联的商户及商品将一并删除，不可逆请谨慎操作！`,
        onOk() {
          resolve(1);
        },
        onCancel() {
          reject(new Error());
        },
      });
    });
  };

  // 改变餐品类型
  const onChangeMealType = async ms => {
    try {
      if (props.info && props.info.id && ms.length < mealTypes.length) {
        await checkConfirm();
      }
      if (mealTypes.includes('1') && mealTypes.includes('2')) {
        if (!(ms.includes('1') && ms.includes('2'))) {
          if (ms.includes('3')) {
            ms = ['3'];
          } else {
            ms = [];
          }
        }
      } else if (ms.length < 3 && ms.length) {
        ms = ['1', '2'];
        if (ms.includes('3')) {
          ms.push('3');
        }
      }
      form.setFieldsValue({
        types: ms,
      });
      setMealTypes(ms);
    } catch {
      form.setFieldsValue({
        types: mealTypes,
      });
    }
  };
  // 改变餐段
  const onChangeMealSection = e => {
    console.log('e.target :>> ', e.target);
    const { value, checked, label } = e.target;
    const values = Object.assign({}, meals);
    if (checked) {
      values[value] = label;
      // values.push(value);
      // } else if (values.includes(value)) {
      // const index = values.findIndex(v => v === value);
      // values.splice(index, 1);
    } else {
      delete values[value];
    }
    setMeals(values);
  };

  return (
    <Modal
      title="企业客户信息"
      open={props.visible}
      destroyOnClose
      maskClosable={false}
      width="850px"
      onOk={handleConfirm}
      onCancel={handleCancel}
    >
      <Form name="basicInfo" {...layout} form={form}>
        <Form.Item
          label="公司名称"
          name="businessName"
          rules={[{ required: true, message: '请输入公司名称!' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item label="企业取餐点" name="qucan">
          <Select />
        </Form.Item>
        <Form.Item
          label="企业截止时间"
          name="times"
          wrapperCol={{ span: 20 }}
          rules={[{ required: true, message: '请输入企业截止时间!' }]}
          extra={<span>企业员工下单的截至时间，仅支持正整数，单位为分钟。</span>}
        >
          <Row>
            <Col span={22}>
              <Input />
            </Col>
            <Col span={2}>
              <div className={style.tip}>分钟</div>
            </Col>
          </Row>
        </Form.Item>
        <Form.Item
          label="餐品类型"
          name="types"
          rules={[{ required: true, message: '请选择餐品类型!' }]}
        >
          <CheckboxGroup options={jsonToArray(typeOptions)} onChange={onChangeMealType} />
        </Form.Item>
        <Form.Item label="餐段配置" required>
          <MealSection meals={meals} onChange={onChangeMealSection} />
        </Form.Item>
        <Form.Item
          label="商品展示信息"
          name="xinxin"
          rules={[{ required: true, message: '请选择商品展示信息!' }]}
        >
          <CheckboxGroup options={infoOptions} />
        </Form.Item>
        <Divider orientation="left" plain>
          企业单笔消费限额
        </Divider>
        {Object.keys(meals).map(meal => (
          <Form.Item label={meals[meal]} required wrapperCol={{ span: 20 }}>
            <Row>
              {mealTypes.map((t, i) => (
                <Col span={7} offset={i ? 1 : 0}>
                  <MealLimit value={t} label={typeOptions[t]} name={`${meal}-${t.value}`} />
                </Col>
              ))}
            </Row>
          </Form.Item>
        ))}
        <Form.Item
          label="是否周预览"
          name="yulan"
          rules={[{ required: true, message: '请选择是否周预览!' }]}
        >
          <CheckboxGroup options={boolOptions} />
        </Form.Item>
      </Form>
    </Modal>
  );
};
export default CustomerInfo;
