import { RESPONSE_CODE } from '@/constants/enum';
import {
  postCanrdApiUserAddressList,
  postCanrdApiUserList,
  postKingdeeRepCustomerDetail,
  postKingdeeRepMaterial,
  postKingdeeRepMaterialUnit,
  postKingdeeRepMeasureUnit,
  postServiceOrderAddOrder,
  postServiceOrderAfterSalesQuerySnapshotOrder,
  postServiceOrderApplyAfterSales,
  postServiceOrderApplyModify,
  postServiceOrderQuerySalesCode,
  postServiceOrderUpdateOrder,
} from '@/services';
import {
  FloatAdd,
  FloatMul,
  enumToSelect,
  getAliYunOSSFileNameFromUrl,
  getUserInfo,
} from '@/utils';
import { getDefaultString } from '@/utils/StringUtil';
import { getTeacherCustomFieldNumber } from '@/utils/kingdee';
import {
  DrawerForm,
  FormListActionType,
  ProCard,
  ProFormDateTimePicker,
  ProFormDigit,
  ProFormList,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProFormUploadDragger,
} from '@ant-design/pro-components';
import { Button, Form, Modal, message } from 'antd';
import { cloneDeep } from 'lodash';
import { useEffect, useRef, useState } from 'react';
import {
  AFTE_SALES_PLAN_OPTIONS,
  INVOCING_STATUS_OPTIONS,
  INVOCING_STATUS_OPTIONS_OLD,
  PAYEE_OPTIONS,
  PAYMENT_CHANNEL_OPTIONS,
  PAYMENT_METHOD_OPTIONS,
  PRODUCT_BELONG_DEPARTMENT_OPTIONS,
  SHIPPING_WAREHOUSE_OPTIONS,
} from '../constant';
import KingdeeCustomerModal from './KingdeeCustomerModal';

export default ({ onClose, data, subOrders, orderOptType }) => {
  const [invoicingStatus, setInvoicingStatus] = useState('');
  const [salesCodeOptions, setSalesCodeOptions] = useState([]);
  const [submitBtnLoading, setSubmitBtnLoading] = useState(false);
  const [drawerTitle, setDrawerTitle] = useState('');
  const [hasLocalData, setHasLocalData] = useState(false);
  // const [customer, setCustomer] = useState({});
  const [localSaveLoading, setLocalSaveLoading] = useState(false);
  const [kingdeeCstomerModalVisible, setKingdeeCstomerModalVisible] =
    useState(false);
  const [paymentMethod, setPaymentMethod] = useState('');
  const [customerRequestCount, setCustomerRequestCount] = useState(0);
  const [
    productParametersDisabledFlagList,
    setProductParametersDisabledFlagList,
  ] = useState([]);
  // const [productInvStockOptionsList, setProductInvStockOptionsList] = useState(
  //   [],
  // ); //商品的仓库选项
  const [productUnitOptionsList, setProductUnitOptionsList] = useState([]); //商品的单位选项
  // const [productCustomerContactOptions, setProductCustomerContactOptions] =
  //   useState([]); //客户的收货人选项
  const [form] = Form.useForm<{
    isLocalData: boolean;
    salesCode: '';
    customerName: '';
    customerContactNumber: '';
    institution: '';
    institutionContactName: '';
    customerShippingAddress: '';
    totalPayment: '';
    paymentChannel: '';
    paymentMethod: '';
    productBelongBusiness: '';
    invoicingStatus: '';
    invoiceIdentificationNumber: '';
    invoicingTime: '';
    bank: '';
    bankAccountNumber: '';
    deleteSubOrderLists: [];
    filePaths: [];
    notes: '';
    invoiceFirst: boolean;
    list: [
      {
        productCode: '';
        productName: '';
        quantity: '';
        productPrice: '';
        parameters: '';
        subOrderPayment: '';
        unit: '';
        serialNumber: '';
        notes: '';
      },
    ];
  }>();

  let copyData = cloneDeep(data);

  let originSubOrders = cloneDeep(subOrders);

  /**
   * 获取当前的操作类型boolean值
   * @param type 操作类型,如果与当前匹配返回true
   */
  function optType(type: string) {
    return orderOptType === type;
  }

  /**
   * 获取销售代码枚举,在复制和编辑的时候判断是否为旧的代码
   */
  const getSalesCodeOptions = async () => {
    const res = await postServiceOrderQuerySalesCode();
    let options = res.data?.map((item) => {
      return {
        label: item.userName,
        value: item.userName,
        number: item.number,
      };
    });
    setSalesCodeOptions(options);

    if (optType('copy') || optType('edit')) {
      let includeFlag = false;
      //销售代码校验,如果是旧的销售代码,则提示并清空
      for (let option of options) {
        if (option.value === copyData.salesCode) {
          includeFlag = true;
        }
      }

      if (!includeFlag) {
        form.resetFields(['salesCode']);
        message.warning('检测到销售代码为旧的,已清空,请重新选择');
      }
    }
  };

  /**
   * 选择客户后自动为收货人Select添加选项,填充课题组和单位信息
   * @param option 客户选项
   */
  async function autoFillCustomerContactSelectOptions(customerId: any) {
    //查询单位详细信息
    let res = await postKingdeeRepCustomerDetail({
      data: {
        id: customerId,
      },
    });

    //erp客户名称
    form.setFieldValue('erpCustomerName', res?.name);

    //重新设置当前option
    form.setFieldValue('erpCustomerId', {
      label: res?.name,
      value: res?.id,
      id: res?.id,
    });

    //查询客户自定义字段,课题组
    let entity_number = await getTeacherCustomFieldNumber();

    //在单位详细信息中拿到自定义字段的值
    let customField = res?.custom_field;
    if (customField) {
      let teacherName = customField[entity_number];
      //填充到课题组老师表单字段中
      form.setFieldValue('institutionContactName', teacherName);
    }

    //单位名称,从客户名称中获取,客户名称规则<单位名称>-<联系人名称和电话>
    let namePortions = res?.name?.split('-');
    if (namePortions && namePortions.length >= 2) {
      form.setFieldValue('institution', namePortions[0]);
    }

    //如果原来的收货信息没有包含在这次查询出来的收货人选项中,那么清除原来的收货人信息
    let existFlag = false;

    //填充收货人选项
    // let newProductCustomerContactOptions = res?.bomentity?.map((item) => {
    //   let address =
    //     item.contact_person + ',' + item.mobile + ',' + item.contact_address;
    //   if (address === data.contactAddress) {
    //     existFlag = true;
    //   }
    //   return { ...item, label: address, value: address };
    // });

    // setProductCustomerContactOptions(newProductCustomerContactOptions);

    if (!existFlag) {
      //清空原来的收货人信息
      form.setFieldValue('customerShippingAddress', undefined);
      form.setFieldValue('customerContactNumber', undefined);
      form.setFieldValue('customerName', undefined);
      form.setFieldValue('erpCustomerAddress', undefined);
    }
  }

  /**
   * 回显金蝶信息
   */
  // async function showKindeeInfo() {
  //   //客户信息
  //   if (copyData.customerId) {
  //     //客户回显
  //     autoFillCustomerContactSelectOptions(copyData.customerId);
  //   }

  //   //商品单位回显
  //   let list = copyData?.subOrderInformationLists;
  //   if (list) {
  //     let newProductUnitOptionsList = [...productUnitOptionsList];
  //     for (let i = 0; i < list.length; i++) {
  //       newProductUnitOptionsList[i] = [
  //         { label: list[i].unit, value: list[i].unitId },
  //       ];
  //     }
  //     setProductUnitOptionsList(newProductUnitOptionsList);
  //   }
  // }

  /**
   * 构建回显数据
   */
  function buildOrderData() {
    // let mainInfoDisbled = optType('edit');
    if (!optType('add')) {
      if (subOrders !== undefined && subOrders.length > 0) {
        copyData.subOrderInformationLists = subOrders;
      }

      //如果是复制,需要开票,不回显是否需要开票字段
      if (optType('copy')) {
        if (copyData.invoicingStatus === 'INVOICED') {
          copyData.invoicingStatus = undefined;

          //复制的时候,如果是不需要开票,要把开票信息清空
          if (copyData.invoicingStatus === 'UN_INVOICE') {
            copyData.invoiceIdentificationNumber = undefined;
          }
        }
      }
      //主订单事业部默认显示子订单第一条的事业部
      copyData.productBelongBusiness =
        copyData.subOrderInformationLists[0].productBelongBusiness;
      copyData.paymentMethod =
        copyData.subOrderInformationLists[0].paymentMethod;
      copyData.paymentChannel =
        copyData.subOrderInformationLists[0].paymentChannel;
      copyData.invoicingStatus =
        copyData.subOrderInformationLists[0].invoicingStatus;

      copyData.customerNameString = copyData.customerName;

      setPaymentMethod(copyData.paymentMethod);

      //子订单数据处理:子订单在表单中的命名为list
      let i = 0;
      let newList = copyData.subOrderInformationLists?.map((item) => {
        item.filePaths = item.listAnnex?.map((path) => {
          return {
            uid: i++,
            name: getAliYunOSSFileNameFromUrl(path),
            status: 'uploaded',
            url: path,
            response: { data: [path] },
          };
        });
        return item;
      });

      copyData['list'] = newList;

      //发货仓库处理
      for (let listItem of copyData.list) {
        if (listItem.shippingWarehouse === null) {
          listItem.shippingWarehouse = 'DALANG_WAREHOUSE';
        }
      }
      setInvoicingStatus(copyData.invoicingStatus);
      form.setFieldsValue({ ...copyData });
      //如果是新建,需要清空list
      if (optType('add')) {
        form.resetFields(['list']);
      }

      if (!optType('after-sales-check')) {
        // showKindeeInfo();
      }
    }
  }

  /**
   * 获取旧订单信息
   * @param id
   */
  async function getOldOrderData(id: any) {
    let res = await postServiceOrderAfterSalesQuerySnapshotOrder({
      data: {
        mainOrderId: id,
      },
    });

    copyData = res.data.mainOrder;
    copyData.subOrderInformationLists = res.data.subOrders;
    originSubOrders = res.data.subOrders;

    //客户显示
    form.setFieldValue('erpCustomerId', {
      label: copyData.erpCustomerName,
      value: copyData.customerId,
    });

    buildOrderData();
  }

  /**
   *
   * @returns 获取开票选项
   */
  function getInvoicingSelect() {
    if (optType('edit') || optType('after-sales-check')) {
      return enumToSelect(INVOCING_STATUS_OPTIONS_OLD);
    }
    return enumToSelect(INVOCING_STATUS_OPTIONS);
  }

  const fileList: any = [];

  useEffect(() => {
    //弹窗标题
    if (optType('add')) {
      setDrawerTitle('新增订单');
    }
    if (optType('copy')) {
      setDrawerTitle('复制订单');
    }
    if (optType('edit')) {
      setDrawerTitle('修改订单');
    }
    if (optType('after-sales')) {
      setDrawerTitle('申请售后');
    }
    if (optType('after-sales-check')) {
      setDrawerTitle('订单信息');
    }
    if (optType('order-change-normal')) {
      setDrawerTitle('申请修改');
    }
  }, []);

  const actionRef = useRef<
    FormListActionType<{
      name: string;
    }>
  >();

  useEffect(() => {
    form.setFieldsValue({ ...data });
    //如果是新建,需要清空list
    if (optType('add')) {
      form.resetFields(['list']);
    }
  }, [data]);

  /**
   * 所属部门修改事件
   * 如果选择实验耗材事业部,那么发货仓库默认是大朗仓库
   * @param val
   */
  function productBelongBusinessChange(val: any, index: any) {
    if (val === 'EXPERIMENTAL_CONSUMABLES') {
      let list = form.getFieldValue('list');
      let currentData = list[index];
      if (currentData) {
        currentData.shippingWarehouse = 'DALANG_WAREHOUSE';
        form.setFieldValue('list', list);
        message.info('已默认选择大朗仓库');
      }
    }
  }

  /**
   *
   * @param option 商品名称所对应的商品数据
   * @param currentRowData list中当前行的数据
   */
  async function autoFillProductInfo(
    option: any,
    currentRowData: any,
    index: any,
  ) {
    let newProductParametersDisabledFlagList = [
      ...productParametersDisabledFlagList,
    ];
    let newProductUnitOptionsList = [...productUnitOptionsList];
    newProductUnitOptionsList[index] = [];

    //是新增商品
    if (option.type === 'add') {
      //商品参数开放权限可以编辑
      newProductParametersDisabledFlagList[index] = false;

      //清空商品信息
      let copyList = form.getFieldValue('list');
      let currentData = copyList[index];
      currentData.productCode = undefined;
      currentData.parameters = undefined;
      currentData.unit = undefined;
      currentData.subOrderPayment = undefined;
      currentData.quantity = undefined;
      currentData.notes = undefined;
      currentData.productPrice = undefined;

      currentData.unitId = undefined;
      currentData.materialId = undefined;
      form.setFieldValue('list', copyList);

      //todo 查询计量单价列表
      if (false) {
        let res = await postKingdeeRepMeasureUnit({ data: {} });
        if (res && res?.rows) {
          for (let row of res?.rows) {
            newProductUnitOptionsList[index].push({
              label: row.name,
              value: row.id,
            });
          }
        }
      }
    } else {
      //选择的是已有的商品,进行内容自动填充
      let copyList = form.getFieldValue('list');
      let currentData = copyList[index];
      currentData.productCode = option?.number;
      currentData.parameters = option?.model;
      currentData.unit = option?.base_unit_name;

      //商品id
      currentData.materialId = option?.id;

      //单位
      currentData.unit = option.base_unit_name;
      currentData.unitId = option.base_unit_id;

      form.setFieldValue('list', copyList);

      //商品所在的仓库选项填充
      // let res = await postKingdeeRepMaterialStock({
      //   data: {
      //     material_id: option.id,
      //   },
      // });
      // let newProductInvStockOptionsList = [...productInvStockOptionsList];
      // newProductInvStockOptionsList[index] = res?.rows?.map((item) => {
      //   return { label: item.inv_stock, value: item.inv_stock_id };
      // });
      // setProductInvStockOptionsList(newProductInvStockOptionsList);

      //商品单位填充,查询商品单位列表
      let res = await postKingdeeRepMaterialUnit({
        data: { material_id: option.id },
      });
      if (res && res.rows) {
        for (let row of res.rows) {
          newProductUnitOptionsList[index].push({
            label: row.unit_name,
            value: row.unit_id,
          });
        }
      }
      //商品参数不允许编辑
      newProductParametersDisabledFlagList[index] = true;
    }

    setProductParametersDisabledFlagList(newProductParametersDisabledFlagList);
    setProductUnitOptionsList(newProductUnitOptionsList);
  }

  /**
   * 选择收货人后自动填充信息
   * @param option 收货人信息
   */
  async function autoFillCustomerInfo(option: any) {
    if (option === undefined || option === null || option.type === 'add') {
      form.setFieldValue('customerShippingAddress', undefined);
      form.setFieldValue('customerContactNumber', undefined);
      form.setFieldValue('institution', undefined);
      form.setFieldValue('institutionContactName', undefined);
      form.setFieldValue('customerShippingAddress', undefined);

      if (option !== undefined && option !== null) {
        form.setFieldValue('customerNameString', option.name);
      }
    } else {
      form.setFieldValue('customerShippingAddress', option.fullAddress);
      form.setFieldValue('customerContactNumber', option.phone);
      form.setFieldValue('institution', option.institution);
      form.setFieldValue(
        'institutionContactName',
        option.institutionContactName,
      );
      form.setFieldValue(
        'customerShippingAddress',
        getDefaultString(option.province) +
          getDefaultString(option.city) +
          getDefaultString(option.district) +
          getDefaultString(option.detail),
      );
      form.setFieldValue('customerNameString', option.realName);
    }

    //erp收货地址:需要与客户联系人中的地址一样:姓名,手机号,地址
    // form.setFieldValue('contactAddress', option.value);
  }

  /**
   * 填充销售代表的信息
   * @param option
   */
  function autoFillSalesInfo(option: any) {
    //销售代表对应职员编码填充
    form.setFieldValue('empNumber', option.number);
  }

  /**
   * todo 选择商品单位后自动填充
   * @param option
   * @param index
   */
  // function autoFillUnit(option: any, index: any) {
  //   let copyList = form.getFieldValue('list');
  //   let currentData = copyList[index];
  //   currentData.unit = option?.label;
  //   form.setFieldValue('list', copyList);
  // }

  /**
   * 计算子订单金额
   * @param listMeta 当前商品信息
   */
  function computeSubOrderPayment(listMeta: any) {
    let quantity = listMeta?.record?.quantity;
    let productPrice = listMeta?.record?.productPrice;
    quantity = quantity === '' || quantity === undefined ? 0 : quantity;
    productPrice =
      productPrice === '' || productPrice === undefined ? 0 : productPrice;
    quantity = parseInt(quantity);
    productPrice = parseFloat(productPrice);

    listMeta.subOrderPayment = FloatMul(quantity, productPrice);
    let list = form.getFieldValue('list');
    list[listMeta?.index].subOrderPayment = FloatMul(quantity, productPrice);
    form.setFieldValue('list', list);
  }

  /**
   * 计算支付总额
   */
  function computeTotalPayment() {
    let list = form.getFieldValue('list');
    let totalPayment = 0;
    list?.forEach((subOrder: any) => {
      let subOrderPayment = subOrder?.subOrderPayment;
      if (subOrderPayment !== '' && subOrderPayment !== undefined) {
        totalPayment = FloatAdd(subOrderPayment, totalPayment);
      }
    });
    form.setFieldValue('totalPayment', totalPayment);
  }

  /**
   * 检查客户是否可以编辑
   * @returns
   */
  // const customerEditable = () => {
  //   let erpCustomerId = form.getFieldValue('erpCustomerId');
  //   if (
  //     optType('after-sales-check') ||
  //     erpCustomerId === null ||
  //     erpCustomerId === undefined
  //   ) {
  //     return false;
  //   }

  //   return true;
  // };

  /**
   * 是否有草稿
   */
  function checkHasLocalData() {
    let preOrderData = localStorage.getItem('preOrderData');
    let hasLocalData =
      preOrderData !== null &&
      preOrderData !== undefined &&
      preOrderData !== '';
    setHasLocalData(hasLocalData);
    return hasLocalData;
  }

  /**
   * 保存表单数据到本地
   */
  function saveFormDataToLocal() {
    let preOrderData = localStorage.getItem('preOrderData');
    let values = form.getFieldsValue();
    values.isLocalData = true; //标识为本地草稿数据
    let formData = JSON.stringify(values);

    //检查本地是否已有数据
    if (preOrderData) {
      Modal.confirm({
        title: '提示',
        content: '检测到本地有订单数据,是否覆盖?',
        onOk: () => {
          localStorage.setItem('preOrderData', formData);
          message.success('本地保存成功');
        },
        onCancel: () => {
          message.info('取消保存');
        },
      });
    } else {
      localStorage.setItem('preOrderData', formData);
      message.success('本地保存成功');
    }

    checkHasLocalData();
    setLocalSaveLoading(false);
  }

  /**
   * 使用草稿数据
   */
  function useLocalFormData() {
    let preOrderData = localStorage.getItem('preOrderData');
    if (preOrderData) {
      let formData = JSON.parse(preOrderData);
      form.setFieldsValue(formData);
      setPaymentMethod(formData.paymentMethod);
    }
  }

  /**
   * 刪除草稿数据
   */
  function removeLocalFormData() {
    localStorage.removeItem('preOrderData');
  }

  useEffect(() => {
    checkHasLocalData();
    getSalesCodeOptions();
    if (optType('after-sales-check')) {
      getOldOrderData(data.id);
    } else {
      buildOrderData();
    }
  }, []);

  return (
    <>
      <DrawerForm<{
        isLocalData: any;
        deleteSubOrderLists: any;
        name: string;
        company: string;
      }>
        open
        width="35%"
        title={drawerTitle}
        resize={{
          onResize() {
            console.log('resize!');
          },
          maxWidth: window.innerWidth * 0.8,
          minWidth: 400,
        }}
        onFinishFailed={() => {
          message.error('表单项存在错误,请检查');
          setSubmitBtnLoading(false);
        }}
        submitter={{
          render: (props) => {
            return [
              <Button
                key="cancel"
                onClick={() => {
                  onClose();
                }}
              >
                取消
              </Button>,
              <Button
                key="localSave"
                loading={localSaveLoading}
                hidden={!optType('add') && !optType('copy')}
                onClick={() => {
                  setLocalSaveLoading(true);
                  saveFormDataToLocal();
                }}
              >
                本地保存
              </Button>,
              <Button
                key="ok"
                type="primary"
                loading={submitBtnLoading}
                disabled={optType('after-sales-check')}
                onClick={() => {
                  setSubmitBtnLoading(true);
                  props.submit();
                }}
              >
                提交
              </Button>,
            ];
          },
        }}
        form={form}
        autoFocusFirstInput
        drawerProps={{
          destroyOnClose: true,
          maskClosable: false,
          extra: [
            <Button
              key="useLocalData"
              hidden={!hasLocalData}
              type="link"
              onClick={() => {
                useLocalFormData();
              }}
            >
              使用草稿
            </Button>,
          ],
        }}
        submitTimeout={2000}
        onFinish={async (values) => {
          let res = {};
          //附件处理
          let list = values.list;
          // console.log(list);
          list = list.map((item) => {
            item.filePaths = item.filePaths?.map((file) => {
              return { url: file.response.data[0] };
            });
            return item;
          });

          values.list = list;
          values.institution = values.institution?.trim();
          values.institutionContactName = values.institutionContactName?.trim();
          values.customerName = values.customerNameString.trim();

          if (typeof values.erpCustomerId !== 'string') {
            values.erpCustomerId = values.erpCustomerId?.id;
          }

          //新增
          if (optType('add') || optType('copy')) {
            res = await postServiceOrderAddOrder({ data: values });
          }
          //修改或者申请售后或者申请修改
          if (
            optType('edit') ||
            optType('after-sales') ||
            optType('order-change-normal')
          ) {
            //计算已删除的子订单id

            let originIds = [];
            if (originSubOrders !== undefined && originSubOrders.length > 0) {
              originIds = originSubOrders?.map((item) => {
                return item.id;
              });
            }

            const curIds = form.getFieldValue('list')?.map((item) => {
              return item.id;
            });
            let diff = originIds.filter((item) => !curIds.includes(item));
            values.deleteSubOrderLists = diff;

            if (optType('edit')) {
              res = await postServiceOrderUpdateOrder({ data: values });
            }

            values.applyType = orderOptType;
            if (optType('after-sales')) {
              values.filePaths = values.filePaths?.map((file) => {
                return { url: file.response.data[0] };
              });
              res = await postServiceOrderApplyAfterSales({ data: values });
            }

            if (optType('order-change-normal')) {
              values.filePaths = values.filePaths?.map((file) => {
                return { url: file.response.data[0] };
              });
              res = await postServiceOrderApplyModify({ data: values });
            }
          }

          if (res.result === RESPONSE_CODE.SUCCESS) {
            message.success(res.message);
            // 不返回不会关闭弹框
            onClose(true);

            //判断保存的数据是否是本地草稿,是的话将草稿删除
            let isLocalData = form.getFieldValue('isLocalData');
            if (isLocalData) {
              removeLocalFormData();
              checkHasLocalData();
            }

            return true;
          }

          setSubmitBtnLoading(false);
        }}
        onOpenChange={(val) => {
          return !val && onClose();
        }}
      >
        {optType('after-sales') ? (
          <>
            <h2>售后信息</h2>
            <ProFormSelect
              key="key"
              label="售后方案"
              width="lg"
              showSearch
              name="afterSalesPlan"
              options={enumToSelect(AFTE_SALES_PLAN_OPTIONS)}
              placeholder="请搜索"
              rules={[{ required: true, message: '售后方案必填' }]}
            ></ProFormSelect>
            <ProFormTextArea
              width="lg"
              label="售后原因"
              name="afterSalesNotes"
              rules={[{ required: true, message: '售后原因必填' }]}
            />
            <ProFormUploadDragger
              key="filePaths"
              label="售后附件"
              name="filePaths"
              action="/api/service/order/fileProcess"
              fieldProps={{
                headers: { Authorization: localStorage.getItem('token') },
              }}
            />
          </>
        ) : (
          ''
        )}

        <h2>订单基本信息</h2>
        <ProFormText
          key="id"
          name="id"
          width="lg"
          disabled
          label="id"
          placeholder="id"
          hidden
        />
        <ProFormText
          key="empNumber"
          name="empNumber"
          width="lg"
          label="销售职员编码"
          placeholder="销售职员编码"
          hidden
        />
        <ProFormSelect
          name="salesCode"
          key="salesCode"
          width="lg"
          showSearch
          label="销售代表"
          placeholder="请输入销售代表"
          rules={[{ required: true, message: '销售代表必填' }]}
          options={salesCodeOptions}
          onChange={(_, option) => {
            autoFillSalesInfo(option);
          }}
          disabled={optType('after-sales-check')}
        />
        <ProFormText
          key="erpCustomerName"
          name="erpCustomerName"
          hidden
        ></ProFormText>
        <ProFormText
          key="customerNameString"
          name="customerNameString"
          hidden
        ></ProFormText>

        <ProFormText
          key="contactAddress"
          name="contactAddress"
          hidden
        ></ProFormText>

        <ProFormSelect
          key="customerName"
          label="收货人"
          width="lg"
          showSearch
          name="customerName"
          placeholder="请选择收货人"
          rules={[{ required: true, message: '收货人必填' }]}
          onChange={(_, option) => {
            autoFillCustomerInfo(option);
          }}
          fieldProps={{
            filterOption() {
              return true;
            },
            optionItemRender(item: any) {
              if (item.type === 'add') {
                return (
                  <div title={item.name + '(新增客户)'}>
                    <span style={{ color: '#333333' }}>{item.name}</span>
                    {' | '}
                    <span style={{ color: 'orange' }}>自定义</span>
                  </div>
                );
              }

              let title = '';
              let spanText = '';
              let realName = item.realName;
              let phone = item.phone;
              let province = item.province;
              let city = item.city;
              let district = item.district;
              let detail = item.detail;
              let institution = item.institution;
              let institutionContactName = item.institutionContactName;

              title =
                getDefaultString(realName) +
                '|' +
                getDefaultString(phone) +
                '|' +
                getDefaultString(institution) +
                '|' +
                getDefaultString(institutionContactName) +
                '|' +
                getDefaultString(province) +
                getDefaultString(city) +
                getDefaultString(district) +
                getDefaultString(detail);

              spanText =
                getDefaultString(realName) +
                '|' +
                getDefaultString(phone) +
                '|' +
                getDefaultString(institution) +
                '|' +
                getDefaultString(institutionContactName);
              return (
                <div title={title}>
                  <span style={{ color: '#333333' }}>{spanText}</span>
                </div>
              );
            },
          }}
          debounceTime={1000}
          request={async (value, {}) => {
            const keywords = value.keyWords;
            const res = await postCanrdApiUserAddressList({
              data: { keywords: keywords },
            });
            let options = res?.data?.map((c: any) => {
              return {
                ...c,
                label: c.name,
                value: c.id,
                key: c.id,
              };
            });
            console.log(form.getFieldsValue());
            console.log(form.getFieldValue('customerName'));
            //判断如果是在修改或者复制,那么第一次请求的时候,默认生成当前收货人信息的option
            let realName = form.getFieldValue('customerName');
            let detail = form.getFieldValue('customerShippingAddress');
            let institution = form.getFieldValue('institution');
            let institutionContactName = form.getFieldValue(
              'institutionContactNam',
            );
            if (customerRequestCount === 0) {
              setCustomerRequestCount(1);
              options.push({
                label: realName,
                value: realName,
                key: realName,
                realName: realName,
                detail: detail,
                institution: institution,
                institutionContactName: institutionContactName,
              });
            }
            //第一个商品默认为要新增客户
            if (keywords.trim() !== '') {
              options.unshift({
                name: keywords,
                type: 'add',
                label: keywords,
                value: 3.1415926,
                key: keywords,
              });
            }

            return options;
          }}
        />

        <ProFormText
          width="lg"
          key="customerContactNumber"
          name="customerContactNumber"
          label="联系方式"
          placeholder="请输入联系方式"
          rules={[{ required: true, message: '联系方式必填' }]}
        />
        <ProFormText
          width="lg"
          key="institution"
          name="institution"
          label="单位"
          placeholder="请输入单位"
          rules={[{ required: true, message: '单位必填' }]}
        />
        <ProFormText
          width="lg"
          key="institutionContactName"
          name="institutionContactName"
          label="课题组"
          placeholder="请输入课题组"
          rules={[{ required: true, message: '课题组必填' }]}
        />
        <ProFormTextArea
          width="lg"
          key="customerShippingAddress"
          name="customerShippingAddress"
          label="收货地址"
          placeholder="请输入收货地址"
          rules={[{ required: true, message: '收货地址必填' }]}
        />
        <div id="total-payment">
          <ProFormDigit
            name="totalPayment"
            width="lg"
            key="totalPayment"
            label="支付总额(¥)"
            rules={[
              { required: true, message: '支付总额必填' },
              {
                validator: (_, value) => {
                  if (value <= 0) {
                    return Promise.reject(
                      new Error(
                        '支付总额必须大于0 (扣预存的订单现在也必须填写实际金额)',
                      ),
                    );
                  }
                  return Promise.resolve();
                },
              },
            ]}
            tooltip="点击计算,合计所有子订单金额"
            fieldProps={{
              addonAfter: (
                <Button
                  className="rounded-l-none"
                  type="primary"
                  disabled={optType('after-sales-check')}
                  onClick={computeTotalPayment}
                >
                  计算
                </Button>
              ),
            }}
            disabled={optType('after-sales-check')}
          />
        </div>

        <ProFormSelect
          placeholder="请输入支付渠道"
          name="paymentChannel"
          width="lg"
          key="paymentChannel"
          label="支付渠道"
          options={enumToSelect(PAYMENT_CHANNEL_OPTIONS)}
          rules={[{ required: true, message: '支付渠道必填' }]}
          disabled={optType('after-sales-check')}
        />
        <ProFormSelect
          placeholder="请输入支付方式"
          name="paymentMethod"
          width="lg"
          key="paymentMethod"
          label="支付方式"
          onChange={(val: any) => {
            setPaymentMethod(val);
          }}
          options={enumToSelect(PAYMENT_METHOD_OPTIONS)}
          rules={[{ required: true, message: '支付方式必填' }]}
          disabled={optType('after-sales-check')}
        />
        <ProFormSelect
          name="prepaidUid"
          key="prepaidUid"
          width="lg"
          hidden={paymentMethod !== 'WITHHOLDING_ADVANCE_DEPOSIT'}
          showSearch
          label="预存账号"
          onChange={(option: any) => {
            form.setFieldValue('prepaidAmount', option.nowMoney);
          }}
          placeholder="请选择预存账号"
          rules={[
            {
              required: paymentMethod === 'WITHHOLDING_ADVANCE_DEPOSIT',
              message: '支付方式为扣预存时,预存账号必填',
            },
          ]}
          fieldProps={{
            filterOption() {
              return true;
            },
            optionItemRender(item) {
              let name =
                item.label +
                ' | ' +
                item.institution +
                ' | ' +
                item.nowMoney +
                '¥' +
                ' | ' +
                item.phone;
              return (
                <div title={name}>
                  <span style={{ color: '#333333' }}>{name}</span>
                </div>
              );
            },
          }}
          debounceTime={1000}
          request={async (value, {}) => {
            const keywords = value.keyWords;
            const res = await postCanrdApiUserList({
              data: { keywords: keywords, pageSize: 1000000 },
            });
            let options = res?.data?.data?.map((c: any) => {
              return {
                ...c,
                label: c.realName,
                value: c.uid,
                key: c.uid,
              };
            });
            return options;
          }}
        />
        <ProFormSelect
          placeholder="选择是否需要开票"
          name="invoicingStatus"
          width="lg"
          key="invoicingStatus"
          label="是否需要开票"
          options={getInvoicingSelect()}
          disabled={optType('after-sales-check')}
          onChange={(_, option) => {
            setInvoicingStatus(option.value);
            if (option.value === 'UN_INVOICE') {
              form.setFieldValue('invoiceIdentificationNumber', undefined);
              form.setFieldValue('bank', undefined);
              form.setFieldValue('bankAccountNumber', undefined);
              form.setFieldValue('invoiceFirst', false);
            }
          }}
          rules={[{ required: true, message: '是否需要开票必填' }]}
        />
        <ProFormSelect
          placeholder="是否开票后发货"
          name="invoiceFirst"
          width="lg"
          key="invoiceFirst"
          label="是否开票后发货"
          disabled={optType('after-sales-check')}
          hidden={invoicingStatus === 'UN_INVOICE'}
          options={[
            {
              value: true,
              label: '是',
            },
            {
              value: false,
              label: '否',
            },
          ]}
        />

        <ProFormSelect
          placeholder="收款单位"
          name="receivingCompany"
          width="lg"
          key="receivingCompany"
          showSearch
          label="开票收款单位"
          tooltip="财务开票将依据这个字段,选择对应的公司开票"
          options={enumToSelect(PAYEE_OPTIONS)}
          disabled={optType('after-sales-check')}
          hidden={invoicingStatus === 'UN_INVOICE'}
        />

        <ProFormTextArea
          width="lg"
          name="invoiceIdentificationNumber"
          label="开票信息"
          key="invoiceIdentificationNumber"
          disabled={optType('after-sales-check')}
          hidden={invoicingStatus === 'UN_INVOICE'}
          placeholder="请输入开票信息"
          rules={[
            {
              required: invoicingStatus === 'UN_INVOICE' ? false : true,
              message: '开票信息必填',
            },
          ]}
        />

        {getUserInfo().roleSmallVO?.code === 'admin' ? (
          <ProFormDateTimePicker
            width="lg"
            key="invoicingTime"
            name="invoicingTime"
            disabled={optType('after-sales-check')}
            hidden={invoicingStatus === 'UN_INVOICE'}
            label="开票时间"
            placeholder="请输入开票时间"
          />
        ) : (
          ''
        )}
        <ProFormText
          width="lg"
          name="bank"
          key="bank"
          label="开户银行"
          disabled={optType('after-sales-check')}
          hidden={invoicingStatus === 'UN_INVOICE'}
          placeholder="请输入开户银行"
        />
        <ProFormText
          width="lg"
          key="bankAccountNumber"
          name="bankAccountNumber"
          hidden={invoicingStatus === 'UN_INVOICE'}
          label="银行账号"
          disabled={optType('after-sales-check')}
          placeholder="请输入银行账号"
        />
        <ProFormTextArea
          width="lg"
          name="notes"
          label="备注"
          key="notes"
          disabled={optType('after-sales-check')}
          placeholder="请输入备注"
          rules={[
            {
              max: 1000, // 最大长度为1000个字符
              message: '备注不能超过1000个字符',
            },
            {
              validator: (rule, value) => {
                let totalPayment = form.getFieldValue('totalPayment');
                let list = form.getFieldValue('list');
                let reduce = list.reduce(
                  (sum, item) => FloatAdd(sum, item.subOrderPayment),
                  0,
                );
                console.log(reduce);
                console.log(totalPayment);
                if (reduce === totalPayment || value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('请填写订单金额不一致的原因'));
              },
            },
          ]}
        />

        <h2>商品信息</h2>
        <ProFormList
          creatorButtonProps={{ disabled: optType('after-sales-check') }}
          deleteIconProps={!optType('after-sales-check')}
          name="list"
          label=""
          copyIconProps={false} //复制按钮不显示
          initialValue={[
            {
              productCode: '',
              productName: '',
              quantity: '',
              productPrice: '',
              parameters: '',
              subOrderPayment: '',
            },
          ]}
          actionGuard={{
            beforeRemoveRow: async () => {
              return new Promise((resolve) => {
                let list = form.getFieldValue('list');
                if (list && list.length === 1) {
                  message.error('至少需要保留一个商品');
                  resolve(false);
                  return;
                }
                resolve(true);
              });
            },
          }}
          itemRender={(doms, listMeta) => {
            if (optType('edit')) {
              let i = 0;
              let defaultFileList = listMeta.record?.listAnnex?.map((annex) => {
                return {
                  uid: i++,
                  name: annex,
                  status: 'uploaded',
                  url: annex,
                  response: { data: [annex] },
                };
              });
              fileList[listMeta.index] = defaultFileList;
            }
            let itemFileList = fileList[listMeta.index];
            return (
              <ProCard
                bordered
                extra={doms.action}
                title={'商品' + (listMeta.index + 1)}
                style={{
                  marginBlockEnd: 8,
                }}
              >
                {[
                  <ProFormText
                    key={'material' + listMeta.index}
                    name="materialId"
                    hidden
                  ></ProFormText>,
                  <ProFormSelect
                    key="key"
                    label="商品名称"
                    width="lg"
                    showSearch
                    name="productName"
                    disabled={optType('after-sales-check')}
                    placeholder="请搜索商品"
                    tooltip="空格将作为或条件。例如输入[极片 电池],那么查找出来的将是包含[极片]或者包含[电池]的搜索结果"
                    rules={[{ required: true, message: '商品名称必填' }]}
                    onChange={(_, option) => {
                      autoFillProductInfo(option, listMeta, listMeta.index);
                    }}
                    initialValue={{
                      label: listMeta?.record?.productName,
                      value: listMeta?.record?.materialId,
                    }}
                    fieldProps={{
                      filterOption() {
                        return true;
                      },
                      optionItemRender(item) {
                        if (item.type === 'add') {
                          return (
                            <div title={item.name + '(新增商品信息)'}>
                              <span style={{ color: '#333333' }}>
                                {item.label}
                              </span>
                              {' | '}
                              <span style={{ color: 'orange' }}>新增商品</span>
                            </div>
                          );
                        }
                        return (
                          <div
                            title={
                              item.label +
                              ' | ' +
                              (item.model === undefined
                                ? '无参数'
                                : item.model) +
                              ' | ' +
                              item.base_unit_name
                            }
                          >
                            <span style={{ color: '#333333' }}>
                              {item.label}
                            </span>
                            {' | '}
                            <span style={{ color: '#339999' }}>
                              {item.model === undefined ? '无参数' : item.model}
                            </span>
                            {' | '}
                            <span style={{ color: '#666666' }}>
                              {item.base_unit_name === undefined
                                ? '无单位'
                                : item.base_unit_name}
                            </span>
                          </div>
                        );
                      },
                    }}
                    debounceTime={1000}
                    request={async (value) => {
                      const keywords = value.keyWords;
                      const res = await postKingdeeRepMaterial({
                        data: { search: keywords },
                      });
                      let options = res?.rows?.map((p: any) => {
                        return {
                          ...p,
                          label: p.name,
                          value: p.id + '|' + p.name,
                          key: p.id,
                        };
                      });

                      //第一个商品默认为要新增的商品
                      if (keywords.trim() !== '') {
                        options.unshift({
                          productName: keywords,
                          type: 'add',
                          label: keywords,
                          value: 13 + '|' + keywords,
                          key: keywords,
                        });
                      }
                      return options;
                    }}
                  />,
                  <ProFormText
                    key="orderStatus"
                    name="orderStatus"
                    width="lg"
                    disabled
                    label="orderStatus"
                    placeholder="orderStatus"
                    hidden
                  />,
                  <ProFormText
                    key={'productCode' + listMeta.index}
                    width="lg"
                    name="productCode"
                    disabled
                    label={
                      <>
                        <span>商品编码</span>
                        <span className="pl-2 text-xs text-gray-400">
                          新增商品时,商品编码由系统自动生成
                        </span>
                      </>
                    }
                    placeholder="未输入商品名称"
                  />,
                  // <ProFormSelect
                  //   key="inv_stock"
                  //   placeholder="请选择仓库"
                  //   name="invStockId"
                  //   width="lg"
                  //   label="仓库"
                  //   options={productInvStockOptionsList[listMeta.index]}
                  // />,
                  <ProFormText
                    key={'parameters' + listMeta.index}
                    width="lg"
                    name="parameters"
                    label="商品参数"
                    placeholder="请输入商品参数"
                    disabled={
                      productParametersDisabledFlagList[listMeta.index] !==
                        false || optType('after-sales-check')
                    }
                  />,
                  <ProFormDigit
                    key={'quantity' + listMeta.index}
                    width="lg"
                    name="quantity"
                    label="商品数量"
                    fieldProps={{
                      onChange: (value) => {
                        listMeta.record.quantity = value;
                        computeSubOrderPayment(listMeta);
                      },
                    }}
                    placeholder="请输入商品数量"
                    disabled={optType('after-sales-check')}
                    rules={[{ required: true, message: '商品数量必填' }]}
                  />,
                  <ProFormDigit
                    key={'productPrice' + listMeta.index}
                    width="lg"
                    name="productPrice"
                    label="商品单价"
                    fieldProps={{
                      onChange: (value) => {
                        listMeta.record.productPrice = value;
                        computeSubOrderPayment(listMeta);
                      },
                    }}
                    placeholder="请输入商品单价"
                    disabled={optType('after-sales-check')}
                    rules={[{ required: true, message: '商品单价必填' }]}
                  />,
                  <ProFormText
                    key={'unit' + listMeta.index}
                    width="lg"
                    name="unit"
                    label="商品单位"
                    placeholder="请输入商品单位"
                    disabled={
                      productParametersDisabledFlagList[listMeta.index] !==
                        false || optType('after-sales-check')
                    }
                    rules={[{ required: true, message: '商品单位必填' }]}
                  />,

                  <ProFormDigit
                    width="lg"
                    key={'subOrderPayment' + listMeta.index}
                    name="subOrderPayment"
                    label="子订单金额"
                    placeholder="请输入子订单金额"
                    tooltip="商品数量和单价变化后会自动计算子订单金额"
                    disabled={optType('after-sales-check')}
                    rules={[{ required: true, message: '子订单金额必填' }]}
                  />,
                  <ProFormSelect
                    key={'productBelongBusiness' + listMeta.index}
                    placeholder="请输入所属事业部"
                    name="productBelongBusiness"
                    width="lg"
                    label="所属事业部"
                    options={enumToSelect(PRODUCT_BELONG_DEPARTMENT_OPTIONS)}
                    onChange={(val: any) => {
                      productBelongBusinessChange(val, listMeta.index);
                    }}
                    initialValue={'EXPERIMENTAL_CONSUMABLES'}
                    rules={[{ required: true, message: '所属事业部必填' }]}
                    disabled={optType('after-sales-check')}
                  />,
                  <ProFormSelect
                    key={'shippingWarehouse' + listMeta.index}
                    placeholder="请选择发货仓库"
                    name="shippingWarehouse"
                    width="lg"
                    label="发货仓库"
                    options={enumToSelect(SHIPPING_WAREHOUSE_OPTIONS)}
                    disabled={optType('after-sales-check')}
                  />,
                  <ProFormTextArea
                    key={'notes' + listMeta.index}
                    width="lg"
                    name="notes"
                    disabled={optType('after-sales-check')}
                    label={
                      <div>
                        <span>备注</span>
                        <span className="pl-2 text-xs text-gray-400">
                          备注将体现在出货单上,请将需要仓管看见的信息写在备注上,例如需要开收据等信息。
                        </span>
                      </div>
                    }
                    placeholder="请输入备注"
                    rules={[
                      {
                        max: 1000, // 最大长度为1000个字符
                        message: '备注不能超过1000个字符',
                      },
                    ]}
                  />,
                  <>
                    <ProFormUploadDragger
                      key={'filePaths' + listMeta.index}
                      label="附件"
                      name="filePaths"
                      action="/api/service/order/fileProcess"
                      disabled={optType('after-sales-check')}
                      fieldProps={{
                        headers: {
                          Authorization: localStorage.getItem('token'),
                        },
                        itemFileList,
                      }}
                    />
                  </>,
                ]}
              </ProCard>
            );
          }}
          actionRef={actionRef}
        ></ProFormList>
      </DrawerForm>
      {kingdeeCstomerModalVisible && (
        <KingdeeCustomerModal
          setVisible={setKingdeeCstomerModalVisible}
          data={customer}
          onClose={(customerId: any) => {
            setKingdeeCstomerModalVisible(false);
            //回显已经新建好的客户
            autoFillCustomerContactSelectOptions(customerId);
          }}
        />
      )}
    </>
  );
};