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

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

import { selectAllSysStation } from '#/api/system/infoEntry/stationInfo/stationInfo';

const props = defineProps({
  isdrawer: {
    type: Boolean,
    default: false,
  },
  isdrawerloading: {
    type: Boolean,
    default: false,
  },
  editdata: {
    type: Object,
    default: () => {},
  },
  isdrawertitle: {
    type: String,
    default: '',
  },
});
const emit = defineEmits(['update:modelValue', 'submit']);
const handleClose = () => {
  emit('update:modelValue', false);
  console.log('关闭了');
  // 重置表单数据
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields();
  }
  // 重置表单对象
  Object.assign(ruleForm.value, {
    id: '',
    name: '',
    firstWorkTime: '',
    lastWorkTime: '',
    firstWorkDuration: '',
    secondWorkTime: '',
    secondLastWorkTime: '',
    secondWorkDuration: '',
    common: '0',
    stationIds: [],
  });
};

// 将小时的小数形式（如7.59）转换为"X小时Y分钟"格式
const convertDecimalToDuration = (decimalHours: number | string): string => {
  if (!decimalHours) return '';

  const hours = Number(decimalHours);
  const integerHours = Math.floor(hours);
  const minutes = Math.round((hours - integerHours) * 60);

  return `${integerHours}小时${minutes}分钟`;
};

const ruleFormRef = ref();
const options = ref([]) as any;
onMounted(async () => {
  try {
    // @ts-ignore
    options.value = (
      await selectAllSysStation({
        isAll: 1,
        pageSize: 10_000,
      })
    ).map((item) => ({
      value: item?.id,
      label: item?.stationName,
    }));
  } catch (error) {
    console.log(error);
  }
});

// 监听editdata变化，实现数据回显
watch(
  () => props.editdata,
  (newEditData) => {
    if (newEditData && Object.keys(newEditData).length > 0) {
      // 保存ID用于编辑时的标识
      ruleForm.value.id = newEditData.id || '';

      // 填充基本字段
      ruleForm.value.name = newEditData.shiftName || newEditData.name || '';
      ruleForm.value.common = newEditData.isCommon?.toString() || '0';

      // 处理时间字段（确保转换为Date对象或组件可接受的格式）
      if (newEditData.firstStartTime) {
        ruleForm.value.firstWorkTime = new Date(newEditData.firstStartTime);
      }
      if (newEditData.firstEndTime) {
        ruleForm.value.lastWorkTime = new Date(newEditData.firstEndTime);
      }
      if (newEditData.secondStartTime) {
        ruleForm.value.secondWorkTime = new Date(newEditData.secondStartTime);
      }
      if (newEditData.secondEndTime) {
        ruleForm.value.secondLastWorkTime = new Date(newEditData.secondEndTime);
      }

      // 处理工作时长（将小数转换为"X小时Y分钟"格式）
      if (newEditData.firstDuration) {
        ruleForm.value.firstWorkDuration = convertDecimalToDuration(
          newEditData.firstDuration,
        );
      }
      if (newEditData.secondDuration) {
        ruleForm.value.secondWorkDuration = convertDecimalToDuration(
          newEditData.secondDuration,
        );
      }
      // 处理场站ID列表
      if (newEditData.applicableStations) {
        ruleForm.value.stationIds = newEditData.applicableStations
          .split(',')
          .map(Number);
      }
    }
  },
  { deep: true, immediate: true },
);
const ruleForm = ref({
  id: '',
  name: '',
  firstWorkTime: '',
  lastWorkTime: '',
  firstWorkDuration: '',
  secondWorkTime: '',
  secondLastWorkTime: '',
  secondWorkDuration: '',
  common: '0',
  stationIds: [],
}) as any;

const rules = reactive({
  name: [{ required: true, message: '请输入班次名称', trigger: 'blur' }],
  firstWorkTime: [
    { required: true, message: '请选择第一次上班时间', trigger: 'change' },
  ],
  lastWorkTime: [
    { required: true, message: '请选择第一次下班时间', trigger: 'change' },
  ],
  secondWorkTime: [
    { required: true, message: '请选择第二次上班时间', trigger: 'change' },
  ],
  secondLastWorkTime: [
    { required: true, message: '请选择第二次下班时间', trigger: 'change' },
  ],
  common: [{ required: true, message: '请选择常用', trigger: 'change' }],
  stationIds: [
    { required: true, message: '请选择适用场站', trigger: 'change' },
  ],
});
const SelectAll = async () => {
  try {
    // @ts-ignore
    ruleForm.value.stationIds = (
      await selectAllSysStation({
        isAll: 1,
        pageSize: 10_000,
      })
    ).map((item: any) => item?.id);
  } catch (error) {
    console.log(error);
  }
};
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      emit('submit', ruleForm.value);
    } else {
      console.log('error submit!', fields);
    }
  });
};

// 计算工作时长
const calculateWorkDuration = (
  startTime: Date | string,
  endTime: Date | string,
): string => {
  if (!startTime || !endTime) return '';

  const start = new Date(startTime);
  const end = new Date(endTime);

  // 计算毫秒差值
  const diffMs = end.getTime() - start.getTime();

  // 转换为小时和分钟
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
  const diffMinutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60));

  // 格式化显示
  return `${diffHours}小时${diffMinutes}分钟`;
};

// 计算第一次上班时长
const calculateFirstWorkDuration = () => {
  ruleForm.value.firstWorkDuration = calculateWorkDuration(
    ruleForm.value.firstWorkTime,
    ruleForm.value.lastWorkTime,
  );
};

// 计算第二次上班时长
const calculateSecondWorkDuration = () => {
  ruleForm.value.secondWorkDuration = calculateWorkDuration(
    ruleForm.value.secondWorkTime,
    ruleForm.value.secondLastWorkTime,
  );
};

// const resetForm = (formEl: FormInstance | undefined) => {
//   if (!formEl) return;
//   formEl.resetFields();
// };
</script>

<template>
  <el-drawer
    :model-value="isdrawer"
    @update:model-value="emit('update:modelValue', $event)"
    :title="isdrawertitle"
    direction="rtl"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div v-loading="isdrawerloading" style="width: 100%; height: 100%">
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
      >
        <el-form-item label="班次名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入班次名称" />
        </el-form-item>
        <div style="display: flex; justify-content: space-between; gap: 20px">
          <el-form-item label="第一次上班时间" prop="firstWorkTime">
            <el-date-picker
              v-model="ruleForm.firstWorkTime"
              type="datetime"
              placeholder="请选择"
              @change="calculateFirstWorkDuration"
            />
          </el-form-item>
          <el-form-item label="第一次下班时间" prop="lastWorkTime">
            <el-date-picker
              v-model="ruleForm.lastWorkTime"
              type="datetime"
              placeholder="请选择"
              @change="calculateFirstWorkDuration"
            />
          </el-form-item>
        </div>
        <el-form-item label="第一次上班时长" prop="firstWorkDuration">
          <el-input v-model="ruleForm.firstWorkDuration" disabled />
        </el-form-item>
        <div style="display: flex; justify-content: space-between; gap: 20px">
          <el-form-item label="第二次上班时间" prop="secondWorkTime">
            <el-date-picker
              v-model="ruleForm.secondWorkTime"
              type="datetime"
              placeholder="请选择"
              @change="calculateSecondWorkDuration"
            />
          </el-form-item>
          <el-form-item label="第二次下班时间" prop="secondLastWorkTime">
            <el-date-picker
              v-model="ruleForm.secondLastWorkTime"
              type="datetime"
              placeholder="请选择"
              @change="calculateSecondWorkDuration"
            />
          </el-form-item>
        </div>
        <el-form-item label="第二次上班时长" prop="secondWorkDuration">
          <el-input v-model="ruleForm.secondWorkDuration" disabled />
        </el-form-item>
        <el-form-item label="常用" prop="common">
          <el-radio-group v-model="ruleForm.common">
            <el-radio value="1" size="large">是</el-radio>
            <el-radio value="0" size="large">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="适用场站" prop="stationIds">
          <div style="display: flex; gap: 20px">
            <el-select
              v-model="ruleForm.stationIds"
              multiple
              placeholder="请选择"
              style="width: 240px"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-button type="primary" @click="SelectAll"> 全选 </el-button>
          </div>
        </el-form-item>
        <el-form-item>
          <div
            style="
              width: 100%;
              display: flex;
              justify-content: flex-end;
              gap: 20px;
            "
          >
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              提交
            </el-button>
            <el-button @click="handleClose">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </el-drawer>
</template>
