<template>
  <div>
    <el-dialog :title="props.title || '新增驾驶员里程信息'" width="1000px" v-model="props.addDiaShow"
      :before-close="handleClose">
      <div class="config fj">
        <el-form :model="ruleForm" :rules="rules" label-width="150px" class="demo-ruleForm.value" ref="formEl"
          style="width: 100% !important;flex-wrap: wrap;">
          <el-form-item style="width: 100%;" label="选择日期：">
            <el-date-picker style="width: 252px;" v-model="ruleForm.month" type="month" format="YYYY-MM"
              value-format="YYYY-MM" @change="dateChange" :disabled-date="mosthDisabled" />
          </el-form-item>
          <el-divider></el-divider>
          <el-form-item label="开始行驶日期：" prop="startDate">
            <el-date-picker style="width:300px" disabled v-model="ruleForm.startDate" type="date" format="YYYY-MM-DD"
              value-format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item label="结束行驶日期：" prop="endUnit">
            <el-date-picker style="width:300px" disabled v-model="ruleForm.endUnit" type="date" format="YYYY-MM-DD"
              value-format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item label="驾驶员：">
            <el-input style="width:300px" v-model="ruleForm.driver" readonly>
              <template #append>
                <el-button type="primary" @click="ChooseJsy('01')">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="累计行驶里程：" prop="mileage">
            <el-input-number v-model="ruleForm.mileage" :disabled="!ruleForm.startDate" :min="0" :max="99999999"
              :maxlength="9" :step="1" :precision="0" style="width: 300px" />
          </el-form-item>

          <el-form-item label="备注：" style="width: 100%;">
            <el-input v-model="ruleForm.bz" type="textarea" :rows="6" show-word-limit maxlength="200"
              style="width:730px" />
          </el-form-item>
        </el-form>
        <div style="font-size: 12px;color: red;">注：不要忘记在外面也要点击保存，累计行驶里程为仪表盘上的数值</div>
        <!-- 驾驶员选择 -->
        <MOSTY.Choosejsy v-if="isShowJsy" v-model="isShowJsy" :Single="true" :leaderid="leaderid" @confirm="jsyChange"
          :empnature="undefined" :orgid="undefined" :defaultData="jsyData">
        </MOSTY.Choosejsy>
      </div>
      <template #footer>
        <span class="dialog-footer">

          <el-button type="primary" :loading="loading" @click="handleSave(formEl)" v-if="saveBtnShow">
            <el-icon>
              <DocumentChecked />
            </el-icon>
            <span>保存</span>
          </el-button>
          <el-button @click="handleClose" type="primary">
            <el-icon>
              <DocumentDelete />
            </el-icon>
            <span>关闭</span>
          </el-button><!--  -->
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 引入
import { ref, defineProps, defineEmits, reactive, watchEffect, getCurrentInstance, watch } from "vue";
import * as rule from "@/utils/rules.js";
import { ElMessage } from "element-plus";
import { getMonthDate } from "@/utils/tools.js";
import * as MOSTY from "@/components/MyComponents/index";
import { getApi, deleteApi, putApi, postApi } from "@/api/tobAcco_api.js";

const { proxy } = getCurrentInstance();
const formEl = ref()
//表单数据
const ruleForm = ref({

});
/**驾驶员弹框 */
const isShowJsy = ref(false)
const leaderid = ref("");
/** 驾驶员回显数据格式[id,id] */
const jsyData = ref([]);

//规则校验
const rules = reactive({
  startDate: [{ required: true, message: "开始行驶日期不能为空", trigger: "change" }],
  endUnit: [{ required: true, message: "结束行驶日期不能为空", trigger: "change" }],
  driver: [{ required: true, message: "驾驶员不能为空", trigger: "change" }],
  mileage: [{
    required: true, trigger: "change", validator: (rule, code, callback) => {
      checkValid(rule, code, callback)
    }
  }],

});
const props = defineProps({
  addDiaShow: {
    type: Boolean,
    default: false
  },
  rowxq: {
    type: Object,
    default: () => { }
  },
  title: String,
  saveBtnShow: {
    default: true,
    type: Boolean
  },
  mileArr: {
    type: Array,
    default: () => []
  }
});
const loading = ref(false)

watch(() => props.rowxq, (val) => {
  if (props.rowxq) {
    ruleForm.value = JSON.parse(JSON.stringify(props.rowxq));
    // ruleForm.value = {
    //   ...props.rowxq
    // }
    if (ruleForm.value.startDate) {
      ruleForm.value.month = `${ruleForm.value.startDate.substring(0, 7)}`
    }
    if (!ruleForm.value.driver && props.rowxq.carNumber) {
      setDriver()
    }
  } else {
    ruleForm.value = {}
  }
}, {
  immediate: true
})

const emits = defineEmits(["ok", "changeclose"]);

function ChooseJsy(val) {
  // leaderid.value = val
  isShowJsy.value = true
}
const mosthDisabled = (time) => {
  // return false // 下面的备用
  let mileArr = Array.isArray(props.mileArr) ? [...props.mileArr] : []
  let year = new Date(time).getFullYear()
  let month = new Date(time).getMonth() + 1
  /** 之前的时间也可以选 */
  const oldDate = new Date(props.rowxq.startDate)
  // 移除回显的时间，让其可以选择
  mileArr = mileArr.filter(item => {
    let itemYear = new Date(item.startDate).getFullYear()
    let itemMonth = new Date(item.startDate).getMonth()
    return oldDate.getFullYear() !== itemYear || oldDate.getMonth() !== itemMonth
  })
  return mileArr.some(item => {
    let itemYear = new Date(item.startDate).getFullYear()
    let itemMonth = new Date(item.startDate).getMonth() + 1

    return itemYear === year && itemMonth === month
  })
}
/** 获取一段时间的上个时间对象，和下个时间对象
 *  @param {Array} dateArray - 日期数组
 *  @param {Date} targetDate - 目标日期
 *  @param {Date} startDate - 开始日期
 *  @returns {Object} 包含前一个日期和后一个日期的对象 { prevItem, nextItem }
 ]
 */
function getAdjacentItems(dateArray, targetDate, startDate) {
  dateArray = Array.isArray(dateArray) ? dateArray : []
  if (!dateArray.length) return { prevItem: null, nextItem: null }
  // 将目标日期转换为时间戳
  const targetTime = new Date(targetDate).getTime();
  const targetTimeStart = new Date(startDate).getTime();
  // 对数组按日期升序排序
  const sortedArray = [...dateArray].sort((a, b) =>
    new Date(a.endUnit).getTime() - new Date(b.endUnit).getTime()
  );
  let first = sortedArray[0]

  let last = sortedArray[sortedArray.length - 1] // 最后一个
  let firstTime = new Date(first.startDate).getTime()
  let lastTime = new Date(last.endUnit).getTime()

  let prevItem = targetTime > lastTime ? last : null; // 如果目标日期大于最后一个日期，则将最后一个日期作为前一个日期
  let nextItem = targetTimeStart < firstTime ? first : null; // 如果目标日期小于第一个日期，则将第一个日期作为下一个日期
  // 找到下一个日期item
  for (let i = 0; i < sortedArray.length; i++) {
    const currentTime = new Date(sortedArray[i].endUnit).getTime();
    if (currentTime > targetTime) {
      nextItem = sortedArray[i];
      break;
    }
  }
  // 找到前一个日期 item
  for (let i = sortedArray.length - 1; i >= 0; i--) {
    const currentTime = new Date(sortedArray[i].endUnit).getTime();
    if (currentTime < targetTime) {
      prevItem = sortedArray[i];
      break;
    }
  }
  return { prevItem, nextItem };
}
/**设置驾驶员- 自动填充*/
function setDriver() {
  const row = props.rowxq
  getApi({ carNumber: row.carNumber }, `/mosty-jcgl/car/getDriverName`).then((res) => {
    ruleForm.value.driver = res?.drivername || ''
  }).finally(() => {
  })
}
const dateChange = (val) => {
  const { start, end } = getMonthDate(val) // 根据日期获取 月的开始和结束日期
  ruleForm.value.startDate = start
  ruleForm.value.endUnit = end
  ruleForm.value.mileage = '' // 清理掉，方便重新验证
}
// 关闭
const handleClose = () => {
  if (!formEl.value) return;
  if (props.saveBtnShow) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        emits("changeclose", false);
      })
      .catch(() => {
        // catch error
      })
  } else {
    emits("changeclose", false);
  }

};
/** 驾驶员选中 */
const jsyChange = (value = []) => {
  ruleForm.value.driver = value[0]?.drivername
  jsyData.value = [value[0]?.id]
};
// 关闭×
const closeDialog = () => {
  emits("changeclose", false);
};
/** 检测时间 */
const checkDate = () => {
  const endUnit = new Date(ruleForm.value.endUnit)
  const startDate = new Date(ruleForm.value.startDate)
  if (endUnit < startDate) {
    ElMessage.warning('结束时间不能小于开始时间！')
  }
  return endUnit >= startDate
}
const checkValid = (rule, code, callback) => {
  let form = ruleForm.value
  if (!form?.startDate || !form?.endUnit) return callback()
  let { prevItem, nextItem } = getAdjacentItems(props.mileArr, ruleForm.value.endUnit, ruleForm.value.startDate)
  prevItem = prevItem || { mileage: 0 }
  nextItem = nextItem || { mileage: 99999999 }
  if (prevItem?.mileage > form.mileage || nextItem.mileage < form.mileage) {
    // 填写 的行驶里程必须大于等于上一个月的数据小于等于下一个月的数据
    callback(new Error(`累计行驶里程不在范围内 ( ${prevItem.mileage || 0} - ${nextItem.mileage} )`));
  }
  callback()
}
// 保存
const handleSave = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      loading.value = true
      if (ruleForm.value) {
        if (!ruleForm.value?.mileage) {
          ruleForm.value.mileage = 0
        }
        emits("ok", ruleForm.value);
        loading.value = false
      }
      emits("changeclose", false);
      loading.value = false
    } else {
      ElMessage.warning('请检测表单！')
    }
  })
};
</script>

<style lang="scss" scoped>
.fj {
  .el-form {
    padding: 10px;
    margin-top: 10px;
    flex-wrap: wrap;
    // width: 1170px;
    justify-content: flex-end;
  }

  .from_fix {
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    margin-top: 10px;

    // .el-form-item--default .el-form-item__content {
    //   flex-wrap: nowrap !important;
    // }

    .el-input {
      width: 100%;
    }
  }
}

::v-deep .el-form-item__content {
  flex-wrap: nowrap !important;
}

.config {
  width: 955px;

  .el-form {
    padding: 10px 40px;
    margin-top: 10px;
    flex-wrap: wrap;
    justify-content: space-between;
  }

  .el-form-item {
    width: 46%;
    text-align: center;
  }
}

.pxdx_box {
  width: 500px;
}

.titleBox {
  align-items: center;
  margin: 0;
  padding: 0;
  height: 60px;
  border: 1px solid rgb(32, 75, 54);
  padding: 20px;
}

.form>div {
  position: relative;
  margin-top: 30px;
  display: flex;
  justify-content: space-between;

  div {
    display: flex;
    align-items: center;

    .el-select {
      width: 65%;
    }
  }
}

.el-input {
  width: 75%;
}

.two .el-input {
  width: 65%;
}

.three {
  justify-content: flex-start !important;

  .el-select {
    width: 15%;
  }
}

.four {
  display: flex;
  align-items: center;

  span {
    width: 5%;
  }

  .el-textarea__inner {
    width: 95%;
  }
}

.group {
  margin-top: 50px;
  // background-color: red;
  position: relative;
}

.fj {
  margin-top: 20px;
  width: 100%;

  .content {
    width: 100%;
    display: flex;
    padding: 20px;

    div {
      display: flex;
      width: 85%;
      align-items: center;
    }

    justify-content: space-between;
  }
}

.jc {
  margin-top: 50px;
}

.tabBox {
  height: 300px !important;
}

.el-table {
  height: 300px !important;
  border: 1px solid var(--el-color-primary);
}

.el-form-item__content {
  flex-wrap: nowrap;
}
</style>
