import {
  MyBetaModalFormProps,
  MyButtons,
  MyFormItems,
  MyModalFormProps,
  rulesHelper,
} from '@/common';
import { Selects } from '@/components/Select';
import { Apis } from '@/gen/Apis';
import {
  ApprovalTemplateNodesNodeTypeEnum,
  ApprovalTemplatesTypeEnum,
  ContractBillsIncomeExpenseTypeEnum,
} from '@/gen/Enums';
import { BetaSchemaForm } from '@ant-design/pro-components';
import { Button, Form, message } from 'antd';
import { useEffect, useState } from 'react';

export default function CompleteApply(props: MyBetaModalFormProps) {
  const [form] = Form.useForm();
  const [ApprovalTemplates, setApprovalTemplates] = useState<any>([]);

  // 监听费用增减和变更金额的变化，自动计算变更后金额
  const costType = Form.useWatch('cost_type', form);
  const costAmount = Form.useWatch('cost_amount', form);
  const originalAmount = Form.useWatch('original_amount', form);

  // 当费用增减、变更金额或原始金额变化时，自动计算变更后金额
  useEffect(() => {
    if (originalAmount) {
      let finalAmount = parseFloat(originalAmount);
      if (costType === 'Increase' && costAmount) {
        finalAmount += parseFloat(costAmount);
      } else if (costType === 'Decrease' && costAmount) {
        finalAmount -= parseFloat(costAmount);
      }
      // 确保金额为正数
      if (finalAmount < 0) {
        finalAmount = 0;
      }
      form.setFieldsValue({ final_amount: finalAmount.toFixed(2) });
    }
  }, [costType, costAmount, originalAmount, form]);

  return (
    <BetaSchemaForm<ApiTypes.Contract.ContractBillObjects.CompleteApply>
      {...MyModalFormProps.props}
      title={props?.title}
      trigger={
        <MyButtons.Default
          title={props?.title}
          size="small"
          color="pink"
          disabled={
            props?.item?.typeSource === '标地'
              ? props?.item?.status === 'Completed'
              : props.item?.payment_status === 'Paid' ||
                props.item?.cost_type !== 'Expense' ||
                props.item?.audit_status === 'Approved' ||
                props.item?.audit_status === 'Pending'
          }
          variant="solid"
          type="primary"
        />
      }
      wrapperCol={{ span: 24 }}
      key={new Date().getDate()}
      width="680px"
      form={form}
      onOpenChange={(open: any) => {
        if (open && props.item) {
          // 清空所有字段
          form.resetFields(); // 清空表单数据
          // 从合同详情API获取账单金额和标的要求
          Apis.Contract.ContractBills.Show({
            id: props.item?.id || 0,
          })
            .then((res) => {
              let contractData = res?.data || {};
              let originalAmount =
                props.item?.amount ||
                contractData?.amount ||
                contractData?.total_amount ||
                '0';

              form.setFieldsValue({
                original_amount: originalAmount,
                final_amount: originalAmount,
                contract_bill_objects:
                  contractData?.contract_bill_objects?.[0]?.name || '',
                contract_bill_objects_id:
                  contractData?.contract_bill_objects?.[0]?.id || 0,
              });
            })
            .catch((error) => {
              console.error('获取合同详情失败:', error);
              // 失败时使用默认值
              const originalAmount = props.item?.amount || '0';
              form.setFieldsValue({
                ...props.item,
                original_amount: originalAmount,
                final_amount: originalAmount,
              });
            });
        }
      }}
      onFinish={async (values: any) => {
        const { node_approvers } = values;

        if (ApprovalTemplates?.length > 0 && node_approvers?.length > 0) {
          // 遍历模板节点，通过名称找到对应的提交节点进行校验
          for (const templateNode of ApprovalTemplates) {
            // 通过名称找到对应的提交节点
            const submittedNode = node_approvers.find(
              (node: any) => node?.name === templateNode?.name,
            );

            // 如果模板节点在提交数据中不存在，说明被删除了，报错
            if (!submittedNode) {
              message.error(`节点"${templateNode?.name}"不能删除`);
              return false;
            }

            // 校验审批人
            if (
              templateNode?.node_type ===
              ApprovalTemplateNodesNodeTypeEnum.Approver.value
            ) {
              const originalMembers =
                templateNode?.approval_template_node_members?.map(
                  (member: any) => member?.company_employees_id,
                );

              if (originalMembers?.length > 0) {
                const submittedMembers = submittedNode?.members || [];

                const isMatch =
                  originalMembers.length === submittedMembers.length &&
                  originalMembers.every((memberId: number) =>
                    submittedMembers.includes(memberId),
                  );

                if (!isMatch) {
                  message.error(
                    `节点"${templateNode?.name}"的审批人必须与审批模板设置保持一致`,
                  );
                  return false;
                }
              }
            }
          }
        }

        return Apis.Contract.ContractBillObjects.CompleteApply({
          ...values,
          id: values?.contract_bill_objects_id || 0,
          completed_description: values?.completed_description || '',
          cost_amount: values?.cost_amount || 0,
        })
          .then(() => {
            message.success('提交申请成功！');
            props.reload?.();
            return true;
          })
          .catch(() => false);
      }}
      columns={[
        {
          title: '标的ID',
          key: 'contract_bill_objects_id',
          colProps: { span: 4 },
          formItemProps: {
            ...rulesHelper.text,
          },
          fieldProps: {
            disabled: true,
          },
        },
        {
          title: '标的要求',
          valueType: 'text',
          key: 'contract_bill_objects',
          colProps: { span: 14 },
          formItemProps: {
            ...rulesHelper.text,
          },
          fieldProps: {
            disabled: true,
          },
        },
        {
          title: '账单金额',
          valueType: 'text',
          key: 'original_amount',
          colProps: { span: 6 },
          formItemProps: {
            ...rulesHelper.text,
          },
          fieldProps: {
            disabled: true,
          },
        },

        {
          title: '标的完成说明',
          valueType: 'textarea',
          key: 'completed_description',
          formItemProps: { ...rulesHelper.text },
        },
        MyFormItems.EnumRadio({
          key: 'cost_type',
          title: '账单变更',
          colProps: { span: 12 },
          valueEnum: ContractBillsIncomeExpenseTypeEnum,
          formItemProps: { ...rulesHelper.text },
          fieldProps: {
            onChange: (e: any) => {
              if (e) {
                form.setFieldsValue({
                  cost_amount: '',
                });
              }
            },
          },
        }),
        {
          name: ['cost_type'],
          valueType: 'dependency',
          columns: ({ cost_type }) => {
            return cost_type !==
              ContractBillsIncomeExpenseTypeEnum.Neutral.value
              ? [
                  {
                    title: '变更金额',
                    valueType: 'digit',
                    key: 'cost_amount',
                    fieldProps: {
                      style: { width: '100%' },
                    },
                    colProps: { span: 6 },
                    formItemProps: { ...rulesHelper.text },
                  },
                ]
              : [];
          },
        },
        {
          title: '变更后账单',
          valueType: 'digit',
          key: 'final_amount',
          formItemProps: { ...rulesHelper.text },
          colProps: { span: 6 },
          fieldProps: {
            style: { width: '100%' },
            disabled: true,
          },
        },
        {
          title: '完成日期',
          valueType: 'date',
          key: 'completed_time',
          colProps: { span: 12 },
          formItemProps: { ...rulesHelper.text },
          fieldProps: {
            style: { width: '100%' },
          },
        },
        //变更后账单金额 = 变更前账单金额 +/- 变更金额

        MyFormItems.UploadImages({
          key: 'completed_attachments',
          title: '附件',
          tooltip: '上限9张',
          uploadType: 'file',
          max: 9,
          colProps: { span: 24 },
          formItemProps: { ...rulesHelper.array },
        }),

        Selects?.ApprovalTemplates({
          key: 'approval_templates_id',
          title: '审批模版',
          // 选择审批模版
          params: {
            type: ApprovalTemplatesTypeEnum.ContractPayment.value,
            is_enabled: '1',
          },
          colProps: { span: 24 },
          formItemProps: { ...rulesHelper.number },
          fieldProps: {
            onChange: (e: any) => {
              // 确保e是有效值，并且使用正确的value字段
              if (e) {
                const templateId = typeof e === 'object' ? e.value : e;
                Apis.Approval.ApprovalTemplates.Show({
                  id: templateId,
                }).then((res) => {
                  setApprovalTemplates(res?.data?.approval_template_nodes);
                  form.setFieldsValue({
                    approval_templates_id: templateId,
                    node_approvers: res?.data?.approval_template_nodes?.map(
                      (item: any) => ({
                        ...item,
                        members: item?.approval_template_node_members?.map(
                          (member: any) => member?.company_employees_id,
                        ),
                      }),
                    ),
                  });
                });
              }
              // 不返回任何值，防止默认行为
            },
          },
        }),
        {
          valueType: 'dependency',
          name: ['approval_templates_id'],
          columns: ({ approval_templates_id }) => {
            return approval_templates_id
              ? [
                  {
                    valueType: 'formList',
                    dataIndex: 'node_approvers',
                    // title: '审批节点',
                    fieldProps: {
                      copyIconProps: false,
                      deleteIconProps: false,
                      creatorButtonProps: false,
                      actionRender: (field: any, action: any) => [
                        <Button
                          key="add"
                          type="link"
                          size="small"
                          onClick={() => {
                            const currentNodeType = form.getFieldValue([
                              'node_approvers',
                              field.name,
                              'node_type',
                            ]);
                            if (
                              currentNodeType ===
                              ApprovalTemplateNodesNodeTypeEnum.CC.value
                            ) {
                              message.warning('抄送节点不允许添加');
                              return;
                            }
                            action.add(
                              {
                                node_type:
                                  ApprovalTemplateNodesNodeTypeEnum.Approver
                                    .value,
                              },
                              field.name + 1,
                            );
                          }}
                        >
                          添加
                        </Button>,
                        <Button
                          key="delete"
                          type="link"
                          size="small"
                          danger
                          onClick={() => {
                            action.remove(field.name);
                          }}
                        >
                          删除
                        </Button>,
                      ],
                    },
                    formItemProps: {
                      ...rulesHelper.array,
                      wrapperCol: { span: 24 },
                    },
                    columns: [
                      {
                        valueType: 'group',
                        colProps: { span: 24 },
                        columns: [
                          MyFormItems.EnumSelect({
                            key: 'node_type',
                            // title: `类型`,
                            valueEnum: ApprovalTemplateNodesNodeTypeEnum,
                            colProps: { span: 5 },
                            formItemProps: {
                              ...rulesHelper.text,
                            },
                            fieldProps: {
                              disabled: true,
                            },
                          }),
                          {
                            // title: '节点名称',
                            key: 'name',
                            colProps: { span: 6 },
                            formItemProps: {
                              ...rulesHelper.text,
                            },
                            fieldProps: {
                              disabled: true,
                            },
                          },
                          {
                            valueType: 'dependency',
                            name: ['node_type'],
                            columns: ({ node_type }) => {
                              return [
                                Selects.Employees({
                                  key: 'members',
                                  title: ``,
                                  colProps: { span: 13 },
                                  formItemProps: {
                                    ...rulesHelper.array,
                                  },
                                  fieldProps: {
                                    mode: 'multiple',
                                    showSearch: true,
                                    maxCount:
                                      node_type ===
                                      ApprovalTemplateNodesNodeTypeEnum.Approver
                                        .value
                                        ? 1
                                        : 9,
                                    maxTagTextLength: 3,
                                    labelRender: (res: any) => {
                                      if (res?.label) {
                                        return res?.label;
                                      } else {
                                        return ApprovalTemplates?.map(
                                          (item: any) => {
                                            if (
                                              item?.node_type === node_type &&
                                              item
                                                ?.approval_template_node_members
                                                ?.length
                                            ) {
                                              return item?.approval_template_node_members?.map(
                                                (i: any) => {
                                                  if (
                                                    i?.company_employees_id ===
                                                    res?.value
                                                  ) {
                                                    return (
                                                      i?.company_employee
                                                        ?.name || ''
                                                    );
                                                  }
                                                },
                                              );
                                            }
                                          },
                                        );
                                      }
                                    },
                                  },
                                }),
                              ];
                            },
                          },
                        ],
                      },
                    ],
                  },
                ]
              : [];
          },
        },
      ]}
    />
  );
}
