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

// 企业客户信息
const CustomerInfo = props => {
  const [meals, setMeals] = useState([]); // 选中的餐段
  const [selectedMealTypes, setSelectedMealTypes] = useState([]); // 选中的餐品类型
  const [pickSelfList, setPickSelfList] = useState({}); // 自提点列表
  const [visible, setVisible] = useState(false);
  const refForm = useRef();

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

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

  /*
   *  6. 表单提交
   */
  const submitForm = async () => {
    // 校验表单 并 转换成接口需要的数据
    const formData = refForm.current.validateFields();
    const data = await transformToApiParams(formData, selectedMealTypes, meals);
    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: '保存成功！' });
    }
  };

  // 改变餐品类型 (选自助餐必选外卖)
  const onChangeMealType = async ms => {
    try {
      // 编辑时，取消餐段需提示用户确认风险
      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');
      }

      refForm.current.setFieldsValue({
        mealType: ms,
      });
      setSelectedMealTypes(ms);
    } catch {
      refForm.current.setFieldsValue({
        mealType: selectedMealTypes,
      });
    }
  };
  /**
   * 改变餐段
   * @param {object} e 事件对象
   * meals: { 1: '早餐', 2: '午餐', 3: '晚餐' }
   */
  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);
    // 餐段都没选 则设置为空数组
    if (Object.keys(values).length === 0) {
      refForm.current.setFieldsValue({
        mealTimePeriod: null,
      });
    }
    // 触发验证当前自段 是否显示表单提示
    refForm.current.validateFields(['mealTimePeriod']);
  };

  // 获取表单信息
  const getInfo = async () => {
    const res = await apiEnterpriseInfo(props.id);
    if (res && res.data) {
      // 转换成表单需要的数据
      const formData = transformToFormData(res.data);
      setSelectedMealTypes(formData.mealType);
      setMeals(formData.mealTimePeriodMap);
      refForm.current.setFieldsValue(formData);
    }
  };

  useEffect(() => {
    if (props.visible) {
      // 如果有客户ID 则为编辑 需获取表单信息
      if (props.id) {
        getInfo();
      } else {
        // 新增的时候才获取自提点列表
        getPickSelf(setPickSelfList, setVisible);
      }
      setVisible(true);
    } else {
      setVisible(false);
    }
  }, [props.visible]);

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

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