import {
  MyBetaModalFormProps,
  MyButtons,
  MyFormItems,
  MyModalFormProps,
  rulesHelper,
} from '@/common';
import { Selects } from '@/components/Select';
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 }}
      // 基础表单
      layout="horizontal"
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 24 }}
      labelAlign="left"
      width="680px"
      trigger={<MyButtons.Create title={`创建收费标准`} />}
      form={form}
      key={new Date().getTime()}
      onOpenChange={(open: any) => {
        if (open) {
          form.resetFields(); // 清空表单数据
        }
      }}
      onFinish={async (values: any) =>
        Apis.HouseCharage.HouseChargeStandards.Store({
          ...values,
          asset_projects_id: props?.item?.id || values?.asset_projects_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?.calculation_mode ===
              HouseChargeStandardsCalculationModeEnum.FixedAmount.value
              ? values.price
              : 0,

          // is_tiered:
          //   values?.price_algorithm ===
          //   HouseChargeStandardsPriceAlgorithmEnum.Fixed.value
          //     ? 0
          //     : 1,
        })
          .then(() => {
            props.reload?.();
            message.success('收费标准创建成功');
            return true;
          })
          .catch(() => false)
      }
      columns={[
        ...(props?.item?.id
          ? []
          : [
              Selects?.AssetProjects({
                key: 'asset_projects_id',
                title: '选择项目',
                colProps: { span: 24 },
                required: true,
              }),
            ]),

        {
          key: 'name',
          title: '收费名称',
          colProps: { span: 24 },
          formItemProps: { ...rulesHelper.text },
        },
        {
          valueType: 'dependency',
          name: ['asset_projects_id'],
          columns: ({ asset_projects_id }) => {
            return [
              Selects?.ProjectAccounts({
                title: '收款账户',
                key: 'company_receipt_accounts_id',
                params: {
                  asset_projects_id: asset_projects_id || props?.item?.id || 0,
                },
                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: 24 },
                    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: 24 },
                    valueEnum: () => {
                      let obj: any = JSON.parse(
                        JSON.stringify(
                          HouseChargeStandardsCalculationMethodEnum,
                        ),
                      );
                      delete obj.ElectricityUsage;
                      delete obj.WaterUsage;
                      return obj;
                    },
                    required: true,
                    fieldProps: {
                      onChange: () => {
                        // 切换计量单位时清空计费模式
                        form.setFieldValue('calculation_mode', undefined);
                        form.setFieldValue('price', undefined);
                        form.setFieldValue('price_algorithm', undefined);
                      },
                    },
                  }),
                ]
              : 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: 24 },
                    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,
                    fieldProps: {
                      onChange: () => {
                        // 切换计量单位时清空计费模式
                        form.setFieldValue('calculation_mode', undefined);
                        form.setFieldValue('price', undefined);
                        form.setFieldValue('price_algorithm', undefined);
                      },
                    },
                  }),
                ]
              : [];
          },
        },
        {
          name: ['calculation_method'],
          valueType: 'dependency',
          columns: ({ calculation_method }: any) => {
            return calculation_method ===
              HouseChargeStandardsCalculationMethodEnum.PerUnit.value
              ? [
                  {
                    key: 'price',
                    title: '固定单价',
                    colProps: { span: 24 },
                    fieldProps: {
                      addonAfter: '元',
                    },
                    formItemProps: { ...rulesHelper.number },
                  },
                ]
              : !calculation_method &&
                calculation_method !==
                  HouseChargeStandardsCalculationMethodEnum.PerUnit.value
              ? []
              : [
                  MyFormItems.EnumRadio({
                    key: 'calculation_mode',
                    title: '计费模式',
                    colProps: { span: 24 },
                    // valueEnum: HouseChargeStandardsCalculationModeEnum,
                    valueEnum: () => {
                      let obj: any = JSON.parse(
                        JSON.stringify(HouseChargeStandardsCalculationModeEnum),
                      );
                      delete obj.FixedAmount;
                      return obj;
                    },
                    required: true,
                  }),
                ];
          },
        },

        {
          name: ['calculation_mode'],
          valueType: 'dependency',
          columns: ({ calculation_mode }: any) => {
            return calculation_mode ===
              HouseChargeStandardsCalculationModeEnum.FixedAmount.value
              ? [
                  {
                    key: 'price',
                    title: '固定单价',
                    colProps: { span: 24 },
                    fieldProps: {
                      addonAfter: '元',
                    },
                    formItemProps: { ...rulesHelper.number },
                  },
                ]
              : calculation_mode ===
                HouseChargeStandardsCalculationModeEnum.QuantityPrice.value
              ? [
                  MyFormItems.EnumRadio({
                    key: 'price_algorithm',
                    title: '计费算法',
                    colProps: { span: 24 },
                    valueEnum: HouseChargeStandardsPriceAlgorithmEnum,
                    required: true,
                    fieldProps: {
                      onChange: () => {
                        // 切换计费算法时清空阶梯配置
                        form.setFieldValue('price', undefined);
                        form.setFieldValue('tiered_rates', undefined);
                      },
                    },
                  }),
                  {
                    name: ['price_algorithm'],
                    valueType: 'dependency',
                    columns: ({ price_algorithm }: any) => {
                      return price_algorithm ===
                        HouseChargeStandardsPriceAlgorithmEnum.Fixed.value
                        ? [
                            {
                              key: 'price',
                              title: '固定单价',
                              colProps: { span: 24 },
                              fieldProps: {
                                addonAfter: '元',
                                max: 99,
                              },
                              formItemProps: { ...rulesHelper.number },
                            },
                          ]
                        : price_algorithm ===
                          HouseChargeStandardsPriceAlgorithmEnum.Tiered.value
                        ? [
                            {
                              valueType: 'formList',
                              dataIndex: 'tiered_rates',
                              title: '阶梯标准',
                              formItemProps: { ...rulesHelper.array },
                              initialValue: [
                                {
                                  min_quantity: 0,
                                  max_quantity: null,
                                  price: null,
                                },
                              ],
                              fieldProps: {
                                actionRef: actionRef,
                                copyIconProps: false,
                                // deleteIconProps: false,
                              },
                              columns: [
                                {
                                  valueType: 'group',
                                  colProps: { span: 24 },
                                  columns: [
                                    {
                                      key: 'min_quantity',
                                      colProps: { span: 9 },
                                      // title: '起始值',
                                      valueType: 'number',
                                      fieldProps: {
                                        min: 0,
                                        addonBefore: '阶梯范围',
                                        placeholder: '起始值',
                                      },
                                      width: '100%',
                                      formItemProps: { ...rulesHelper.number },
                                    },
                                    {
                                      key: 'max_quantity',
                                      colProps: { span: 5 },
                                      // title: '结束值',
                                      valueType: 'number',
                                      width: '100%',
                                      formItemProps: { ...rulesHelper.number },
                                      fieldProps: {
                                        min: 0,
                                        max: 999,
                                        placeholder: '结束值',
                                      },
                                    },
                                    {
                                      key: 'price',
                                      colProps: { span: 10 },
                                      // title: '阶梯单价',
                                      valueType: 'number',
                                      fieldProps: {
                                        addonBefore: '阶梯单价',
                                        addonAfter: '元',
                                        min: 0,
                                        max: 999,
                                      },
                                      formItemProps: { ...rulesHelper.number },
                                    },
                                  ],
                                },
                              ],
                            },
                          ]
                        : price_algorithm ===
                          HouseChargeStandardsPriceAlgorithmEnum.Peak.value
                        ? [
                            {
                              valueType: 'formList',
                              dataIndex: 'tiered_rates',
                              title: '阶梯标准',
                              formItemProps: { ...rulesHelper.array },
                              initialValue: [
                                {
                                  min_quantity: 0,
                                  max_quantity: null,
                                  price: null,
                                },
                              ],
                              fieldProps: {
                                actionRef: actionRef,
                                copyIconProps: false,
                                // deleteIconProps: false,
                              },
                              columns: [
                                {
                                  valueType: 'group',
                                  colProps: { span: 24 },
                                  columns: [
                                    {
                                      key: 'min_quantity',
                                      colProps: { span: 9 },
                                      // title: '起始值',
                                      valueType: 'number',
                                      fieldProps: {
                                        min: 0,
                                        addonBefore: '阶梯范围',
                                        placeholder: '起始值',
                                      },
                                      width: '100%',
                                      formItemProps: { ...rulesHelper.number },
                                    },
                                    {
                                      key: 'max_quantity',
                                      colProps: { span: 5 },
                                      // title: '结束值',
                                      valueType: 'number',
                                      width: '100%',
                                      formItemProps: { ...rulesHelper.number },
                                      fieldProps: {
                                        min: 0,
                                        max: 999,
                                        placeholder: '结束值',
                                      },
                                    },
                                    {
                                      key: 'price',
                                      colProps: { span: 10 },
                                      // title: '阶梯单价',
                                      valueType: 'number',
                                      fieldProps: {
                                        addonBefore: '阶梯单价',
                                        addonAfter: '元',
                                        min: 0,
                                        max: 999,
                                      },
                                      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: 24 },
                        valueEnum: HouseChargeStandardsCalculationPeriodEnum,
                        required: true,
                      }),
                      {
                        key: 'auto_date',
                        title: '生成日期',
                        colProps: { span: 24 },
                        tooltip: '系统将按该设置日期自动生成第一期的账单',
                        valueType: 'date',
                        width: '100%',
                        formItemProps: { ...rulesHelper.text },
                      },
                      {
                        key: 'has_late_fee',
                        title: '启用滞纳金',
                        colProps: { span: 24 },
                        valueType: 'switch',
                        width: '100%',
                      },
                      {
                        name: ['has_late_fee'],
                        valueType: 'dependency',
                        columns: ({ has_late_fee }: any) => {
                          return has_late_fee
                            ? [
                                {
                                  key: 'late_fee_start_days',
                                  title: '起算天数',
                                  colProps: { span: 24 },
                                  formItemProps: { ...rulesHelper.number },
                                  fieldProps: {
                                    mix: 1,
                                    addonBefore: '生成账单后',
                                    addonAfter: '天',
                                    placeholder:
                                      '请输入按账单生成后多少天后开始收取',
                                  },
                                },
                                {
                                  key: 'late_fee_rate',
                                  title: '收取费率',
                                  valueType: 'number',
                                  colProps: { span: 24 },
                                  formItemProps: { ...rulesHelper.number },
                                  fieldProps: {
                                    addonBefore: '每日',
                                    addonAfter: '%',
                                    max: 100,
                                  },
                                },
                                {
                                  key: 'late_fee_cap_days',
                                  title: '封顶天数',
                                  colProps: { span: 24 },
                                  formItemProps: { ...rulesHelper.number },
                                  fieldProps: {
                                    mix: 1,
                                    placeholder: '请输入封顶天数',
                                    addonAfter: '天',
                                  },
                                },
                              ]
                            : [];
                        },
                      },
                      {
                        key: 'remark',
                        title: '备注',
                        colProps: { span: 24 },
                        valueType: 'textarea',
                        fieldProps: {
                          // rows: 2,
                          maxLength: 100,
                          showCount: true,
                        },
                      },
                    ],
                  },
                ]
              : [];
          },
        },
      ]}
    />
  );
}
