import {
  MyBetaModalFormProps,
  MyButtons,
  MyModalFormProps,
  rulesHelper,
} from '@/common';
import { Selects } from '@/components/Select';
import { Apis } from '@/gen/Apis';
import { HouseMeterReadingsOperationTypeEnum } from '@/gen/Enums';
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.Meter.HouseMeterReadings.Update>
      {...MyModalFormProps.props}
      title={`修正抄表数据`}
      layout="horizontal"
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 18 }}
      labelAlign="left"
      width="600px"
      key={new Date().getTime()}
      trigger={<MyButtons.Default title={`修正`} type="primary" />}
      form={form}
      onOpenChange={(open: any) => {
        if (open && props.item) {
          form.setFieldsValue(props.item);
        }
      }}
      onFinish={async (values) =>
        Apis.Meter.HouseMeterReadings.Update({
          ...values,
          id: props.item?.id ?? 0,
          house_meters_id: props.item?.house_meters_id,
          previous_reading: props.item?.previous_reading,
          operation_type:
            HouseMeterReadingsOperationTypeEnum.CorrectReading.value,
        })
          .then(() => {
            props.reload?.();
            message.success(props.title + '成功');
            return true;
          })
          .catch(() => false)
      }
      columns={[
        {
          key: 'previous_reading',
          title: '上次抄表读数',
          colProps: { span: 24 },
          fieldProps: { disabled: true },
        },
        {
          key: 'current_reading',
          title: '修正抄表读数',
          valueType: 'number',
          colProps: { span: 24 },
          formItemProps: {
            ...rulesHelper.number,
            rules: [
              ...rulesHelper.number.rules,
              {
                validator: (_, value) => {
                  const latestValue = form.getFieldValue('latest_value');
                  if (
                    value &&
                    latestValue &&
                    Number(value) <= Number(latestValue)
                  ) {
                    return Promise.reject(
                      new Error('本次读数必须大于上次抄表读数'),
                    );
                  }
                  return Promise.resolve();
                },
              },
            ],
          },
          fieldProps: {
            onChange: (e: any, num: number) => {
              form.setFieldsValue({
                usage_amount: rulesHelper.getDifference(
                  parseFloat(form.getFieldValue('previous_reading')),
                  parseFloat(form.getFieldValue('current_reading')),
                ),
                remark: `修正前读数：${props.item?.current_reading}`,
              });
            },
          },
        },
        {
          key: 'reading_time',
          title: '修正抄表时间',
          valueType: 'dateTime',
          colProps: { span: 24 },
          formItemProps: {
            ...rulesHelper.text,
            rules: [
              ...rulesHelper.text.rules,
              {
                validator: (_, value) => {
                  const latestTime = form.getFieldValue('latest_time');
                  if (value && latestTime) {
                    const currentTime = new Date(value);
                    const lastTime = new Date(latestTime);
                    if (currentTime <= lastTime) {
                      return Promise.reject(
                        new Error('本次抄表时间必须大于上次抄表时间'),
                      );
                    }
                  }
                  return Promise.resolve();
                },
              },
            ],
          },
          fieldProps: {
            disabledDate: (current: any) => {
              // 禁用未来的日期
              return current && current > new Date();
            },
            disabledTime: (current: any) => {
              // 如果是今天，禁用未来的时间
              if (
                current &&
                current.format('YYYY-MM-DD') ===
                  new Date().toISOString().split('T')[0]
              ) {
                const now = new Date();
                return {
                  disabledHours: () => {
                    const hours = [];
                    for (let i = now.getHours() + 1; i < 24; i++) {
                      hours.push(i);
                    }
                    return hours;
                  },
                  disabledMinutes: (selectedHour: number) => {
                    if (selectedHour === now.getHours()) {
                      const minutes = [];
                      for (let i = now.getMinutes() + 1; i < 60; i++) {
                        minutes.push(i);
                      }
                      return minutes;
                    }
                    return [];
                  },
                  disabledSeconds: (
                    selectedHour: number,
                    selectedMinute: number,
                  ) => {
                    if (
                      selectedHour === now.getHours() &&
                      selectedMinute === now.getMinutes()
                    ) {
                      const seconds = [];
                      for (let i = now.getSeconds() + 1; i < 60; i++) {
                        seconds.push(i);
                      }
                      return seconds;
                    }
                    return [];
                  },
                };
              }
              return {};
            },
          },
        },
        {
          key: 'usage_amount',
          title: '修正后用量',
          valueType: 'number',
          colProps: { span: 24 },
          formItemProps: {
            ...rulesHelper.number,
          },
          fieldProps: {
            disabled: true,
          },
        },
        Selects?.Employees({
          key: 'company_employees_id',
          title: '抄表人',
          params: {
            companies_id: props.item?.companies_id,
          },
          colProps: { span: 24 },
          required: true,
          fieldProps: {
            showSearch: true,
            fieldNames: {
              label: 'label',
              value: 'value',
            },
            labelRender: (res: any) => {
              if (res?.label) {
                return res?.label;
              } else {
                return props?.item?.company_employee?.name;
              }
            },
          },
        }),
        {
          key: 'remark',
          title: '备注',
          valueType: 'textarea',
          colProps: { span: 24 },
        },
      ]}
    />
  );
}
