import React, { useEffect, useState } from 'react';
import {
  Button,
  Divider,
  Form,
  Input,
  InputNumber,
  Checkbox,
  Radio,
  Col,
  Row,
  Modal,
  Select,
  message,
} from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { jsonToArray } from '@/utils/utils';
import {
  layout,
  mealType,
  boolOptions,
  hideOptions,
  infoOptions,
  mealSections,
} from '../staticData/index';
import { apiEnterpriseInfo, apiNewEnterprise, apiEditEnterprise } from '../service';
import style from '../style/info.less';
import MealSection from './MealSection';
import MealLimit from './MealLimit';

const CheckboxGroup = Checkbox.Group;
const RadioGroup = Radio.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();
    // const res = await form.getFieldsValue();
    if (res.mealTimePeriod.length < 1) {
      message.warn('请选择餐段');
      return;
    }
    const params = Object.assign({}, res);
    const arr = [];
    res.mealTimePeriod.forEach(item => {
      if (item.mealPeriodType) {
        arr.push(item);
      }
    });
    params.mealTimePeriod = arr;
    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 { id, checked, label } = e.target;
    const values = Object.assign({}, meals);
    if (checked) {
      values[id] = label;
      // values.push(value);
      // } else if (values.includes(value)) {
      // const index = values.findIndex(v => v === value);
      // values.splice(index, 1);
    } else {
      delete values[id];
    }
    console.log('values :>> ', values);
    setMeals(values);
  };

  // 获取企业客户新
  const getInfo = async () => {
    const res = await apiEnterpriseInfo(1);
  };

  useEffect(() => {
    if (props.visible) {
      getInfo();
    }
  }, [props.visible]);

  return (
    <Modal
      title="企业客户信息"
      open={props.visible}
      destroyOnClose
      maskClosable={false}
      width="880px"
      onOk={handleConfirm}
      onCancel={handleCancel}
    >
      <Form
        name="basicInfo"
        initialValues={{ mealTimePeriod: [{}, {}, {}] }}
        {...layout}
        form={form}
      >
        <Form.Item
          label="公司名称"
          name="name"
          rules={[{ required: true, message: '请输入公司名称!' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item label="企业取餐点" name="pickselfIds">
          <Select />
        </Form.Item>
        <Form.Item
          label="企业截止时间"
          name="endOrderTime"
          wrapperCol={{ span: 20 }}
          rules={[{ required: true, message: '请输入企业截止时间!' }]}
          extra={<span>企业员工下单的截至时间，仅支持正整数，单位为分钟。</span>}
        >
          <Row>
            <InputNumber min={0} max={600} addonAfter="分钟" />
          </Row>
        </Form.Item>
        <Form.Item
          label="餐品类型"
          name="mealType"
          rules={[{ required: true, message: '请选择餐品类型!' }]}
        >
          <CheckboxGroup options={jsonToArray(mealType)} onChange={onChangeMealType} />
        </Form.Item>
        <Form.Item label="餐段配置" required wrapperCol={{ span: 12 }}>
          <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]} key={meal} required wrapperCol={{ span: 20 }}>
            <Row>
              {mealTypes.map((t, i) => (
                <Col span={7} offset={i ? 1 : 0} key={t}>
                  <MealLimit value={t} label={mealType[t]} name={`${meal}-${t.value}`} />
                </Col>
              ))}
            </Row>
          </Form.Item>
        ))}
        <Form.Item label="商品隐藏信息" name="hideInfo">
          <CheckboxGroup options={hideOptions} />
        </Form.Item>
        <Form.Item
          label="是否周预览"
          name="weekPreview"
          rules={[{ required: true, message: '请选择是否周预览!' }]}
        >
          <RadioGroup options={boolOptions} />
        </Form.Item>
      </Form>
    </Modal>
  );
};
export default CustomerInfo;
