import React, { useEffect, useState } from "react";
import { Modal, Form, InputNumber, Select, message, Radio, Divider } from "antd";
import { useStore } from "../index";
import { savePlatformMobile } from "../api";
import { CompanyCategoryTypeEnum, ExpireRepayRuleObj } from "@/pages/finance/entitys";
import { RadioChangeEvent } from "antd/lib/radio";
import InputX from "@/pages/finance/SpecialAccount/FinancingCompany/components/InputX";

const FormItem = Form.Item;
const { Option } = Select;

export default function CreateModal() {
  const { visible, current, setCurrent, setVisible, fcList, accountList, setLoading, dealerId, brandList } = useStore();
  const [form] = Form.useForm();

  const [saveLoading, setSaveLoading] = useState<boolean>(false);
  useEffect(() => {
    if (visible) {
      form.setFieldsValue({
        ...current,
        fcComp: current.compId ? { value: current.compId, label: current.compName } : undefined,
        compCategory: current.compCategory,
        account: current.accountId ? { value: current.accountId, label: current.accountName } : undefined,
        depositAccount: current.depositAccountId
          ? { value: current.depositAccountId, label: current.depositAccountName }
          : undefined,
        maxCreditQuota: current.maxCreditQuota,
        depositType: current.depositType || 1,
        depositValue: current.depositValue,
        billServiceFee: current.billServiceFee,
        billLimitDates: current.billLimitDates,
        billTransferDates: current.billTransferDates,
        billTransferInterest: current.billTransferInterest,
        interestSettleDay: current.interestSettleDay,
        depositPayMethod: current.depositPayMethod || 1,
        brand: current.brandId ? { value: current.brandId, label: current.brandName } : undefined,
        repayAdvanceDays: current.repayAdvanceDays,
        toLoan: current.toLoan ? 1 : 0,
        toLoanDue: current.toLoanDueTime
          ? { number: current.toLoanDueTime, unit: current.toLoanDueTimeType }
          : undefined,
        repayAccount: current.repayAccountId
          ? { value: current.repayAccountId, label: current.repayAccountName }
          : undefined,
        toLoanRepayAdvanceDays: current.toLoanRepayAdvanceDays,
        loan: current.loan ? 1 : 0,
        loanInterest: current.loanInterest,
        loanInterestSettleDay: current.loanInterestSettleDay,
        loanRepayAdvanceDays: current.loanRepayAdvanceDays,
      });
    }
  }, [visible]);

  function onCompare(fieldValue: any) {
    if (current.compId && fieldValue.depositPayMethod == 1 && current.depositValue != fieldValue.depositValue) {
      Modal.confirm({
        title: "保证金变更",
        content: (
          <div>
            <p>{`往来单位：${current.compName}`}</p>
            <Divider orientation="left">调整前</Divider>
            <p>{`原最大授信额度：${current.maxCreditQuota!.toFixed(2)}元`}</p>
            <p>{`原保证金：${current.depositValue!.toFixed(2)}${current.depositType == 1 ? "元" : "%"}`}</p>
            <Divider orientation="left">调整后</Divider>
            <p>{`最大授信额度：${fieldValue.maxCreditQuota.toFixed(2)}元`}</p>
            <p>{`保证金：${fieldValue.depositValue.toFixed(2)}${fieldValue.depositType == 1 ? "元" : "%"}`}</p>
          </div>
        ),
        onOk: () => {
          submit(fieldValue);
        },
      });
    } else {
      submit(fieldValue);
    }
  }

  function submit(fieldValue: any) {
    const param = {
      dealerId,
      ...fieldValue,
      compCategory: fieldValue.compCategory,
      compId: fieldValue.fcComp.value,
      compName: fieldValue.fcComp.label,
      accountId: fieldValue.account.value,
      accountName: fieldValue.account.label,
      depositAccountId: fieldValue.depositAccount && fieldValue.depositAccount.value,
      depositAccountName: fieldValue.depositAccount && fieldValue.depositAccount.label,
      depositValue: fieldValue.depositValue,
      brandId: fieldValue.brand && fieldValue.brand.value,
      brandName: fieldValue.brand && fieldValue.brand.label,
      toLoan: !!fieldValue.toLoan,
      toLoanDueTime: fieldValue.toLoanDue && fieldValue.toLoanDue.number,
      toLoanDueTimeType: fieldValue.toLoanDue && fieldValue.toLoanDue.unit,
      repayAccountId: fieldValue.repayAccount && fieldValue.repayAccount.value,
      repayAccountName: fieldValue.repayAccount && fieldValue.repayAccount.label,
      loan: !!fieldValue.loan,
    };
    setSaveLoading(true);
    savePlatformMobile(param)
      .then((res) => {
        message.success("保存成功");
        setVisible(false);
        setLoading(true);
      })
      .catch((err) => {
        message.error(err.message);
      })
      .finally(() => {
        setSaveLoading(false);
      });
  }

  function onCancel() {
    setVisible(false);
  }

  return (
    <Modal
      title={`${current.compId ? "编辑" : "新增"}融资账户`}
      visible={visible}
      confirmLoading={saveLoading}
      onOk={form.submit}
      onCancel={onCancel}
      afterClose={() => {
        setCurrent({});
        form.resetFields();
      }}
      maskClosable={false}
      width="48%"
    >
      <Form form={form} labelCol={{ span: 7 }} wrapperCol={{ span: 15 }} onFinish={onCompare}>
        <FormItem label="账户类别" name="compCategory" rules={[{ required: true, message: "请选择类别" }]}>
          <Select placeholder="请选择类别" disabled={!!current.compId}>
            {[1, 2].map((i) => (
              <Option key={i} value={i}>
                {CompanyCategoryTypeEnum[i]}
              </Option>
            ))}
          </Select>
        </FormItem>
        <FormItem name="brand" label="品牌" rules={[{ required: true, message: "请选择品牌" }]}>
          <Select labelInValue placeholder="请选择品牌" showSearch optionFilterProp="children">
            {brandList.map((item) => (
              <Option key={item.id} value={item.id}>
                {item.name}
              </Option>
            ))}
          </Select>
        </FormItem>
        <FormItem
          noStyle
          shouldUpdate={(prevValues, currentValues) => prevValues.compCategory != currentValues.compCategory}
        >
          {({ getFieldValue }): any => {
            const category = getFieldValue("compCategory");
            return category ? (
              <FormItem label="融资公司" name="fcComp" rules={[{ required: true, message: "请选择融资公司" }]}>
                <Select
                  showSearch
                  labelInValue
                  placeholder="请选择融资公司"
                  optionFilterProp="children"
                  disabled={!!current.compId}
                >
                  {fcList
                    .filter((list) => list.compCategory == getFieldValue("compCategory"))
                    .map((item) => (
                      <Option key={item.id} value={Number(item.id)}>
                        {item.name}
                      </Option>
                    ))}
                </Select>
              </FormItem>
            ) : null;
          }}
        </FormItem>
        <FormItem
          name="depositPayMethod"
          label="保证金支付方式"
          rules={[{ required: true, message: "请选择支付方式" }]}
        >
          <Radio.Group>
            <Radio value={1}>前期一次性支付</Radio>
            <Radio value={2}>每张票支付</Radio>
          </Radio.Group>
        </FormItem>
        <FormItem name="depositAccount" label="保证金账户">
          <Select labelInValue placeholder="请选择账户" showSearch optionFilterProp="children" allowClear>
            {accountList.map((item) => (
              <Option key={item.id} value={item.id}>
                {item.name}
              </Option>
            ))}
          </Select>
        </FormItem>
        <FormItem name="account" label="一般账户" rules={[{ required: true, message: "请选择一般账户" }]}>
          <Select labelInValue placeholder="请选择一般账户">
            {accountList.map((item) => (
              <Option key={item.id} value={item.id}>
                {item.name}
              </Option>
            ))}
          </Select>
        </FormItem>
        <FormItem name="repayAccount" label="还款账户">
          <Select labelInValue placeholder="请选择还款账户" allowClear>
            {accountList.map((item) => (
              <Option key={item.id} value={item.id}>
                {item.name}
              </Option>
            ))}
          </Select>
        </FormItem>
        <FormItem
          name="maxCreditQuota"
          label="最大授信额度"
          rules={[{ required: true, message: "请输入最大授信额度" }]}
        >
          <InputNumber
            style={{ width: "100%" }}
            placeholder="请输入最大授信额度"
            min={0}
            precision={2}
            formatter={(value) => `${value} 元`}
          />
        </FormItem>
        <FormItem
          name="depositType"
          label="保证金类型"
          rules={[{ required: true, message: "请选择保证金类型" }]}
          getValueFromEvent={(e: RadioChangeEvent) => {
            form.setFieldsValue({ depositValue: undefined });
            return e.target.value;
          }}
        >
          <Radio.Group disabled={!!current.compId}>
            <Radio value={1}>固定</Radio>
            <Radio value={2}>比例</Radio>
          </Radio.Group>
        </FormItem>
        <FormItem
          noStyle
          shouldUpdate={(prevValues, currentValues) => prevValues.depositType != currentValues.depositType}
        >
          {({ getFieldValue }): any => {
            return (
              <FormItem label="保证金" name="depositValue" rules={[{ required: true, message: "请输入保证金" }]}>
                <InputNumber
                  style={{ width: "100%" }}
                  placeholder="请输入保证金"
                  min={0}
                  precision={2}
                  max={getFieldValue("depositType") == 1 ? Infinity : 100}
                  formatter={(value) => `${value} ${getFieldValue("depositType") == 1 ? "元" : "%"}`}
                />
              </FormItem>
            );
          }}
        </FormItem>
        <FormItem name="billServiceFee" label="出票手续费" rules={[{ required: true, message: "请输入出票手续费" }]}>
          <InputNumber
            style={{ width: "100%" }}
            placeholder="请输入手续费"
            min={0}
            max={100}
            precision={2}
            step={0.01}
            formatter={(value) => `${value} %`}
          />
        </FormItem>
        {/* 清票划扣账户类型：1 一般户；2 保证金户；3 一般户，保证金户(See: 清票划扣账户类型) */}
        <FormItem
          name="deductAccountType"
          label="清票划扣账户"
          rules={[{ required: true, message: "请选择清票划扣账户" }]}
        >
          <Radio.Group>
            <Radio value={1}>一般户</Radio>
            <Radio value={2}>保证金户</Radio>
            <Radio value={3}>一般户，保证金户</Radio>
          </Radio.Group>
        </FormItem>
        <FormItem name="billLimitDates" label="票据期限" rules={[{ required: true, message: "请输入票据期限" }]}>
          <InputNumber style={{ width: "100%" }} placeholder="请输入票据期限" formatter={(value) => `${value} 个月`} />
        </FormItem>
        <FormItem
          name="repayAdvanceDays"
          label="票据到期提前还款天数"
          rules={[{ required: true, message: "请输入票据到期提前还款天数" }]}
        >
          <InputNumber style={{ width: "100%" }} placeholder="请输入提前天数" formatter={(value) => `${value} 天`} />
        </FormItem>
        <FormItem name="toLoan" label="是否支持票转贷" rules={[{ required: true, message: "请选择是否支持票转贷" }]}>
          <Radio.Group>
            <Radio value={1}>是</Radio>
            <Radio value={0}>否</Radio>
          </Radio.Group>
        </FormItem>
        <FormItem noStyle shouldUpdate={(prevValues, currentValues) => prevValues.toLoan != currentValues.toLoan}>
          {({ getFieldValue }): any => {
            const category = getFieldValue("toLoan");
            return category ? (
              <>
                <FormItem
                  name="toLoanDue"
                  label="票转贷最长期限"
                  rules={[{ required: true, message: "请输入票转贷最长期限" }]}
                >
                  <InputX />
                </FormItem>

                <FormItem
                  name="billTransferInterest"
                  label="票转贷年利率"
                  rules={[{ required: true, message: "请输入票转贷年利率" }]}
                >
                  <InputNumber
                    style={{ width: "100%" }}
                    placeholder="请输入票转贷年利率"
                    min={0}
                    max={100}
                    precision={2}
                    step={0.01}
                    formatter={(value) => `${value} %`}
                  />
                </FormItem>
                <FormItem label="票转贷结息日期">
                  <span>每月</span>
                  <FormItem
                    name="interestSettleDay"
                    noStyle
                    rules={[{ required: true, message: "请输入票转贷利息结算日期" }]}
                  >
                    <InputNumber
                      style={{ width: "80%", marginRight: 6, marginLeft: 6 }}
                      placeholder="请输入票转贷利息结算日期"
                      min={1}
                      precision={0}
                      max={31}
                    />
                  </FormItem>
                  <span>日</span>
                </FormItem>
                <FormItem
                  name="toLoanRepayAdvanceDays"
                  label="票转贷还款提前天数"
                  rules={[{ required: true, message: "请输入票转贷还款提前天数" }]}
                >
                  <InputNumber
                    style={{ width: "100%" }}
                    placeholder="请输入提前天数"
                    formatter={(value) => `${value} 天`}
                  />
                </FormItem>
              </>
            ) : null;
          }}
        </FormItem>
        <FormItem name="loan" label="是否支持贷款启票" rules={[{ required: true, message: "请选择是否支持贷款启票" }]}>
          <Radio.Group>
            <Radio value={1}>是</Radio>
            <Radio value={0}>否</Radio>
          </Radio.Group>
        </FormItem>
        <FormItem noStyle shouldUpdate={(prevValues, currentValues) => prevValues.loan != currentValues.loan}>
          {({ getFieldValue }): any => {
            const category = getFieldValue("loan");
            return category ? (
              <>
                <FormItem
                  name="loanInterest"
                  label="贷款启票年利率"
                  rules={[{ required: true, message: "请输入贷款启票年利率" }]}
                >
                  <InputNumber
                    style={{ width: "100%" }}
                    placeholder="请输入贷款启票年利率"
                    min={0}
                    max={100}
                    precision={2}
                    step={0.01}
                    formatter={(value) => `${value} %`}
                  />
                </FormItem>
                <FormItem label="贷款启票结息日">
                  <span>每月</span>
                  <FormItem
                    name="loanRepayAdvanceDays"
                    noStyle
                    rules={[{ required: true, message: "请输入贷款启票结息日" }]}
                  >
                    <InputNumber
                      style={{ width: "80%", marginRight: 6, marginLeft: 6 }}
                      placeholder="请输入贷款启票结息日"
                      min={1}
                      precision={0}
                      max={31}
                    />
                  </FormItem>
                  <span>日</span>
                </FormItem>
                <FormItem
                  name="loanInterestSettleDay"
                  label="贷款启票还款提前天数"
                  rules={[{ required: true, message: "请输入贷款启票还款提前天数" }]}
                >
                  <InputNumber
                    style={{ width: "100%" }}
                    placeholder="请输入提前天数"
                    formatter={(value) => `${value} 天`}
                  />
                </FormItem>
              </>
            ) : null;
          }}
        </FormItem>
        <FormItem
          name="expireRepayRule"
          label="票据到期还款推送"
          rules={[{ required: true, message: "请选择推送方式" }]}
        >
          <Radio.Group>
            {ExpireRepayRuleObj.map((item) => (
              <Radio value={item.value}>{item.label}</Radio>
            ))}
          </Radio.Group>
        </FormItem>
      </Form>
    </Modal>
  );
}
