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 NormalReading(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.Create
          title={`抄表`}
          type="primary"
          size={props.item?.size || 'middle'}
        />
      }
      form={form}
      onOpenChange={(open: any) => {
        if (open && props.item) {
          form.resetFields(); // 清空表单数据
          form.setFieldsValue({
            ...props.item,
            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.NormalReading.value,
        })
          .then(() => {
            props.reload?.();
            message.success(props.title + '成功');
            return true;
          })
          .catch(() => false)
      }
      columns={[
        {
          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,
            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();
                },
              },
            ],
          },
        },
        {
          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 },
        },
      ]}
    />
  );
}
