import {
  MyBetaModalFormProps,
  MyButtons,
  MyFormItems,
  MyModalFormProps,
  rulesHelper,
} from '@/common';
import { Apis } from '@/gen/Apis';
import {
  HouseBillsTypeEnum,
  HouseChargeStandardsApportionmentMethodEnum,
  HouseChargeStandardsCalculationMethodEnum,
  HouseChargeStandardsCalculationModeEnum,
  HouseChargeStandardsCalculationPeriodEnum,
  HouseChargeStandardsPriceAlgorithmEnum,
  HouseChargeStandardsTypeEnum,
} from '@/gen/Enums';
import { BetaSchemaForm } from '@ant-design/pro-components';
import { Form, message } from 'antd';
import { useRef } from 'react';

export default function Create(props: MyBetaModalFormProps) {
  const [form] = Form.useForm();
  const actionRef = useRef<any>();

  return (
    <BetaSchemaForm<ApiTypes.HouseCharage.HouseChargeStandards.Store>
      {...MyModalFormProps.props}
      title={`创建收费标准`}
      wrapperCol={{ span: 24 }}
      width="600px"
      trigger={<MyButtons.Create title={`创建收费标准`} />}
      form={form}
      key={new Date().getTime()}
      onOpenChange={(open: any) => {
        if (open) {
          form.resetFields(); // 清空表单数据
        }
      }}
      onFinish={async (values: any) => {
        values?.grid_ranges?.forEach((res: { asset_projects_id: string }) => {
          res.asset_projects_id = props?.item?.id;
        });
        return Apis.HouseCharage.HouseChargeStandards.Store({
          ...values,
          asset_projects_id: props?.item?.id,
          type:
            values.charge_type === HouseBillsTypeEnum.PropertyFee.value ||
            values.charge_type === HouseBillsTypeEnum.MaintenanceFund.value
              ? HouseChargeStandardsTypeEnum.House.value
              : HouseChargeStandardsTypeEnum.Meter.value,
          is_apportionment:
            values.charge_type === HouseBillsTypeEnum.SharedWaterFee.value ||
            values.charge_type === HouseBillsTypeEnum.SharedElectricityFee.value
              ? 1
              : 0,
          // 按套
          calculation_mode:
            values?.calculation_method ===
            HouseChargeStandardsCalculationMethodEnum.PerUnit.value
              ? HouseChargeStandardsCalculationModeEnum.FixedAmount.value
              : values?.calculation_mode,
          // 按固定金额
          price_algorithm:
            values?.calculation_mode ===
              HouseChargeStandardsCalculationModeEnum.FixedAmount.value ||
            values?.calculation_method ===
              HouseChargeStandardsCalculationMethodEnum.PerUnit.value
              ? HouseChargeStandardsPriceAlgorithmEnum.Fixed.value
              : values?.price_algorithm,
          tiered_rates: values.tiered_rates?.map((res: any) => {
            return {
              ...res,
            };
          }),
          // 避免计费模式切换导致的价格异常
          price:
            values?.price_algorithm ===
            HouseChargeStandardsPriceAlgorithmEnum.Fixed.value
              ? values.price
              : 0,
        })
          .then(() => {
            props.reload?.();
            message.success('收费标准创建成功');
            return true;
          })
          .catch(() => false);
      }}
      columns={[
        {
          key: 'name',
          title: '收费标准名称',
          colProps: { span: 24 },
          formItemProps: { ...rulesHelper.text },
        },
        MyFormItems.EnumRadio({
          key: 'charge_type',
          title: '收费项目',
          colProps: { span: 24 },
          valueEnum: HouseBillsTypeEnum,
          required: true,
        }),
        {
          name: ['charge_type'],
          valueType: 'dependency',
          columns: ({ charge_type }: any) => {
            return charge_type === HouseBillsTypeEnum.SharedWaterFee.value ||
              charge_type === HouseBillsTypeEnum.SharedElectricityFee.value
              ? [
                  MyFormItems.EnumRadio({
                    key: 'calculation_method',
                    title: '分摊方式',
                    colProps: { span: 18 },
                    valueEnum: HouseChargeStandardsApportionmentMethodEnum,
                    required: true,
                  }),
                ]
              : [];
          },
        },

        // Selects?.AssetProjects({
        //   key: 'asset_projects_id',
        //   title: '项目',
        //   colProps: { span: 12 },
        //   formItemProps: { ...rulesHelper.text },
        // }),
        {
          name: ['charge_type'],
          valueType: 'dependency',
          columns: ({ charge_type }: any) => {
            return charge_type === HouseBillsTypeEnum.PropertyFee.value ||
              charge_type === HouseBillsTypeEnum.MaintenanceFund.value
              ? [
                  MyFormItems.EnumRadio({
                    key: 'calculation_method',
                    title: '计量单位',
                    colProps: { span: 16 },
                    valueEnum: () => {
                      let obj: any = JSON.parse(
                        JSON.stringify(
                          HouseChargeStandardsCalculationMethodEnum,
                        ),
                      );
                      delete obj.ElectricityUsage;
                      delete obj.WaterUsage;
                      return obj;
                    },
                    required: true,
                  }),
                ]
              : charge_type === HouseBillsTypeEnum.WaterFee.value ||
                charge_type === HouseBillsTypeEnum.ElectricityFee.value ||
                charge_type === HouseBillsTypeEnum.SharedWaterFee.value ||
                charge_type === HouseBillsTypeEnum.SharedElectricityFee.value
              ? [
                  MyFormItems.EnumRadio({
                    key: 'calculation_method',
                    title: '计量单位',
                    colProps: { span: 16 },
                    valueEnum: () => {
                      let obj: any = JSON.parse(
                        JSON.stringify(
                          HouseChargeStandardsCalculationMethodEnum,
                        ),
                      );
                      delete obj.ChargeableArea;
                      delete obj.BuiltArea;
                      delete obj.InsideArea;
                      delete obj.PerUnit;
                      return obj;
                    },
                    required: true,
                  }),
                ]
              : [];
          },
        },
        {
          name: ['calculation_method'],
          valueType: 'dependency',
          columns: ({ calculation_method }: any) => {
            return calculation_method ===
              HouseChargeStandardsCalculationMethodEnum.PerUnit.value
              ? [
                  {
                    key: 'price',
                    title: '固定单价',
                    colProps: { span: 10 },
                    fieldProps: {
                      addonAfter: '元',
                    },
                    formItemProps: { ...rulesHelper.number },
                  },
                ]
              : !calculation_method &&
                calculation_method !==
                  HouseChargeStandardsCalculationMethodEnum.PerUnit.value
              ? []
              : [
                  MyFormItems.EnumRadio({
                    key: 'calculation_mode',
                    title: '计费模式',
                    colProps: { span: 12 },
                    valueEnum: HouseChargeStandardsCalculationModeEnum,
                    required: true,
                  }),
                ];
          },
        },

        {
          name: ['calculation_mode'],
          valueType: 'dependency',
          columns: ({ calculation_mode }: any) => {
            return calculation_mode ===
              HouseChargeStandardsCalculationModeEnum.FixedAmount.value
              ? [
                  {
                    key: 'price',
                    title: '固定单价',
                    colProps: { span: 10 },
                    fieldProps: {
                      addonAfter: '元',
                    },
                    formItemProps: { ...rulesHelper.number },
                  },
                ]
              : calculation_mode ===
                HouseChargeStandardsCalculationModeEnum.QuantityPrice.value
              ? [
                  MyFormItems.EnumRadio({
                    key: 'price_algorithm',
                    title: '计费算法',
                    colProps: { span: 14 },
                    valueEnum: HouseChargeStandardsPriceAlgorithmEnum,
                    required: true,
                    // fieldProps: {
                    //   onChange: () => {
                    //     // 切换计费算法时清空阶梯配置
                    //     form.setFieldValue('scheme', undefined);
                    //   },
                    // },
                  }),
                  {
                    name: ['price_algorithm'],
                    valueType: 'dependency',
                    columns: ({ price_algorithm }: any) => {
                      return price_algorithm ===
                        HouseChargeStandardsPriceAlgorithmEnum.Fixed.value
                        ? [
                            {
                              key: 'price',
                              title: '固定单价',
                              colProps: { span: 10 },
                              fieldProps: {
                                addonAfter: '元',
                              },
                              formItemProps: { ...rulesHelper.number },
                            },
                          ]
                        : price_algorithm ===
                          HouseChargeStandardsPriceAlgorithmEnum.Tiered.value
                        ? [
                            {
                              valueType: 'formList',
                              dataIndex: 'tiered_rates',
                              title: '阶梯标准',
                              formItemProps: { ...rulesHelper.array },
                              initialValue: [
                                {
                                  start: 0,
                                  end: null,
                                  price: null,
                                },
                              ],
                              fieldProps: {
                                actionRef: actionRef,
                                copyIconProps: false,
                                // deleteIconProps: false,
                              },
                              columns: [
                                {
                                  valueType: 'group',
                                  colProps: { span: 24 },
                                  columns: [
                                    {
                                      key: 'min_quantity',
                                      colProps: { span: 10 },
                                      title: '起始值',
                                      valueType: 'number',
                                      fieldProps: {
                                        min: 0,
                                        addonBefore: (
                                          _: any,
                                          {
                                            field,
                                          }: { field: { index: number[] } },
                                        ) => `第${field.index[1] + 1}阶梯`,
                                      },
                                      width: '100%',
                                      formItemProps: { ...rulesHelper.number },
                                    },
                                    {
                                      key: 'max_quantity',
                                      colProps: { span: 6 },
                                      title: '结束值',
                                      valueType: 'number',
                                      width: '100%',
                                      formItemProps: { ...rulesHelper.number },
                                      fieldProps: { maxLength: 12 },
                                    },
                                    {
                                      key: 'price',
                                      colProps: { span: 8 },
                                      title: '阶梯单价',
                                      valueType: 'number',
                                      fieldProps: {
                                        addonAfter: '元',
                                        min: 0,
                                      },
                                      formItemProps: { ...rulesHelper.number },
                                    },
                                  ],
                                },
                              ],
                            },
                          ]
                        : price_algorithm ===
                          HouseChargeStandardsPriceAlgorithmEnum.Peak.value
                        ? [
                            {
                              valueType: 'formList',
                              dataIndex: 'tiered_rates',
                              title: '阶梯标准',
                              formItemProps: { ...rulesHelper.array },
                              initialValue: [
                                {
                                  start: 0,
                                  end: null,
                                  price: null,
                                },
                              ],
                              fieldProps: {
                                actionRef: actionRef,
                                copyIconProps: false,
                                // deleteIconProps: false,
                              },
                              columns: [
                                {
                                  valueType: 'group',
                                  colProps: { span: 24 },
                                  columns: [
                                    {
                                      key: 'min_quantity',
                                      colProps: { span: 10 },
                                      title: '起始值',
                                      valueType: 'number',
                                      fieldProps: {
                                        min: 0,
                                        addonBefore: (
                                          _: any,
                                          {
                                            field,
                                          }: { field: { name: number[] } },
                                        ) => `第${field.name[1] + 1}阶梯`,
                                      },
                                      width: '100%',
                                      formItemProps: { ...rulesHelper.number },
                                    },
                                    {
                                      key: 'max_quantity',
                                      colProps: { span: 6 },
                                      title: '结束值',
                                      valueType: 'number',
                                      width: '100%',
                                      formItemProps: { ...rulesHelper.number },
                                      fieldProps: { maxLength: 12 },
                                    },
                                    {
                                      key: 'price',
                                      colProps: { span: 8 },
                                      title: '阶梯单价',
                                      valueType: 'number',
                                      fieldProps: {
                                        addonAfter: '元',
                                        min: 0,
                                      },
                                      formItemProps: { ...rulesHelper.number },
                                    },
                                  ],
                                },
                              ],
                            },
                          ]
                        : [];
                    },
                  },
                ]
              : [];
          },
        },
        {
          name: ['price', 'price_algorithm'],
          valueType: 'dependency',
          columns: ({ price, price_algorithm }: any) => {
            return price ||
              price_algorithm ===
                HouseChargeStandardsPriceAlgorithmEnum.Tiered.value ||
              price_algorithm ===
                HouseChargeStandardsPriceAlgorithmEnum.Peak.value
              ? [
                  {
                    valueType: 'group',
                    columns: [
                      MyFormItems.EnumRadio({
                        key: 'calculation_period',
                        title: '账单计费周期',
                        colProps: { span: 14 },
                        valueEnum: HouseChargeStandardsCalculationPeriodEnum,
                        required: true,
                      }),
                      {
                        key: 'auto_date',
                        title: '账单自动生成日期',
                        colProps: { span: 10 },
                        valueType: 'date',
                        width: '100%',
                      },
                      {
                        key: 'remark',
                        title: '备注',
                        colProps: { span: 24 },
                        valueType: 'textarea',
                        fieldProps: {
                          rows: 4,
                          maxLength: 500,
                          showCount: true,
                        },
                      },
                    ],
                  },
                ]
              : [];
          },
        },
      ]}
    />
  );
}
