import {
  MyButtons,
  MyModalFormProps,
  MyPageContainer,
  renderTextHelper,
  rulesHelper,
} from '@/common';
import MyContractsSelectList from '@/components/ModalsContractsSelectList';
import { Apis } from '@/gen/Apis';
import {
  ContractBillsCostTypeEnum,
  ContractsSettlementModeEnum,
  ContractTemplatesIncomeExpenseTypeEnum,
} from '@/gen/Enums';
import {
  BetaSchemaForm,
  ProCard,
  ProDescriptions,
} from '@ant-design/pro-components';
import { useNavigate, useSearchParams } from '@umijs/max';
import { Empty, Form, message, Space, Tag } from 'antd';
import { useEffect, useState } from 'react';

export default function Create() {
  const [form] = Form.useForm();
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const [data, setShow] = useState<any>({});
  const id = searchParams.get('id') ?? 0;
  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)
      ).toFixed(2),
    );
  };

  useEffect(() => {
    if (id) {
      getContractsShow(Number(id));
      form.setFieldsValue({
        contracts_id: id,
      });
    }
  }, [id]);

  return (
    <MyPageContainer
      title={
        <Space
          style={{ cursor: 'pointer' }}
          onClick={() => {
            navigate(-1);
          }}
        >
          {/* <LeftCircleOutlined size={34} /> */}
          新增合同账单
        </Space>
      }
      enableTabs={false}
      tabKey="charge-standards-create"
    >
      <ProCard>
        <div style={{ width: 1200, minHeight: '83vh', margin: '0 auto' }}>
          <BetaSchemaForm<ApiTypes.Contract.ContractBills.Store>
            {...MyModalFormProps.props}
            wrapperCol={{ span: 24 }}
            width="1200px"
            layoutType="Form"
            form={form}
            onFinish={async (values: any) => {
              let year_month_is = false;
              let total_bill_amount = totalBillSeparableAmount();
              let taotal_amount = parseFloat(values?.amount) || 0;
              if (
                total_bill_amount <= 0 &&
                data?.settlement_mode === 'LumpSumContract'
              ) {
                message.warning('没有多余金额可生成账单！');
                return false;
              }
              if (values?.payee === values?.payer) {
                year_month_is = true;
                message.warning('收款方和付款方不能相同');
                return false;
              }
              if (
                data?.settlement_mode === 'LumpSumContract' &&
                taotal_amount <= 0
              ) {
                message.warning('账单金额必须大于0');
                return false;
              }
              if (
                data?.settlement_mode === 'LumpSumContract' &&
                taotal_amount !== total_bill_amount
              ) {
                message.warning(`请把¥${total_bill_amount}，拆分完！`);
                return false;
              }
              if (year_month_is) {
                return;
              }
              // 处理年月
              let year_month = values?.year_month;
              let k = year_month?.split('-');
              let year = k[0];
              let month = parseInt(k[1]);
              // 构建账单数据
              const billData = {
                ...values,
                year: year,
                month: month,
                contracts_id: data?.id,
                cost_type: data?.income_expense_type,
              };
              console.log(billData, 'billData');
              if (data?.settlement_mode === 'OpenContract') {
                //开口合同
                return Apis.Contract.ContractBills.Store({
                  ...billData,
                })
                  .then(() => {
                    navigate('/contract/contract_bills');
                    message.success('提交成功');
                    return true;
                  })
                  .catch(() => false);
              }
              if (
                total_bill_amount > 0 &&
                data?.settlement_mode === 'LumpSumContract'
              ) {
                if (taotal_amount <= total_bill_amount) {
                  return Apis.Contract.ContractBills.Store({
                    ...billData,
                  })
                    .then(() => {
                      navigate('/contract/contract_bills');
                      message.success('提交成功');
                      return true;
                    })
                    .catch(() => false);
                } else {
                  message.warning('可拆分金额不够！');
                }
                console.log(taotal_amount, total_bill_amount, 'taotal_amount');
              }
            }}
            submitter={{
              render: (props) => {
                return [
                  <MyButtons.Default
                    key="Review"
                    size="middle"
                    type="primary"
                    onClick={() => {
                      props.submit();
                    }}
                    title="提交"
                  />,
                ];
              },
            }}
            columns={[
              {
                name: ['contracts_id'],
                valueType: 'dependency',
                columns: ({ contracts_id }: any) => {
                  if (!id) {
                    return [
                      {
                        colProps: { span: 24 },
                        title: '选择合同',
                        key: 'contracts_id',
                        formItemProps: { ...rulesHelper.number },
                        renderFormItem: () => {
                          return (
                            <MyContractsSelectList
                              onChange={(e: any) => {
                                let res = e[0];
                                getContractsShow(res?.id);
                                form.setFieldsValue({
                                  contracts_id: res?.id,
                                });
                                console.log(e, contracts_id, 'e');
                              }}
                            />
                          );
                        },
                      },
                    ];
                  } else {
                    return [];
                  }
                },
              },
              {
                name: ['contracts_id'],
                valueType: 'dependency',
                columns: ({ contracts_id }: any) => {
                  return [
                    {
                      colProps: { span: 24 },
                      renderFormItem: () => {
                        return (
                          <ProCard
                            bordered
                            type="inner"
                            title={
                              contracts_id
                                ? `已选择：${data?.name} ｜ ${data?.code}`
                                : '请选择合同'
                            }
                            headerBordered
                          >
                            {contracts_id ? (
                              <Space
                                size="middle"
                                direction="vertical"
                                style={{ width: '100%' }}
                              >
                                <ProDescriptions
                                  bordered
                                  column={3}
                                  style={{ width: '100%' }}
                                >
                                  <ProDescriptions.Item label="收支类型">
                                    <renderTextHelper.Tag
                                      Enums={
                                        ContractTemplatesIncomeExpenseTypeEnum
                                      }
                                      value={data?.income_expense_type}
                                      key="income_expense_type"
                                    />
                                  </ProDescriptions.Item>
                                  <ProDescriptions.Item label="结算模式">
                                    <renderTextHelper.Tag
                                      Enums={ContractsSettlementModeEnum}
                                      value={data?.settlement_mode}
                                      key="income_expense_type"
                                    />
                                  </ProDescriptions.Item>
                                  <ProDescriptions.Item label="总金额">
                                    ¥{data?.total_amount}
                                  </ProDescriptions.Item>
                                  <ProDescriptions.Item label="已生成账单">
                                    ¥{data?.total_bill_amount}
                                  </ProDescriptions.Item>
                                  <ProDescriptions.Item label="剩余可生成账单金额">
                                    {data?.settlement_mode ===
                                      'LumpSumContract' && (
                                      <span style={{ color: 'red' }}>
                                        ¥{totalBillSeparableAmount()}
                                      </span>
                                    )}
                                  </ProDescriptions.Item>
                                </ProDescriptions>
                              </Space>
                            ) : (
                              <Empty description="请选择合同" />
                            )}
                          </ProCard>
                        );
                      },
                    },
                    {
                      valueType: 'divider',
                      title: '账单设置',
                      fieldProps: {
                        orientation: 'left',
                        children: '账单设置',
                      },
                    },

                    {
                      title: '收款方',
                      valueType: 'select',
                      dataIndex: 'payee',
                      colProps: { span: 12 },
                      formItemProps: { ...rulesHelper.text },
                      fieldProps: {
                        options: data?.contract_peoples
                          ?.filter((item: any) => {
                            // 当收入类型为Income时，只显示内部公司
                            if (data?.income_expense_type === 'Income') {
                              return (
                                item?.counterparty_type === 'InternalCompany'
                              );
                            }
                            // 其他情况显示所有
                            return item?.counterparty_type === 'Supplier';
                          })
                          .map((item: any) => ({
                            label: item?.counterparty,
                            value: item?.counterparty,
                          })),
                      },
                    },
                    {
                      title: '付款方',
                      valueType: 'select',
                      dataIndex: 'payer',
                      colProps: { span: 12 },
                      formItemProps: { ...rulesHelper.text },
                      fieldProps: {
                        options: data?.contract_peoples
                          ?.filter((item: any) => {
                            // 当收入类型为Income时，只显示内部公司
                            if (data?.income_expense_type === 'Expense') {
                              return (
                                item?.counterparty_type === 'InternalCompany'
                              );
                            }
                            // 其他情况显示所有
                            return item?.counterparty_type === 'Supplier';
                          })
                          .map((item: any) => ({
                            label: item?.counterparty,
                            value: item?.counterparty,
                          })),
                      },
                    },
                    {
                      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',
                      colProps: { span: 6 },
                    },
                    {
                      title: '备注',
                      dataIndex: 'remark',
                      valueType: 'textarea',
                      colProps: { span: 24 },
                    },
                  ];
                },
              },
            ]}
          />
        </div>
      </ProCard>
    </MyPageContainer>
  );
}
