import { MyModalFormProps, MyPageContainer, rulesHelper } from '@/common';
import { Apis } from '@/gen/Apis';
import {
  ContractBillsCostTypeEnum,
  ContractsSettlementModeEnum,
  ContractTemplatesIncomeExpenseTypeEnum,
} from '@/gen/Enums';
import { BetaSchemaForm, ProCard } from '@ant-design/pro-components';
import { useNavigate, useSearchParams } from '@umijs/max';
import { Form, message, Space, Tag } from 'antd';
import { useEffect, useState } from 'react';
export default function Index({ title = '编辑合同账单' }) {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const id = searchParams.get('id') ?? 0;
  const [dataBill, setBillShow] = useState<any>({});
  const [data, setShow] = useState<any>({});

  const getContractsShow = (id: number) => {
    Apis.Contract.Contracts.Show({ id: id }).then((res) => {
      setShow(res?.data);
    });
  };

  const totalBillSeparableAmount = () => {
    return parseFloat(
      (
        parseFloat(data?.total_amount) -
        parseFloat(data?.total_bill_amount) +
        parseFloat(dataBill?.amount)
      ).toFixed(2),
    );
  };

  const loadShow = () => {
    Apis.Contract.ContractBills.Show({ id: Number(id) }).then((res) => {
      res.data.year_month = `${res?.data?.year}-${
        res?.data?.month < 10 ? `0${res?.data?.month}` : res?.data?.month
      }`;
      setBillShow(res?.data);
      form.setFieldsValue({
        ...res?.data,
        object_name: res?.data?.contract_bill_objects?.[0]?.name,
      });
      getContractsShow(res?.data?.contracts_id);
      //   form.setFieldsValue(res?.data); // 编辑赋值
    });
  };

  useEffect(() => {
    loadShow();
  }, [id]);

  return (
    <MyPageContainer
      title={
        <Space
          style={{ cursor: 'pointer' }}
          onClick={() => {
            navigate(-1);
          }}
        >
          {/* <LeftCircleOutlined size={34} /> */}
          {title}
        </Space>
      }
      enableTabs={false}
      tabKey="charge-standards-create"
      tabLabel={title}
    >
      <ProCard>
        <div style={{ width: 1000, minHeight: '83vh', margin: '0 auto' }}>
          <BetaSchemaForm<ApiTypes.Contract.ContractArchives.Update>
            {...MyModalFormProps.props}
            title="编辑"
            wrapperCol={{ span: 24 }}
            width="1000px"
            layoutType="Form"
            form={form}
            onFinish={async (values: any) => {
              let total_bill_amount = totalBillSeparableAmount();
              let k = values?.year_month?.split('-');
              values.year = k[0];
              values.month = parseInt(k[1]);
              if (data?.settlement_mode === 'OpenContract') {
                //开口合同
                return Apis.Contract.ContractBills.Update({
                  ...values,
                  id: Number(id),
                })
                  .then(() => {
                    navigate(-1);
                    message.success('提交成功');
                    return true;
                  })
                  .catch(() => false);
              } else {
                if (total_bill_amount > 0) {
                  if (
                    values?.amount <=
                    total_bill_amount + parseFloat(dataBill?.amount)
                  ) {
                    return Apis.Contract.ContractBills.Update({
                      ...values,
                      id: Number(id),
                    })
                      .then(() => {
                        navigate(-1);
                        message.success('提交成功');
                        return true;
                      })
                      .catch(() => false);
                  } else {
                    message.warning('可拆分金额不够！');
                  }
                } else {
                  message.warning('没有多余金额可生成账单！');
                }
              }
            }}
            columns={[
              {
                name: ['contracts_id'],
                valueType: 'dependency',
                columns: ({ contracts_id }: any) => {
                  return contracts_id
                    ? [
                        {
                          colProps: { span: 24 },
                          renderFormItem: () => {
                            return (
                              <ProCard
                                bordered
                                type="inner"
                                title={`已选择合同：${data?.name}`}
                                headerBordered
                              >
                                <Space size="middle" direction="vertical">
                                  <div>
                                    收支类型：
                                    {
                                      ContractTemplatesIncomeExpenseTypeEnum[
                                        data?.income_expense_type as keyof typeof ContractTemplatesIncomeExpenseTypeEnum
                                      ]?.text
                                    }
                                  </div>
                                  <div>
                                    结算模式：
                                    {
                                      ContractsSettlementModeEnum[
                                        data?.settlement_mode as keyof typeof ContractsSettlementModeEnum
                                      ]?.text
                                    }
                                  </div>
                                  <div>总金额： ¥{data?.total_amount}</div>
                                  <div>
                                    已生成账单： ¥{data?.total_bill_amount}
                                  </div>
                                  {data?.settlement_mode ===
                                    'LumpSumContract' && (
                                    <div style={{ color: 'red' }}>
                                      本次编辑可拆分金额： ¥
                                      {totalBillSeparableAmount()}
                                    </div>
                                  )}
                                </Space>
                              </ProCard>
                            );
                          },
                        },
                        {
                          valueType: 'divider',
                          fieldProps: {
                            orientation: 'left',
                            title: '基本信息',
                          },
                        },
                        {
                          title: '收款方',
                          valueType: 'select',
                          dataIndex: 'payee',
                          colProps: { span: 12 },
                          formItemProps: { ...rulesHelper.text },
                          fieldProps: {
                            disabled: true,
                          },
                        },
                        {
                          title: '付款方',
                          valueType: 'select',
                          dataIndex: 'payer',
                          colProps: { span: 12 },
                          formItemProps: { ...rulesHelper.text },
                          fieldProps: {
                            disabled: true,
                          },
                        },
                        {
                          title: '费用类型',
                          dataIndex: 'cost_type',
                          colProps: { span: 2 },
                          align: 'center',
                          renderFormItem: () => {
                            let res =
                              ContractBillsCostTypeEnum[
                                data?.income_expense_type as keyof typeof ContractBillsCostTypeEnum
                              ];
                            return <Tag color={res?.color}>{res?.text}</Tag>;
                          },
                        },
                        {
                          title: '账单月份',
                          valueType: 'dateMonth',
                          dataIndex: 'year_month',
                          colProps: { span: 6 },
                          formItemProps: { ...rulesHelper.text },
                          fieldProps: {
                            style: {
                              width: '100%',
                            },
                          },
                        },
                        {
                          title: '期数',
                          valueType: 'digit',
                          dataIndex: 'period_num',
                          colProps: { span: 4 },
                          formItemProps: { ...rulesHelper.number },
                          fieldProps: {
                            style: {
                              width: '100%',
                            },
                          },
                        },
                        {
                          title: '账单金额',
                          valueType: 'digit',
                          dataIndex: 'amount',
                          colProps: { span: 6 },
                          formItemProps: { ...rulesHelper.number },
                          fieldProps: {
                            style: {
                              width: '100%',
                            },
                          },
                        },
                        {
                          title: '合同标的',
                          formItemProps: { ...rulesHelper.text },
                          dataIndex: 'object_name',
                          fieldProps: {
                            disabled: true,
                          },
                          colProps: { span: 6 },
                        },
                        {
                          title: '备注',
                          dataIndex: 'remark',
                          valueType: 'textarea',
                          colProps: { span: 24 },
                        },
                      ]
                    : [];
                },
              },
            ]}
          />
        </div>
      </ProCard>
    </MyPageContainer>
  );
}
