import {
  MyBetaModalFormProps,
  MyButtons,
  MyFormItems,
  MyModalFormProps,
  rulesHelper,
} from '@/common';
import { Selects } from '@/components/Select';
import { Apis } from '@/gen/Apis';
import {
  HouseMeterReadingsOperationTypeEnum,
  HouseMetersMeterTypeEnum,
  HouseMetersUsageTypeEnum,
} 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.Store>
      {...MyModalFormProps.props}
      title={`重置抄表数据`}
      layout="horizontal"
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 18 }}
      labelAlign="left"
      width="600px"
      key={new Date().getTime()}
      trigger={
        <MyButtons.Default
          title={props.item?.title || `重置读数`}
          type="primary"
          size={props.item?.size || 'middle'}
          danger
        />
      }
      form={form}
      onOpenChange={(open: any) => {
        if (open && props.item) {
          form.resetFields(); // 清空表单数据
          form.setFieldsValue({
            ...props.item,
            house_meters_id: props.item?.id,
            latest_value:
              props.item?.latest_value === '0.00'
                ? props.item?.initial_value
                : props.item?.latest_value,
            latest_time: props.item?.latest_time || props.item?.initial_time,
          });
        }
      }}
      onFinish={async (values) =>
        Apis.Meter.HouseMeterReadings.Store({
          ...values,
          house_meters_id: props.item?.id,
          operation_type:
            HouseMeterReadingsOperationTypeEnum.ResetReading.value,
        })
          .then(() => {
            props.reload?.();
            message.success(props.title + '成功');
            return true;
          })
          .catch(() => false)
      }
      columns={[
        {
          key: 'name',
          title: '仪表名称',
          colProps: { span: 24 },
          fieldProps: { disabled: true },
          formItemProps: { ...rulesHelper.text },
        },
        MyFormItems.EnumRadio({
          key: 'meter_type',
          title: '仪表类型',
          colProps: { span: 24 },
          valueEnum: HouseMetersMeterTypeEnum,
          required: true,
          fieldProps: { disabled: true },
        }),
        MyFormItems.EnumRadio({
          key: 'usage_type',
          title: '使用类型',
          colProps: { span: 24 },
          valueEnum: HouseMetersUsageTypeEnum,
          required: true,
          fieldProps: { disabled: true },
        }),
        {
          key: 'latest_value',
          title: '上次抄表读数',
          colProps: { span: 24 },
          fieldProps: { disabled: true },
        },
        {
          key: 'latest_time',
          title: '上次抄表时间',
          valueType: 'dateTime',
          colProps: { span: 24 },
          fieldProps: { disabled: true },
        },

        {
          key: 'current_reading',
          title: '重置抄表读数',
          valueType: 'number',
          colProps: { span: 24 },
          formItemProps: {
            ...rulesHelper.number,
          },
        },
        {
          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 {};
            },
          },
        },
        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',
            },
          },
        }),

        {
          key: 'remark',
          title: '备注',
          valueType: 'textarea',
          colProps: { span: 24 },
        },
      ]}
    />
  );
}
