<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus';

import { onMounted, reactive, ref, watch } from 'vue';
import { useRoute } from 'vue-router';

// @ts-ignore
import { Page } from '@vben/common-ui';
// @ts-ignore
import { DictEnum } from '@vben/constants';

import { Warning } from '@element-plus/icons-vue';
import { dayjs, ElMessage } from 'element-plus';

// @ts-ignore
import { queryGasStationList } from '#/api/schedule/index';
// @ts-ignore
import {
  addscheduleClassOpeningApi,
  queryscheduleClassOpeningApi,
} from '#/api/schedule/work/class';
// @ts-ignore
import { queryrclassesApilist } from '#/api/schedule/work/classes';
// @ts-ignore
import { SelectUsers } from '#/components/selectUsers';
// @ts-ignore
import { getDictOptions } from '#/utils/dict';
// const emits = defineEmits(['submit']);
const stationName = ref('');
const route = useRoute();
const ruleFormRef = ref<FormInstance>();
const querydata = route.query as any;
const tableData = ref([]) as any;
// 新增：存储子组件的selectedItems
const selectedItems = ref<any[]>([]);
// 存储默认选中的用户ID数组
const modelValue = ref<number[]>([]);
const shiftNameoptions = ref([]) as any;
const workContentoptions = ref([]) as any;
// const Detailsdata = ref({}) as any;
const ruleForm = ref({
  workDate: '',
  shiftName: '',
  weather: '',
});
const weatheroptions = [
  { value: '晴天', label: '晴天' },
  { value: '雨天', label: '雨天' },
  { value: '阴天', label: '阴天' },
];
const executorRef: any = ref(null);
watch(
  () => executorRef.value?.selectedItems,
  (newSelectedItems) => {
    tableData.value = newSelectedItems.map((item: any) => ({
      ...item,
      employeeIdName: item.name || '',
      positionName: item.postName || '',
      shiftName: ruleForm.value.shiftName || '',
    }));
    // console.log(tableData.value, 'tableData.value');
    // if (ruleForm.value.shiftName !== '') {
    //   tableData.value = tableData.value.map((item: any) => {
    //     return {
    //       ...item,
    //       positionName: item.postName || '',
    //       shiftName: ruleForm.value.shiftName,
    //     };
    //   });
    // }
  },
  { deep: true },
);
const queryscheduleClassOpeningApifn = async () => {
  try {
    const res = await queryscheduleClassOpeningApi(querydata?.Detailsid);
    ruleForm.value.workDate = res?.workDate;
    ruleForm.value.shiftName = res?.shiftId;
    ruleForm.value.weather = res?.weather;

    // 回显用户数据
    if (res?.workRecords && res.workRecords.length > 0) {
      tableData.value = res.workRecords.map((item: any) => ({
        ...item,
        employeeIdName: item.employeeIdName || '',
        positionName: item.positionName || '',
        shiftName: res?.shiftId,
        //第一次
        // firstStartTime: new Date(item.firstWorkRecords?.startTime.split(' ')[1]?.slice(0,5))  || '',
        // firstEndTime: new Date(item.firstWorkRecords?.endTime.split(' ')[1]?.slice(0,5))  || '',
        firstStartTime:
          item.firstWorkRecords?.startTime.split(' ')[1]?.slice(0, 5) || '',
        firstEndTime:
          item.firstWorkRecords?.endTime.split(' ')[1]?.slice(0, 5) || '',
        firstWorkContent: item.firstWorkRecords?.workContent,
        //第二次
        secondStartTime:
          item.secondWorkRecords?.startTime.split(' ')[1]?.slice(0, 5) || '',
        secondEndTime:
          item.secondWorkRecords?.endTime.split(' ')[1]?.slice(0, 5) || '',
        secondWorkContent: item.secondWorkRecords?.workContent,
      }));
      console.log(tableData.value);
      const userIds = res.workRecords.map((item: any) =>
        Number(item.employeeId),
      );
      modelValue.value = userIds;
    }
  } catch (err) {
    console.log(err);
  }
};
const queryrclassesApilistfn = async () => {
  try {
    const res = await queryrclassesApilist({});
    if (res?.rows?.length > 0) {
      shiftNameoptions.value = res?.rows?.map((item: any) => ({
        value: item.id,
        label: item.shiftName,
      }));
    }
  } catch (err) {
    console.log(err);
  }
};
const queryGasStationListfn = async () => {
  try {
    const res = await queryGasStationList({ stationId: querydata?.stationId });
    if (res.length > 0) {
      stationName.value = res?.[0]?.stationName || '';
    }
  } catch (err) {
    console.log(err);
  }
};

onMounted(async () => {
  workContentoptions.value = getDictOptions(DictEnum.WORK_CONTENT);
  await queryrclassesApilistfn();
  await queryGasStationListfn();
  if (querydata?.Detailsid) {
    await queryscheduleClassOpeningApifn();
  }
});

const shiftNamehandleChange = (value: any) => {
  if (value !== '' && tableData.value.length > 0) {
    tableData.value = tableData.value.map((item: any) => {
      return {
        ...item,
        shiftName: value,
      };
    });
  }
};
const rules = reactive<FormRules<typeof ruleForm>>({
  workDate: [{ required: true, message: '请输入上班日期', trigger: 'blur' }],
  shiftName: [{ required: true, message: '请输入主班次名称', trigger: 'blur' }],
  weather: [{ required: true, message: '请输入天气', trigger: 'blur' }],
});

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      try {
        await addscheduleClassOpeningApi({
          shiftId: ruleForm.value.shiftName,
          stationId: querydata.stationId,
          userIds: tableData.value.map((item: any) => item.id),
          weather: ruleForm.value.weather,
          workDate: dayjs(ruleForm.value.workDate).format('YYYY-MM-DD'),
          workNum: tableData.value.length,
        });
        // router.replace({
        //   path: '/schedule/work/class',
        // });
      } catch (error: any) {
        ElMessage.error(error.message);
      }
    } else {
      console.error('error submit!');
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  selectedItems.value = [];
  tableData.value = [];
  if (!formEl) return;
  formEl.resetFields();
};

/**
 * 计算上班时长（小时）
 * @param startTime 开始时间
 * @param endTime 结束时间
 * @returns 上班时长（保留一位小数）
 */
const calculateDuration = (startTime: string, endTime: string): number => {
  if (!startTime || !endTime) return 0;
  // 处理纯时间字符串（HH:mm格式）
  const parseTime = (timeStr: string): number => {
    if (!timeStr) return 0;
    const parts = timeStr.split(':');
    if (parts.length !== 2) return 0;
    const [hours, minutes] = parts.map(Number);
    // @ts-ignore
    if (Number.isNaN(hours) || Number.isNaN(minutes)) return 0;
    // @ts-ignore
    return hours * 60 + minutes; // 转换为分钟
  };
  const startMinutes = parseTime(startTime);
  const endMinutes = parseTime(endTime);

  if (startMinutes === 0 || endMinutes === 0 || endMinutes < startMinutes)
    return 0;
  const diffMinutes = endMinutes - startMinutes;
  const diffHours = diffMinutes / 60;

  return Math.round(diffHours * 10) / 10;
};
</script>
<template>
  <Page title="开班" :auto-content-height="true">
    <template #default>
      <div style="position: relative" class="rounded-md bg-white p-4 shadow-md">
        <div class="title">油站：{{ stationName }}</div>
        <div class="middle">
          <div class="left">
            <el-form
              ref="ruleFormRef"
              style="max-width: 600px"
              label-position="left"
              :model="ruleForm"
              status-icon
              :rules="rules"
              label-width="auto"
              class="demo-ruleForm"
            >
              <el-form-item label="上班日期" prop="workDate">
                <el-date-picker
                  v-model="ruleForm.workDate"
                  type="date"
                  placeholder="请选择上班日期"
                />
              </el-form-item>
              <el-form-item label="主班次名称" prop="shiftName">
                <el-select
                  v-model="ruleForm.shiftName"
                  placeholder="请选择主班次名称"
                  style="width: 240px"
                  @change="shiftNamehandleChange"
                >
                  <el-option
                    v-for="item in shiftNameoptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <div style="color: red; font-size: 12px; margin-bottom: 10px">
                开班规则建议:开班负责人负责把班次属于主班次的人员开在本班如负责B班08:00-16:00，则把B1班如时间07:00-11:00,16:00-20:00也开在班次。
              </div>
              <el-form-item label="天气" prop="weather">
                <el-select
                  v-model="ruleForm.weather"
                  placeholder="请选择天气"
                  style="width: 240px"
                >
                  <el-option
                    v-for="item in weatheroptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <el-icon style="font-size: 20px; margin-left: 5px">
                  <Warning />
                </el-icon>
              </el-form-item>
            </el-form>
          </div>
          <div class="right">
            <SelectUsers
              ref="executorRef"
              v-model="modelValue"
              @update:selected-items="(items: any) => (selectedItems = items)"
              :only-users="true"
              :user-params="{ stationId: querydata.stationId }"
            />
          </div>
        </div>
        <div class="bable">
          <el-table :data="tableData" style="width: 100%">
            <el-table-column
              prop="employeeIdName"
              label="姓名"
              width="150"
              align="center"
            />
            <el-table-column
              prop="positionName"
              label="岗位"
              width="150"
              align="center"
            />
            <el-table-column
              prop="shiftName"
              label="班次"
              width="150"
              align="center"
            >
              <template #default="scope">
                <el-select
                  v-model="scope.row.shiftName"
                  placeholder="请选择班次"
                  style="width: 120px"
                >
                  <el-option
                    v-for="item in shiftNameoptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="第一次" align="center">
              <el-table-column
                prop="firstStartTime"
                label="上班时间"
                align="center"
              >
                <template #default="scope">
                  <el-time-picker
                    v-model="scope.row.firstStartTime"
                    format="HH:mm"
                    value-format="HH:mm"
                    type="time"
                    placeholder="上班时间"
                    style="width: 120px"
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="firstEndTime"
                label="下班时间"
                align="center"
              >
                <template #default="scope">
                  <el-time-picker
                    v-model="scope.row.firstEndTime"
                    format="HH:mm"
                    value-format="HH:mm"
                    type="time"
                    placeholder="下班时间"
                    style="width: 120px"
                  />
                </template>
              </el-table-column>
              <el-table-column label="上班时长" align="center">
                <template #default="scope">
                  {{
                    calculateDuration(
                      scope.row?.firstStartTime,
                      scope.row?.firstEndTime,
                    )
                  }}
                </template>
              </el-table-column>
              <el-table-column
                prop="firstWorkContent"
                label="上班内容"
                align="center"
              >
                <template #default="scope">
                  <el-select
                    v-model="scope.row.firstWorkContent"
                    placeholder="请选择上班内容"
                    style="width: 120px"
                  >
                    <el-option
                      v-for="item in workContentoptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="第二次" align="center">
              <el-table-column
                prop="secondStartTime"
                label="上班时间"
                align="center"
              >
                <template #default="scope">
                  <el-time-picker
                    v-model="scope.row.secondStartTime"
                    format="HH:mm"
                    value-format="HH:mm"
                    type="time"
                    placeholder="上班时间"
                    style="width: 120px"
                  />
                </template>
              </el-table-column>
              <el-table-column
                prop="secondEndTime"
                label="下班时间"
                align="center"
              >
                <template #default="scope">
                  <el-time-picker
                    v-model="scope.row.secondEndTime"
                    format="HH:mm"
                    value-format="HH:mm"
                    type="time"
                    placeholder="下班时间"
                    style="width: 120px"
                  />
                </template>
              </el-table-column>
              <el-table-column label="上班时长" align="center">
                <template #default="scope">
                  {{
                    calculateDuration(
                      scope.row.secondStartTime,
                      scope.row.secondEndTime,
                    )
                  }}
                </template>
              </el-table-column>
              <el-table-column
                prop="secondWorkContent"
                label="上班内容"
                align="center"
              >
                <template #default="scope">
                  <el-select
                    v-model="scope.row.secondWorkContent"
                    placeholder="请选择上班内容"
                    style="width: 120px"
                  >
                    <el-option
                      v-for="item in workContentoptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>
        </div>
        <div
          style="margin-top: 20px; display: flex; gap: 20px"
          v-if="!querydata?.Detailsid"
        >
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            保存
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        </div>
        <div
          style="color: red; font-size: 12px; margin-top: 10px"
          v-if="!querydata?.Detailsid"
        >
          请认真确认上班日期和班次信息，保存后不可删除
        </div>
        <div :class="{ masklayer: querydata.Detailsid }"></div>
      </div>
    </template>
  </Page>
</template>
<style lang="less" scoped>
.title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}
.middle {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  position: relative;

  .right {
    // width: 600px;
    height: 300px;
  }
}
.demo-ruleForm {
  :deep(.el-form-item) {
    margin-bottom: 40px;
  }
}
.masklayer {
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.027);
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
}
</style>
