import React, { useState, useEffect, memo } from "react";
import { Select, message, Form, Divider, Button, InputNumber } from "antd";
import { useStore } from "../index";
import { saveCompanyRelationApi } from "@/pages/finance/CompanyRelationAuth/api";
import EditTagList from "./EditTagList";
import { invoiceRequirements, payWay, RequirementsTypeEnum } from "@/pages/finance/CompanyRelationCreate/entity";

const { Option } = Select;

interface Props {
  onPrevious?: () => void;
}

function SelectModal({ onPrevious }: Props) {
  const [form] = Form.useForm();
  const {
    // visible,
    // selected,
    // setVisible,
    companyParams,
    // comBussinessList,
    // comBussinessLoading,
    setDisabled,
    selectData,
    setSelectData,
  } = useStore();
  const [submitLoading, setSubmitLoading] = useState(false);

  useEffect(() => {
    const formDate = transFormData(selectData);
    form.setFieldsValue({ ...formDate });
  }, [selectData]);

  function transFormData(originData: TradeCompany.ComList[]) {
    let res = {};
    const comp = originData.map((it) => it.compName);
    res.comp = comp;
    return res;
  }

  function onCancel() {
    setSelectData([]);
    history.back();
  }

  // 保存
  function _onOk(formData: any) {
    const pa = transformDTO(formData);
    setSubmitLoading(true);
    saveCompanyRelationApi(pa)
      .then((res) => {
        message.success("保存成功");
        setSubmitLoading(false);
        setDisabled(true);
        onCancel();
      })
      .catch((e) => {
        setSubmitLoading(false);
        message.error(e.message);
      });
  }

  function transformDTO(formData: any) {
    const { beforeReimburse, comp = [] } = formData;
    const compList = selectData.filter((item) => comp.find((y) => y === item.compName));
    const relationCompanyList = compList.map((item) => ({
      ...formData,
      comp: undefined,
      compId: item.id,
      beforeReimburse: beforeReimburse === RequirementsTypeEnum["支付前"],
    }));
    const pa = {
      ...companyParams,
      relationCompanyList,
    };
    return pa;
  }

  return (
    <>
      <Form
        form={form}
        labelCol={{
          xs: { span: 24 },
          sm: { span: 8 },
          md: { span: 6 },
        }}
        wrapperCol={{
          xs: { span: 24 },
          sm: { span: 10 },
          md: { span: 15 },
        }}
        onFinish={_onOk}
      >
        <Form.Item label="往来单位" name="comp">
          <EditTagList />
        </Form.Item>
        <Form.Item label="发票要求" name="beforeReimburse" rules={[{ required: true, message: "请选择发票要求" }]}>
          <Select placeholder="请选择发票要求">
            {invoiceRequirements.map((item) => (
              <Option key={item.value} value={item.value}>
                {item.label}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          label="发票金额要求比例"
          name="billAmountRatio"
          rules={[
            { required: true, message: "请输入发票金额要求比例" },
            { pattern: /^(100)$|^((\d|[1-9]\d)(\.\d{1,2})?)$/, message: "请输入0-100之间的数字(保留两位小数)" },
          ]}
        >
          <InputNumber
            min={0}
            max={100}
            style={{ width: "100%" }}
            formatter={(value) => `${value}%`}
            parser={(value) => value!.replace("%", "")}
          />
        </Form.Item>
        <Form.Item label="支持结算方式" name="settleMethods" rules={[{ required: true, message: "请选择结算方式" }]}>
          <Select placeholder="请选择结算方式" mode="multiple">
            {payWay.map((item) => (
              <Option key={item.value} value={item.value}>
                {item.label}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item label="对账周期" name="accountCheckPeriod" rules={[{ required: true, message: "请输入对账周期" }]}>
          <InputNumber
            addonBefore="每月"
            placeholder="请输入"
            min={1}
            precision={0}
            max={31}
            addonAfter="日"
            style={{ width: "100%" }}
          />
        </Form.Item>
      </Form>
      <div style={{ width: "100%", textAlign: "center", marginTop: 30 }}>
        <Button type="primary" style={{ marginBottom: 10 }} onClick={() => history.back()}>
          返回列表
        </Button>
        <Divider type="vertical" />
        <Button
          type="primary"
          style={{ marginBottom: 10 }}
          onClick={() => {
            const comp = form.getFieldValue("comp");
            const _selectData = selectData.filter((item) => comp.find((it) => it === item.compName));

            setSelectData(_selectData);
            onPrevious && onPrevious();
          }}
        >
          返回上一步
        </Button>
        <Divider type="vertical" />
        <Button type="primary" style={{ marginBottom: 10 }} onClick={() => form.submit()} loading={submitLoading}>
          保存
        </Button>
      </div>
    </>
  );
}

export default memo(SelectModal);
