import {
  MyButtons,
  MyModalFormProps,
  MyPageContainer,
  rulesHelper,
} from '@/common';
import { Selects } from '@/components/Select';
import { Apis } from '@/gen/Apis';
import {
  BetaSchemaForm,
  EditableProTable,
  ProCard,
} from '@ant-design/pro-components';
import { useNavigate } from '@umijs/max';
import { Form, message, Space } from 'antd';
import dayjs from 'dayjs';
import { useState } from 'react';
let optionsData: any = [];
export default function Index({ title = '批量排班' }) {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [startDate, setStartDate] = useState([]);
  const [dataSource, setDataSource] = useState([]);

  // 动态提取日期（排除 id 和 name 字段）
  const extractDates = (data: any) => {
    const firstPerson = data[0];
    return Object.keys(firstPerson).filter(
      (key) => key !== 'id' && key !== 'name' && !isNaN(Date.parse(key)),
    );
  };

  const getOptionsData = async (params: any) => {
    if (optionsData?.length) {
      return optionsData || [];
    }
    let res: any = await Apis.Attendance.AttendanceShifts.Select({
      ...params,
      name: params?.keyWords || undefined,
    });
    optionsData = [...res?.data, ...[{ id: -1, name: '取消班次' }]];
    console.log(optionsData, '1');
    return optionsData || [];
  };
  // 生成未来7天日期的函数
  const generateFutureDates = (startDate: string) => {
    const dates = [];

    const columns = [
      {
        title: '员工ID',
        dataIndex: 'id',
        readonly: true,
      },
      {
        title: '员工',
        dataIndex: 'name',
        readonly: true,
      },
    ];
    const start = dayjs(startDate);
    for (let i = 0; i < 7; i++) {
      const currentDate = start.clone().add(i, 'day').format('YYYY-MM-DD');
      dates.push({
        title: currentDate,
        key: currentDate,
        dataIndex: currentDate,
        formItemProps: { ...rulesHelper.number },
        valueType: 'select',
        request: async (params: any) => {
          return getOptionsData(params);
        },
        fieldProps: {
          showSearch: true,
          allowClear: false,
          // placeholder: '请选择班次',
          fieldNames: {
            label: 'name',
            value: 'id',
          },
        },
      });
    }
    console.log(dates);
    if (startDate && dates?.length) {
      return [...columns, ...dates];
    } else {
      return columns;
    }
  };

  return (
    <MyPageContainer
      title={
        <Space
          style={{ cursor: 'pointer' }}
          onClick={() => {
            navigate(-1);
          }}
        >
          {/* <LeftCircleOutlined size={34} /> */}
          {title}
        </Space>
      }
      enableTabs={false}
      tabKey="charge-standards-create"
      tabLabel={title}
    >
      <ProCard>
        <div
          style={{
            width: '1200px',
            minHeight: '83vh',
            margin: '0 auto',
          }}
        >
          <BetaSchemaForm<ApiTypes.Contract.Contracts.Store>
            {...MyModalFormProps.props}
            title={title}
            // 基础表单
            layoutType="Form"
            labelCol={{ span: 24 }}
            wrapperCol={{ span: 24 }}
            labelAlign="left"
            width="900px"
            form={form}
            submitter={{
              render: (props) => {
                return [
                  <MyButtons.Default
                    key="Review"
                    size="middle"
                    type="primary"
                    onClick={() => {
                      props.submit();
                    }}
                    title="提交保存"
                  />,
                ];
              },
            }}
            onFinish={async () => {
              const dates = extractDates(dataSource);
              const missingData: string[] = [];

              // // 先检查所有数据是否完整
              for (const person of dataSource) {
                for (const date of dates) {
                  const shiftId = person[date];
                  if (shiftId === undefined || shiftId === null) {
                    missingData.push(`员工 ${person?.name} 在 ${date}`);
                  }
                }
              }

              // 如果有缺失数据，提示并停止执行（只提示一次）
              // if (missingData.length > 0) {
              //   message.error(
              //     `存在 ${missingData.length} 条未填写的排班数据，请完善后再提交`,
              //   );
              //   return false;
              // }
              // 数据完整，进行转换和提交
              const transformedData: any = dataSource.flatMap((person: any) => {
                console.log(person, 'person');

                return dates.map((date) => {
                  let startDateItem: any = {};
                  if (person[date] === -1) {
                    startDate?.flatMap((item: any) => {
                      if (item?.id === person?.id) {
                        startDateItem = item;
                      }
                    });
                  }
                  console.log(startDateItem, 'startDateItem');
                  return {
                    company_employees_id: person.id,
                    attendance_shifts_id:
                      person[date] === -1
                        ? startDateItem[date]
                        : person[date] || 0,
                    schedule_date: date,
                    status: person[date] < 0 ? 'Cancelled' : '',
                  };
                });
              });
              const filteredData = transformedData.filter(
                (item: any) =>
                  item.attendance_shifts_id !== null &&
                  item.attendance_shifts_id !== 0,
              );
              console.log(transformedData, startDate, 'startDate');

              console.log(filteredData, 'filteredData');
              // return;
              Apis.Attendance.AttendanceSchedules.BatchStore({
                schedules: filteredData || [],
              })
                .then(() => {
                  navigate(-1);
                  message.success('提交成功');
                })
                .catch(() => false);
              console.log(transformedData);
            }}
            columns={[
              Selects?.OrganizationsTree({
                title: '第一步：选择组织',
                key: 'organizations_id',
                colProps: { span: 24 },
                formItemProps: { ...rulesHelper.text },
              }),
              {
                title: '第二步：选择开始日期',
                tooltip: '排班开始日期，最大排班日期为当前日期',
                key: 'schedule_date',
                valueType: 'date',
                fieldProps: {
                  format: 'YYYY-MM-DD',
                  style: { width: '100%' },
                },
                colProps: { span: 24 },
                formItemProps: { ...rulesHelper.text },
              },
              {
                valueType: 'dependency',
                name: ['organizations_id', 'schedule_date'],
                colProps: { span: 24 },
                columns: ({ schedule_date, organizations_id }) => {
                  return [
                    {
                      renderFormItem: () => {
                        console.log(schedule_date, organizations_id);
                        return (
                          <MyButtons.Default
                            type="primary"
                            size="middle"
                            title="第三步：获取环卫人员信息"
                            style={{ width: '100%' }}
                            onClick={() => {
                              // getEmployeesExternal(organizations_id || []); //获取外部员工
                              Apis.Attendance.AttendanceSchedules.ShiftList({
                                schedule_date: schedule_date,
                                organizations_id:
                                  organizations_id?.[
                                    organizations_id?.length - 1
                                  ],
                              }).then((res) => {
                                setStartDate(
                                  JSON.parse(JSON.stringify(res?.data)),
                                );
                                setDataSource(
                                  JSON.parse(JSON.stringify(res?.data)),
                                );
                                console.log(res);
                              });
                            }}
                          />
                        );
                      },
                    },
                    {
                      renderFormItem: () => {
                        return (
                          <ProCard bordered size="small">
                            <EditableProTable<any>
                              key={schedule_date}
                              headerTitle="第四步：设置员工班次（按周）"
                              bordered
                              recordCreatorProps={false}
                              columns={generateFutureDates(schedule_date || '')}
                              rowKey="id"
                              value={dataSource}
                              onChange={(values) => {
                                setDataSource(values);
                              }}
                              editable={{
                                type: 'multiple',
                                editableKeys: dataSource?.map(
                                  (item: any) => item?.id,
                                ),
                                onValuesChange: (record, recordList: any) => {
                                  setDataSource(recordList);
                                },
                                onSave: async (rowKey, data, row) => {
                                  console.log(rowKey, data, row);
                                },
                              }}
                            />
                          </ProCard>
                        );
                      },
                    },
                  ];
                },
              },
            ]}
          />
        </div>
      </ProCard>
    </MyPageContainer>
  );
}
