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 moment from 'moment';
import { jsonToArray } from '@/utils/utils';
import { layout, mealType, boolOptions, hideOptions, mealSections } from '../staticData/index';
import {
  apiEnterpriseInfo,
  apiNewEnterprise,
  apiEditEnterprise,
  apiEnterprisePickSelf,
} from '../service';
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 [selectedMealTypes, setSelectedMealTypes] = useState([]);
  const [pickSelfList, setPickSelfList] = useState([]);

  // 1. 表单展示
  // const formItem = [
  // {
  //   label: '企业名称',
  //   name: 'enterpriseName',
  //   rules: [{ required: true, message: '请输入企业名称' }],
  //   component: <Input placeholder="请输入企业名称" />,
  // },

  // 2. 预加载数据, 数据模型转换,用于表单回显

  // 3. 表单交互逻辑

  // 4. 表单校验
  const validateForm = async () => {
    const res = await form.validateFields();
    console.log(11, res);
    // TODO 其他校验
  };

  // 5. 数据模型转换, 表单到接口的转换, 可以用 lodash
  const tranformFormData = data => {};

  // 6. 表单关闭
  const closeModal = index => {
    if (props.onClose && typeof props.onClose === 'function') {
      props.onClose(!!index);
    }
  };

  // 7. 表单提交

  const sumbitForm = async () => {
    const valid = await validateForm();
    if (!valid) {
      return false;
    }
    return false;
    // const params = tranformFormData(res);
    // const resp = await apiNewEnterprise(params);
    // if (resp && resp.data) {
    //   // 保存成功后刷新列表
    //   closeModal(1);
    //   notification.success({ message: '保存成功！' });
    // }
  };

  // 校验时间
  const checkTime = (arr, curren, curName) => {
    let valid = false;
    arr.forEach(item => {
      if (curren < item.endTime) {
        valid = true;
        const name = meals[item.mealPeriodType];
        notification.error({ message: `${curName}起始时间不能早于${name}截止时间` });
      }
    });
    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,
        hidePrice: 0,
      },
      res,
    );
    const arr = [];
    let validTime = false;
    res.mealTimePeriod.forEach(item => {
      if (item && meals[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, meals[item.mealPeriodType])) {
          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 mealPeriodType = item.replace('limit', '');
      if (meals[mealPeriodType]) {
        const json = {
          mealPeriodType,
          limit: [],
        };
        Object.keys(res.mealLimit[item]).forEach(t => {
          if (selectedMealTypes.includes(t)) {
            json.limit.push({
              mealType: t,
              limit: res.mealLimit[item][t],
            });
          }
        });
        limits.push(json);
      }
    });
    if (limits.length < 1) {
      notification.error({ message: '请选择餐段配置！' });
      return;
    }
    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 && resp.data) {
      // 保存成功后刷新列表
      closeModal(1);
      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 => {
    console.log('mealTypes', selectedMealTypes, ms);
    try {
      // 编辑时，取消餐段，提示确认
      console.log('props.info :>> ', props.id);
      if (props.id && ms.length < selectedMealTypes.length) {
        await checkConfirm();
      }
      // 取消外卖，必须取消自助餐
      if (selectedMealTypes.includes('1') && !ms.includes('1')) {
        ms = ms.filter(item => item !== '2');
      }

      // 选择自助餐，必须选择外卖
      if (!selectedMealTypes.includes('1') && ms.includes('2')) {
        ms.push('1');
      }

      form.setFieldsValue({
        mealType: ms,
      });
      setSelectedMealTypes(ms);
    } catch {
      form.setFieldsValue({
        mealType: selectedMealTypes,
      });
    }
  };
  // 改变餐段
  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 {
        hideImage,
        hidePrice,
        id,
        name,
        mealLimit,
        mealTimePeriod = [],
        mealType: type,
        weekPreview,
      } = res.data;
      const formData = {
        id,
        name,
        weekPreview,
        mealType: type?.map(item => `${item}`) ?? [],
        hideInfo: [],
      };

      // 数据模型转换-隐藏信息
      if (+hidePrice) {
        formData.hideInfo.push('hidePrice');
      }
      if (+hideImage) {
        formData.hideInfo.push('hideImage');
      }

      // 数据模型转换-餐段配置,转为 {餐段:餐段名称}
      // 把mealTimePeriod按mealPeriodType转为map
      const mealTimePeriodMap = {};
      mealTimePeriod.forEach(item => {
        mealTimePeriodMap[item.mealPeriodType] = mealSections[item.mealPeriodType];
      });
      setMeals(mealTimePeriodMap);

      // 数据模型转换-餐段和时间配置, [{餐段, time}, {}, {}]
      const mealTimePeriodArr = Object.keys(mealSections).map(() => ({}));
      formData.mealTimePeriod = mealTimePeriodArr;
      mealTimePeriod.forEach(item => {
        if (!item) return;
        const index = Object.keys(mealSections).indexOf(`${item.mealPeriodType}`);
        if (index > -1) {
          formData.mealTimePeriod[index] = {
            mealPeriodType: `${item.mealPeriodType}`,
            time: [
              moment(`${moment().format('YYYY-MM-DD')} ${item.beginTime}`),
              moment(`${moment().format('YYYY-MM-DD')} ${item.endTime}`),
            ],
          };
        }
      });

      // 数据模型转换-消费限额, 转为{餐段: {餐品类型: 限额}}
      const mealLimitMap = {};
      mealLimit.forEach(item => {
        mealLimitMap[`limit${item.mealPeriodType}`] = {};
        item.limit.forEach(t => {
          mealLimitMap[`limit${item.mealPeriodType}`][t.mealType] = t.limit;
        });
      });
      formData.mealLimit = mealLimitMap;

      setSelectedMealTypes(formData.mealType);
      console.log('formData :>> ', formData);
      form.setFieldsValue(formData);
    }
  };

  // 获取自提点列表
  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 {
        setSelectedMealTypes([]);
        setMeals({});
        form.resetFields();
        getPickSelf();
      }
    } else {
      setSelectedMealTypes([]);
      setMeals({});
      form.setFieldsValue({});
    }
  }, [props.visible]);

  return (
    <Modal
      title="企业客户信息"
      open={props.visible}
      destroyOnClose
      maskClosable={false}
      width="900px"
      onOk={sumbitForm}
      onCancel={() => closeModal(0)}
    >
      <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"
            rules={[{ required: true, type: 'array', message: '请选择企业取餐点!' }]}
          >
            <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>
        <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}`}>
                        {selectedMealTypes.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;
