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

export default function Create(props: MyBetaModalFormProps) {
  const [form] = Form.useForm();

  return (
    <BetaSchemaForm<ApiTypes.HouseCharge.HouseChargeTasks.Store>
      {...MyModalFormProps.props}
      title={`创建${props.title}`}
      width="480px"
      layout="horizontal"
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 16 }}
      labelAlign="left"
      key={new Date().getTime()}
      trigger={<MyButtons.Default title="点击生成" size="small" type="link" />}
      form={form}
      onOpenChange={(open: any) => {
        if (open) {
          form.resetFields();
          if (props?.item?.asset_projects_id) {
            form.setFieldsValue({
              asset_projects_id: props?.item?.asset_projects_id,
            });
          }
          if (props?.item?.house_charge_standards_id) {
            form.setFieldsValue({
              house_charge_standards_id: props?.item?.house_charge_standards_id,
            });
          }
          if (props?.item?.month) {
            form.setFieldsValue({
              month: `${props?.item?.year}-${String(
                props?.item?.month,
              ).padStart(2, '0')}`,
              start_date: rulesHelper.getMonthStartDate(
                `${props?.item?.year}-${String(props?.item?.month).padStart(
                  2,
                  '0',
                )}`,
              ),
              end_date: rulesHelper.getMonthEndDate(
                `${props?.item?.year}-${String(props?.item?.month).padStart(
                  2,
                  '0',
                )}`,
              ),
            });
          }
        }
      }}
      onFinish={async (values) =>
        Apis.HouseCharge.HouseChargeTasks.Store(values)
          .then((response) => {
            const taskId = response?.data?.id;
            if (taskId) {
              return Apis.HouseCharge.HouseChargeTasks.ExecuteTask({
                id: taskId,
              })
                .then(() => {
                  props.reload?.();
                  message.success(props.title + '账单任务创建并执行成功');
                  return true;
                })
                .catch(() => {
                  props.reload?.();
                  message.success(props.title + '账单任务创建成功，但执行失败');
                  return true;
                });
            } else {
              props.reload?.();
              message.success(props.title + '账单任务创建成功');
              return true;
            }
          })
          .catch(() => false)
      }
      columns={[
        Selects?.AssetProjects({
          title: '选择项目',
          key: 'asset_projects_id',
          colProps: { span: 24 },
          formItemProps: { ...rulesHelper.text },
          fieldProps: {
            onChange: () => {
              form.setFieldsValue({
                house_charge_standards_id: undefined,
              });
            },
          },
        }),
        {
          valueType: 'dependency',
          name: ['asset_projects_id'],
          columns: ({ asset_projects_id }) => {
            return [
              Selects?.ChargeStandard({
                title: '选择收费标准',
                key: 'house_charge_standards_id',
                params: {
                  asset_projects_id: asset_projects_id,
                  charge_type: ['PropertyFee', 'MaintenanceFund', 'CarPortFee'],
                },
                colProps: { span: 24 },
                formItemProps: { ...rulesHelper.text },
                fieldProps: {
                  showSearch: true,
                  labelRender: (res: any) => {
                    console.log(res, '222');
                    if (res?.label) {
                      return res?.label;
                    } else {
                      return props?.item?.name;
                    }
                  },
                },
              }),
            ];
          },
        },
        {
          key: 'month',
          title: '选择生成月份',
          valueType: 'date',
          colProps: { span: 24 },
          fieldProps: {
            picker: 'month',
            format: 'YYYY-MM',
            valueFormat: 'YYYY-MM',
            style: {
              width: '100%',
            },
            onChange: (e: any, dateString: string) => {
              form.setFieldsValue({
                start_date: rulesHelper.getMonthStartDate(dateString),
                end_date: rulesHelper.getMonthEndDate(dateString),
              });
            },
          },
          formItemProps: { ...rulesHelper.text },
        },
        {
          key: 'start_date',
          title: '计费开始日期',
          valueType: 'date',
          colProps: { span: 24 },
          fieldProps: {
            style: {
              width: '100%',
            },
          },
          formItemProps: { ...rulesHelper.text },
        },
        {
          key: 'end_date',
          title: '计费结束日期',
          valueType: 'date',
          colProps: { span: 24 },
          fieldProps: {
            style: {
              width: '100%',
            },
          },
          formItemProps: { ...rulesHelper.text },
        },

        {
          colProps: { span: 24 },
          formItemProps: { labelCol: { span: 0 }, wrapperCol: { span: 24 } },
          renderFormItem: () => (
            <span style={{ color: '#5b5b5bff' }}>
              提示：【确认】后，系统将自动执行账单生成任务。
            </span>
          ),
        },
      ]}
    />
  );
}
