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

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

  return (
    <BetaSchemaForm<ApiTypes.Refund.Refunds.Store>
      {...MyModalFormProps.props}
      title={`退款申请单`}
      trigger={
        <MyButtons.Default
          title="申请退款"
          // disabled={props?.item?.bill_status !== 'Paid'}
        />
      }
      layout="horizontal"
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 20 }}
      labelAlign="left"
      width="600px"
      form={form}
      key={new Date().getDate()}
      onOpenChange={(open: any) => {
        if (open && props.item) {
          form.resetFields();
          form.setFieldsValue({
            ...props.item,
          });
        }
      }}
      onFinish={async (values: any) =>
        Apis.Refund.Refunds.Store({
          ...values,
          business_id: props.item?.id ?? '',
          type: 'HouseBill',
        })
          .then(() => {
            props.reload?.();
            message.success(props.title + '成功');
            return true;
          })
          .catch(() => false)
      }
      columns={[
        Selects?.CompanyAccounts({
          key: 'company_receipt_accounts_id',
          title: '付款账户',
          colProps: { span: 24 },
          formItemProps: { ...rulesHelper.number },
          fieldProps: {
            showSearch: true,
          },
        }),
        {
          key: 'refund_amount',
          title: '退款金额',
          valueType: 'digit',
          colProps: { span: 24 },
          fieldProps: {
            style: {
              width: '100%',
            },
            addonAfter: '元',
            max: props.item?.total_paid_amount,
            placeholder: `请输入退款金额（最大${props.item?.total_paid_amount}元）`,
          },
          formItemProps: { ...rulesHelper.number },
        },
        {
          key: 'payee_name',
          title: '收款人',
          colProps: { span: 24 },
          formItemProps: { ...rulesHelper.text },
        },
        {
          key: 'payee_bank',
          title: '收款银行',
          colProps: { span: 24 },
          formItemProps: { ...rulesHelper.text },
        },
        {
          key: 'payee_account',
          title: '收款账号',
          colProps: { span: 24 },
          formItemProps: { ...rulesHelper.text },
        },
        {
          title: '退款原因',
          key: 'remark',
          valueType: 'textarea',
          colProps: { span: 24 },
          formItemProps: { ...rulesHelper.text },
        },
        Selects?.ApprovalTemplates({
          key: 'approval_templates_id',
          title: '审批模版',
          params: { type: props.item?.approval_type || '', 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,
                    },
                    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: ({}) => {
                              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) => {
                                      console.log(res, '222');
                                      if (res?.label) {
                                        return res?.label;
                                      } else {
                                        return ApprovalTemplates?.map(
                                          (item: any) => {
                                            if (
                                              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 || ''
                                                    );
                                                  }
                                                },
                                              );
                                            }
                                          },
                                        );
                                      }
                                    },
                                  },
                                }),
                              ];
                            },
                          },
                        ],
                      },
                    ],
                  },
                ]
              : [];
          },
        },
      ]}
    />
  );
}
