import {
  MyFormItems,
  MyModalFormProps,
  MyPageContainer,
  rulesHelper,
} from '@/common';
import { Selects } from '@/components/Select';
import { Apis } from '@/gen/Apis';
import { BetaSchemaForm, ProCard } from '@ant-design/pro-components';
import { useNavigate, useSearchParams } from '@umijs/max';
import { Form, message, Space } from 'antd';
import { useEffect, useState } from 'react';

export default function Index({ title = '编辑班次' }) {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const id = searchParams.get('id') ?? 0;
  const [data, setShow] = useState<any>({});
  const [dataSource, setDataSource] = useState<
    ApiTypes.Asset.AssetProjects.List[]
  >([]);

  const loadShow = () => {
    Apis.Attendance.AttendanceShifts.Show({ id: Number(id) }).then((res) => {
      setShow(res?.data);
      setDataSource([res?.data?.asset_project]);

      // 处理时间格式，将hh:mm:ss转换为hh:mm用于表单显示
      const formData = { ...res?.data };

      // 处理可打卡开始和结束时间
      if (formData.allow_checkin_start) {
        formData.allow_checkin_start = formData.allow_checkin_start.slice(0, 5);
      }
      if (formData.allow_checkin_end) {
        formData.allow_checkin_end = formData.allow_checkin_end.slice(0, 5);
      }

      // 处理时间段数组中的时间格式
      if (formData.attendance_shift_periods) {
        formData.periods = formData.attendance_shift_periods.map(
          (period: any) => {
            return {
              ...period,
              work_start_time: period.work_start_time
                ? period.work_start_time.slice(0, 5)
                : '',
              work_end_time: period.work_end_time
                ? period.work_end_time.slice(0, 5)
                : '',
            };
          },
        );
      }

      form.setFieldsValue({
        ...formData,
        asset_projects_id: res?.data?.asset_project?.id,
      }); // 编辑赋值
    });
  };

  useEffect(() => {
    loadShow();
  }, [id]);

  return (
    <MyPageContainer
      title={
        <Space
          style={{ cursor: 'pointer' }}
          onClick={() => {
            navigate(-1);
          }}
        >
          {/* <LeftCircleOutlined size={34} /> */}
          {title}
        </Space>
      }
      enableTabs={false}
      tabKey="attendance-shifts-update"
      tabLabel={title}
    >
      <ProCard>
        <div style={{ width: 900, minHeight: '83vh', margin: '0 auto' }}>
          <BetaSchemaForm<ApiTypes.Attendance.AttendanceShifts.Update>
            {...MyModalFormProps.props}
            title={title}
            // 基础表单
            layoutType="Form"
            labelCol={{ span: 24 }}
            wrapperCol={{ span: 24 }}
            labelAlign="left"
            width="900px"
            form={form}
            onFinish={async (values: any) => {
              // 处理时间格式转换，将HH:mm转换为HH:mm:ss格式，秒数固定为00
              const formattedValues = { ...values };

              // 处理work_start_time和work_end_time数组
              if (formattedValues.periods) {
                formattedValues.periods = formattedValues.periods.map(
                  (period: any) => {
                    return {
                      ...period,
                      work_start_time: period.work_start_time
                        ? `${period.work_start_time}:00`
                        : '',
                      work_end_time: period.work_end_time
                        ? `${period.work_end_time}:00`
                        : '',
                    };
                  },
                );
              }

              // 处理可打卡开始和结束时间
              if (formattedValues.allow_checkin_start) {
                formattedValues.allow_checkin_start = `${formattedValues.allow_checkin_start}:00`;
              }
              if (formattedValues.allow_checkin_end) {
                formattedValues.allow_checkin_end = `${formattedValues.allow_checkin_end}:00`;
              }

              Apis.Attendance.AttendanceShifts.Update({
                ...formattedValues,
                is_enabled: values.is_enabled ? true : false,
                id: data?.id,
              })
                .then(() => {
                  //提交
                  navigate(-1);
                  message.success('编辑成功');
                })
                .catch(() => false);
            }}
            columns={[
              {
                title: '班次名称',
                key: 'name',
                formItemProps: { ...rulesHelper.text },
                colProps: { span: 12 },
              },
              {
                title: '状态',
                key: 'is_enabled',
                valueType: 'switch',
                colProps: { span: 12 },
                fieldProps(form, config) {
                  return {
                    ...config.fieldProps,
                    style: { width: '100%' },
                    checkedChildren: '启用',
                    unCheckedChildren: '停用',
                  };
                },
              },
              {
                valueType: 'formList',
                dataIndex: 'periods',
                title: '设置需打卡时段',
                formItemProps: { ...rulesHelper.array },
                fieldProps: {
                  copyIconProps: false,
                  // deleteIconProps: false,
                },
                columns: [
                  {
                    valueType: 'group',
                    colProps: { span: 24 },
                    columns: [
                      MyFormItems.EnumSelect({
                        key: 'period_order',
                        valueEnum: {
                          1: '1',
                          2: '2',
                          3: '3',
                          4: '4',
                          5: '5',
                        },
                        required: true,
                        colProps: { span: 4 },
                      }),
                      // {
                      //   key: 'period_order',
                      //   valueType: 'digit',
                      //   colProps: { span: 6 },
                      //   formItemProps: { ...rulesHelper.text },
                      //   fieldProps: {
                      //     style: { width: '100%' },
                      //     placeholder: '请输入班次序号',
                      //   },
                      // },
                      {
                        key: 'work_start_time',
                        valueType: 'time',
                        fieldProps: {
                          style: { width: '100%' },
                          placeholder: '请选择班次开始时间',
                          format: 'HH:mm',
                        },
                        colProps: { span: 8 },
                        formItemProps: { ...rulesHelper.text },
                      },
                      {
                        key: 'work_end_time',
                        fieldProps: {
                          style: { width: '100%' },
                          placeholder: '请选择班次结束时间',
                          format: 'HH:mm',
                        },
                        valueType: 'time',
                        colProps: { span: 8 },
                        formItemProps: { ...rulesHelper.text },
                      },
                    ],
                  },
                ],
              },
              {
                title: '可打卡开始时间',
                key: 'allow_checkin_start',
                valueType: 'time',
                fieldProps: {
                  style: { width: '100%' },
                  format: 'HH:mm',
                },
                colProps: { span: 12 },
                formItemProps: { ...rulesHelper.text },
              },
              {
                title: '可打卡结束时间',
                key: 'allow_checkin_end',
                fieldProps: {
                  style: { width: '100%' },
                  format: 'HH:mm',
                },
                valueType: 'time',
                colProps: { span: 12 },
                formItemProps: { ...rulesHelper.text },
              },

              Selects?.AssetProjects({
                title: '关联项目',
                key: 'asset_projects_id',
                colProps: { span: 24 },
                formItemProps: { ...rulesHelper.text },
              }),

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