import React, { useEffect, useRef, useState } from 'react';
import { notification } from 'antd';
import { BetaSchemaForm } from '@ant-design/pro-components';
import { layout, getBaseFormItem } from './staticData';
import { checkConfirm, transformVOToFormData, transformFormDataToDTO } from './bll';
import { apiEnterpriseInfo, apiNewEnterprise, apiEditEnterprise } from './service';

// 企业客户信息
const CustomerInfo = props => {
  const [selectedMealSections, setSelectedMealSections] = useState([]); // 选中的餐段
  const [selectedMealTypes, setSelectedMealTypes] = useState([]); // 选中的餐品类型
  const [pageLoading, setPageLoading] = useState(false); // 页面加载状态
  const refForm = useRef();

  /**
   *  7. 表单关闭
   * @param {boolean} isRefresh 是否刷新列表
   */
  const closeModal = isRefresh => {
    if (typeof props.onClose === 'function') {
      props.onClose(!!isRefresh);
    }
    setSelectedMealTypes([]);
    setSelectedMealSections({});
    refForm.current.setFieldsValue({
      mealLimit: [],
    });
  };

  const onOpenChange = v => {
    if (!v) {
      closeModal(!1);
    }
  };

  /*
   *  6. 表单提交
   */
  const submitForm = async () => {
    // 校验表单
    const formData = await refForm.current.validateFields();
    // 转换成接口需要的数据
    const data = await transformFormDataToDTO(formData, selectedMealTypes, selectedMealSections);
    let api = apiNewEnterprise;
    // 如果有客户ID 则为编辑
    if (props.id) {
      data.id = props.id;
      api = apiEditEnterprise;
    }
    const resp = await api(data);
    if (resp && resp.data) {
      // 保存成功后刷新列表
      closeModal(!0);
      notification.success({ message: '保存成功！' });
    }
  };

  /**
   * 改变餐品类型 (选自助餐必选外卖，取消外卖必须取消自助餐)
   * @param {array} mt 选中的餐品类型 ['1', '2']
   * types: { 1: '外卖', 2: '自助餐', 4: '到店' }
   */
  const onChangeMealType = async mt => {
    try {
      // 编辑时，取消餐段需提示用户确认风险
      if (props.id && mt.length < selectedMealTypes.length) {
        await checkConfirm();
      }
      // 取消外卖，必须取消自助餐
      if (selectedMealTypes.includes('1') && !mt.includes('1')) {
        mt = mt.filter(item => item !== '2');
      }
      // 选择自助餐，必须选择外卖
      if (!selectedMealTypes.includes('1') && mt.includes('2')) {
        mt.push('1');
      }

      // 注意 须先set 再from.setFieldsValue 防止丢失数据
      setSelectedMealTypes(mt);
      refForm.current.setFieldsValue({
        mealType: mt,
      });
    } catch {
      refForm.current.setFieldsValue({
        mealType: selectedMealTypes,
      });
    }
  };
  /**
   * 改变餐段
   * @param {object} e 事件对象
   * selectedMealSections: { 1: '早餐', 2: '午餐', 4: '晚餐' }
   */
  const onChangeMealSection = e => {
    const { id, checked, label } = e?.target || {};
    const values = Object.assign({}, selectedMealSections);
    // 选中则添加到选中餐段中，否则删除
    if (checked) {
      values[id] = label;
    } else {
      delete values[id];
    }
    // 设置选中餐段
    setSelectedMealSections(values);
    // 餐段都没选 则设置为空数组
    if (Object.keys(values).length === 0) {
      refForm.current.setFieldsValue({
        mealTimePeriod: null,
      });
    }
    // 触发验证当前自段 是否显示表单提示
    refForm.current.validateFields(['mealTimePeriod']);
  };

  /**
   * 获取表单信息
   * 把接口数据转换成表单需要的数据格式
   */
  const getInfo = async () => {
    setPageLoading(true);
    const res = await apiEnterpriseInfo(props.id);
    setPageLoading(false);
    if (res && res.data) {
      // 转换成表单需要的数据
      const formData = transformVOToFormData(res.data);
      // 选中的餐品类型
      setSelectedMealTypes(formData.mealType);
      // 选中的餐段
      setSelectedMealSections(formData.mealTimePeriodMap);
      refForm.current.setFieldsValue(formData);
    }
  };

  useEffect(() => {
    if (props.visible) {
      // 如果有客户ID 则为编辑 需获取表单信息
      if (props.id) {
        getInfo();
      }
    }
  }, [props.visible]);

  const formItem = getBaseFormItem({
    onChangeMealType,
    onChangeMealSection,
    id: props.id,
    selectedMealSections,
    selectedMealTypes,
    form: refForm.current,
  });

  return (
    <BetaSchemaForm
      layoutType="ModalForm"
      title="企业客户信息"
      open={props.visible}
      width="900px"
      modalProps={{
        maskClosable: false,
        destroyOnClose: true,
        confirmLoading: pageLoading,
      }}
      formRef={refForm}
      onOpenChange={onOpenChange}
      layout="horizontal"
      {...layout}
      onFinish={submitForm}
      columns={formItem}
    />
  );
};
export default CustomerInfo;
