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,
} from '@/gen/Enums';
import { BetaSchemaForm } from '@ant-design/pro-components';
import { Form, message } from 'antd';
import { useRef } from 'react';

const chargeTypeConfig: Record<
  string,
  {
    label: string;
    type: 'House' | 'Meter' | 'CarPort';
    calcFilter: string[];
    hasApportionment: boolean;
  }
> = {
  [HouseBillsTypeEnum.PropertyFee.value]: {
    label: '物业费',
    type: 'House',
    calcFilter: ['ElectricityUsage', 'WaterUsage'],
    hasApportionment: false,
  },
  [HouseBillsTypeEnum.MaintenanceFund.value]: {
    label: '维修基金',
    type: 'House',
    calcFilter: ['ElectricityUsage', 'WaterUsage'],
    hasApportionment: false,
  },
  [HouseBillsTypeEnum.WaterFee.value]: {
    label: '水费',
    type: 'Meter',
    calcFilter: [
      'ChargeableArea',
      'BuiltArea',
      'InsideArea',
      'ElectricityUsage',
    ],
    hasApportionment: false,
  },
  [HouseBillsTypeEnum.ElectricityFee.value]: {
    label: '电费',
    type: 'Meter',
    calcFilter: ['ChargeableArea', 'BuiltArea', 'InsideArea', 'WaterUsage'],
    hasApportionment: false,
  },
  [HouseBillsTypeEnum.SharedWaterFee.value]: {
    label: '公摊水费',
    type: 'Meter',
    calcFilter: [
      'ChargeableArea',
      'BuiltArea',
      'InsideArea',
      'ElectricityUsage',
    ],
    hasApportionment: true,
  },
  [HouseBillsTypeEnum.SharedElectricityFee.value]: {
    label: '公摊电费',
    type: 'Meter',
    calcFilter: ['ChargeableArea', 'BuiltArea', 'InsideArea', 'WaterUsage'],
    hasApportionment: true,
  },
  [HouseBillsTypeEnum.CarPortFee.value]: {
    label: '车位管理费',
    type: 'CarPort',
    calcFilter: ['ElectricityUsage', 'WaterUsage'],
    hasApportionment: false,
  },
};

function getCalculationMethodEnum(filterKeys: string[]) {
  const obj: any = JSON.parse(
    JSON.stringify(HouseChargeStandardsCalculationMethodEnum),
  );
  filterKeys.forEach((key) => {
    delete obj[key];
  });
  return obj;
}

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

  return (
    <BetaSchemaForm<ApiTypes.HouseCharge.HouseChargeStandards.Store>
      {...MyModalFormProps.props}
      form={form}
      title="新增收费标准"
      layout="horizontal"
      labelCol={{ span: 5 }}
      wrapperCol={{ span: 19 }}
      labelAlign="left"
      width="680px"
      trigger={<MyButtons.Create title="新增收费标准" />}
      key={new Date().getTime()}
      onOpenChange={(open: any) => {
        if (open) {
          form.resetFields();
        }
      }}
      onFinish={async (values: any) => {
        const config = chargeTypeConfig[values.charge_type];
        return Apis.HouseCharge.HouseChargeStandards.Store({
          ...values,
          type: config?.type,
          is_apportionment: config?.hasApportionment ? 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?.calculation_method ===
              HouseChargeStandardsCalculationMethodEnum.PerUnit.value
              ? values.price
              : 0,
          late_fee_rate: values.has_late_fee ? values.late_fee_rate : '',
          late_fee_start_days: values.has_late_fee
            ? values.late_fee_start_days
            : '',
          late_fee_cap_days: values.has_late_fee
            ? values.late_fee_cap_days
            : '',
        })
          .then(() => {
            props.reload?.();
            message.success('收费标准创建成功');
            return true;
          })
          .catch(() => false);
      }}
      columns={[
        Selects?.AssetProjects({
          key: 'asset_projects_id',
          title: '选择项目',
          colProps: { span: 24 },
          required: true,
          fieldProps: {
            onChange: () => {
              form.setFieldValue('company_receipt_accounts_id', undefined);
            },
          },
        }),
        {
          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,
                },
                colProps: { span: 24 },
                formItemProps: { ...rulesHelper.text },
              }),
            ];
          },
        },
        MyFormItems.EnumRadio({
          key: 'charge_type',
          title: '收费项目',
          colProps: { span: 24 },
          valueEnum: HouseBillsTypeEnum,
          required: true,
          fieldProps: {
            buttonStyle: 'solid',
            onChange: () => {
              form.setFieldValue('calculation_method', undefined);
              form.setFieldValue('calculation_mode', undefined);
              form.setFieldValue('price', undefined);
              form.setFieldValue('price_algorithm', undefined);
              form.setFieldValue('apportionment_method', undefined);
            },
          },
        }),
        {
          name: ['charge_type'],
          valueType: 'dependency',
          columns: ({ charge_type }: any) => {
            const config = chargeTypeConfig[charge_type];
            if (!config) return [];
            const cols: any[] = [];
            if (config.hasApportionment) {
              cols.push(
                MyFormItems.EnumRadio({
                  key: 'apportionment_method',
                  title: '分摊方式',
                  colProps: { span: 24 },
                  valueEnum: () => {
                    const obj: any = JSON.parse(
                      JSON.stringify(
                        HouseChargeStandardsApportionmentMethodEnum,
                      ),
                    );
                    delete obj.FixedRatio;
                    return obj;
                  },
                  required: true,
                }),
              );
            }
            cols.push(
              MyFormItems.EnumRadio({
                key: 'calculation_method',
                title: '计量单位',
                colProps: { span: 24 },
                valueEnum: () => getCalculationMethodEnum(config.calcFilter),
                required: true,
                fieldProps: {
                  buttonStyle: 'solid',
                  onChange: () => {
                    form.setFieldValue('calculation_mode', undefined);
                    form.setFieldValue('price', undefined);
                    form.setFieldValue('price_algorithm', undefined);
                  },
                },
              }),
            );
            return cols;
          },
        },
        {
          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: () => {
                      const 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: {
                      buttonStyle: 'solid',
                      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: '固定单价',
                              valueType: 'digit',
                              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,
                              },
                              columns: [
                                {
                                  valueType: 'group',
                                  colProps: { span: 24 },
                                  columns: [
                                    {
                                      key: 'min_quantity',
                                      colProps: { span: 9 },
                                      valueType: 'digit',
                                      fieldProps: {
                                        min: 0,
                                        addonBefore: '阶梯范围',
                                        placeholder: '起始值',
                                      },
                                      width: '100%',
                                      formItemProps: {
                                        ...rulesHelper.number,
                                      },
                                    },
                                    {
                                      key: 'max_quantity',
                                      colProps: { span: 5 },
                                      valueType: 'digit',
                                      width: '100%',
                                      formItemProps: {
                                        ...rulesHelper.number,
                                      },
                                      fieldProps: {
                                        min: 0,
                                        max: 999,
                                        placeholder: '结束值',
                                      },
                                    },
                                    {
                                      key: 'price',
                                      colProps: { span: 10 },
                                      valueType: 'digit',
                                      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,
                              },
                              columns: [
                                {
                                  valueType: 'group',
                                  colProps: { span: 24 },
                                  columns: [
                                    {
                                      key: 'min_quantity',
                                      colProps: { span: 9 },
                                      valueType: 'digit',
                                      fieldProps: {
                                        min: 0,
                                        addonBefore: '阶梯范围',
                                        placeholder: '起始值',
                                      },
                                      width: '100%',
                                      formItemProps: {
                                        ...rulesHelper.number,
                                      },
                                    },
                                    {
                                      key: 'max_quantity',
                                      colProps: { span: 5 },
                                      valueType: 'digit',
                                      width: '100%',
                                      formItemProps: {
                                        ...rulesHelper.number,
                                      },
                                      fieldProps: {
                                        min: 0,
                                        max: 999,
                                        placeholder: '结束值',
                                      },
                                    },
                                    {
                                      key: 'price',
                                      colProps: { span: 10 },
                                      valueType: 'digit',
                                      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%',
                        fieldProps: {
                          onChange: () => {
                            form.setFieldValue(
                              'late_fee_start_days',
                              undefined,
                            );
                            form.setFieldValue('late_fee_rate', undefined);
                            form.setFieldValue('late_fee_cap_days', undefined);
                          },
                        },
                      },
                      {
                        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: 'digit',
                                  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: {
                          maxLength: 100,
                          showCount: true,
                        },
                      },
                    ],
                  },
                ]
              : [];
          },
        },
      ]}
    />
  );
}
