import React, { useEffect, useState } from 'react';
import {
  Button,
  Divider,
  Form,
  Input,
  InputNumber,
  Checkbox,
  Radio,
  Col,
  Row,
  Modal,
  Select,
  message,
  notification,
} from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { jsonToArray } from '@/utils/utils';
import moment from 'moment';
import {
  layout,
  mealType,
  boolOptions,
  hideOptions,
  infoOptions,
  mealSections,
} from '../staticData/index';
import {
  apiEnterpriseInfo,
  apiNewEnterprise,
  apiEditEnterprise,
  apiEnterprisePickSelf,
} 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 [pickSelfList, setPickSelfList] = useState([]);

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

  // 校验时间
  const checkTime = (arr, curren) => {
    let valid = false;
    arr.forEach(item => {
      if (curren > item.beginTime && curren < item.endTime) {
        valid = true;
      }
    });
    return valid;
  };

  // 提交
  const handleConfirm = async () => {
    const res = await form.validateFields();
    console.log('res :>> ', res);
    // const res = await form.getFieldsValue();
    if (res.mealTimePeriod.length < 1) {
      message.warn('请选择餐段');
      return;
    }
    const params = Object.assign(
      {
        hideImage: 0,
      },
      res,
    );
    const arr = [];
    let validTime = false;
    res.mealTimePeriod.forEach(item => {
      if (item.mealPeriodType) {
        const obj = Object.assign({}, item);
        obj.beginTime = moment(obj.time[0]).format('HH:mm');
        obj.endTime = moment(obj.time[1]).format('HH:mm');
        delete obj.time;
        if (checkTime(arr, obj.beginTime) || checkTime(arr, obj.endTime)) {
          validTime = true;
        }
        arr.push(obj);
      }
    });
    if (validTime) {
      notification.error({ message: '时间段不能交叉！' });
      return;
    }
    params.mealTimePeriod = arr;
    if (res.hideInfo && res.hideInfo.length) {
      params.hidePrice = res.hideInfo.includes('hidePrice') ? 1 : 0;
      params.hideImage = res.hideInfo.includes('hideImage') ? 1 : 0;
      delete params.hideInfo;
    }
    const limits = [];
    if (!res.mealLimit) {
      notification.error({ message: '请输入限额！' });
      return;
    }
    // 处理限额
    Object.keys(res.mealLimit).forEach(item => {
      const json = {
        mealPeriodType: item.replace('limit', ''),
        limit: [],
      };
      Object.keys(res.mealLimit[item]).forEach(t => {
        json.limit.push({
          mealType: t,
          limit: res.mealLimit[item][t],
        });
      });
      limits.push(json);
    });
    params.mealLimit = limits;
    console.log('params :>> ', params);
    let api = apiNewEnterprise;
    if (props.id) {
      params.id = props.id;
      api = apiEditEnterprise;
    }
    const resp = await api(params);
    if (resp) {
      handleCancel();
      props.reFresh();
      notification.success({ message: '保存成功！' });
    }
  };

  // 风险提示
  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('4')) {
            ms = ['4'];
          } else {
            ms = [];
          }
        }
      } else if (ms.length < 3 && ms.length) {
        ms = ['1', '2'];
        if (ms.includes('4')) {
          ms.push('4');
        }
      }
      form.setFieldsValue({
        mealType: ms,
      });
      setMealTypes(ms);
    } catch {
      form.setFieldsValue({
        mealType: mealTypes,
      });
    }
  };
  // 改变餐段
  const onChangeMealSection = e => {
    const { id, checked, label } = e.target;
    const values = Object.assign({}, meals);
    if (checked) {
      values[id] = label;
    } else {
      delete values[id];
    }
    setMeals(values);
  };

  // 获取企业客户信息
  const getInfo = async () => {
    const res = await apiEnterpriseInfo(props.id);
    if (res && res.data) {
      const obj = Object.assign({}, res.data);
      if (res.data.mealTimePeriod && res.data.mealTimePeriod.length) {
        const m = moment().format('YYYY-MM-DD');
        obj.mealTimePeriod = res.data.mealTimePeriod.map(item => ({
          mealPeriodType: `${item.mealPeriodType}`,
          time: [moment(`${m} ${item.beginTime}`), moment(`${m} ${item.endTime}`)],
        }));
      } else {
        obj.mealTimePeriod = [];
      }
      obj.mealLimit = {};
      if (res.data.mealLimit) {
        res.data.mealLimit.forEach(item => {
          obj.mealLimit[`limit${item.mealPeriodType}`] = {};
          item.limit.forEach(limit => {
            obj.mealLimit[`limit${item.mealPeriodType}`][limit.mealType] = limit.limit;
          });
        });
      }
      obj.hideInfo = [];
      if (+res.data.hidePrice) {
        obj.hideInfo.push('hidePrice');
      }
      if (+res.data.hideImage) {
        obj.hideInfo.push('hideImage');
      }
      obj.mealType = res.data.mealType.map(item => `${item}`);
      console.log('obj :>> ', obj);
      setMealTypes(obj.mealType);
      const json = {};
      res.data.mealTimePeriod.forEach(item => {
        json[item.mealPeriodType] = mealSections[item.mealPeriodType];
      });
      setMeals(json);
      form.setFieldsValue(obj);
    }
  };

  // 获取自提点列表
  const getPickSelf = async () => {
    const res = await apiEnterprisePickSelf({});
    if (res && res.data && res.data.records) {
      const data = res.data.records;
      setPickSelfList(
        data.map(item => ({
          value: item.id,
          label: item.pickselfName,
        })),
      );
    }
  };

  useEffect(() => {
    if (props.visible) {
      if (props.id) {
        getInfo();
      } else {
        setMealTypes([]);
        setMeals({});
        form.resetFields();
        getPickSelf();
      }
    } else {
      setMealTypes([]);
      setMeals({});
      form.setFieldsValue({});
    }
  }, [props.visible]);

  return (
    <Modal
      title="企业客户信息"
      open={props.visible}
      destroyOnClose
      maskClosable={false}
      width="900px"
      onOk={handleConfirm}
      onCancel={handleCancel}
    >
      <Form
        name="basicInfo"
        initialValues={{ mealTimePeriod: [{}, {}, {}] }}
        {...layout}
        form={form}
      >
        <Form.Item
          label="公司名称"
          name="name"
          rules={[{ required: true, message: '请输入公司名称!' }]}
        >
          <Input />
        </Form.Item>
        {!props.id && (
          <Form.Item label="企业取餐点" name="pickselfIds">
            <Select
              options={pickSelfList}
              mode="multiple"
              showSearch
              filterOption={(v, option) =>
                (option?.label ?? '').toLowerCase().includes(v.toLowerCase())
              }
            />
          </Form.Item>
        )}
        <Form.Item
          label="企业截止时间"
          name="endOrderTime"
          wrapperCol={{ span: 20 }}
          rules={[{ required: true, message: '请输入企业截止时间!' }]}
          extra={<span>企业员工下单的截至时间，仅支持正整数，单位为分钟。</span>}
        >
          <InputNumber min={0} max={600} addonAfter="分钟" />
        </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>
        <Form.List name="mealLimit">
          {fields => (
            <>
              {Object.keys(meals).map(meal => (
                <Form.Item label={`${mealSections[meal]}订单`} required wrapperCol={{ span: 20 }}>
                  <Form.List
                    name={`limit${meal}`}
                    key={`${meal}limit`}
                    required
                    wrapperCol={{ span: 20 }}
                  >
                    {fs => (
                      <Row key={`row${meal}`}>
                        {mealTypes.map((t, i) => (
                          <Col span={7} offset={i ? 1 : 0} key={t}>
                            <MealLimit value={t} label={mealType[t]} name={`${t}`} />
                          </Col>
                        ))}
                      </Row>
                    )}
                  </Form.List>
                </Form.Item>
              ))}
            </>
          )}
        </Form.List>
        <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;
