/* eslint-disable no-unused-expressions */
import React, { useEffect, useRef, useState } from 'react';
import { notification } from 'antd';
import { unstable_batchedUpdates } from 'react-dom';
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 refForm = useRef(null);
  /**
   *  7. 表单关闭
   * @param {boolean} isRefresh 是否刷新列表
   */
  const closeModal = isRefresh => {
    if (!isRefresh && typeof props.onClose === 'function') {
      props.onClose(isRefresh === 0);
    }
  };

  /*
   *  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 () => {
    // if (!props.id) {
    //   return {};
    // }
    const res = await apiEnterpriseInfo(props.id);
    if (res && res.data) {
      // 转换成表单需要的数据
      const formData = transformVOToFormData(res.data);

      /**
       * 使用setTimeout 的原因是防止 setState的时候 refForm丢失引用
       * 导致 refForm.current.validateFields 报错
       * 先渲染完表单再setState
       * */
      // setTimeout(() => {
      //   // setState 会导致组件重新渲染 为了防止多次渲染 使用 unstable_batchedUpdates 之后
      //   // React 18 会优化该问题
      unstable_batchedUpdates(() => {
        // 选中的餐品类型
        setSelectedMealTypes(formData.mealType);
        // 选中的餐段
        setSelectedMealSections(formData.mealTimePeriodMap);
      });
      // });
      // return formData;
      refForm.current?.setFieldsValue?.(formData);
    }
    // return {};
  };

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

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

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