<template>
  <div class="app-container Scheduling">
    <div class="pickerBig">
    <span class="pickeTitle">排班日历</span>
    <span>
      <el-button style="margin-right: 10px;" circle type="primary" icon="ArrowLeftBold" @click="ArrowLeftBold(-1)" size='small'></el-button>
      <el-date-picker
        v-model="selectMonth"
        type="month"
        placeholder="Pick a month"
        format="YYYY/MM"
        value-format="YYYY-MM"
        :clearable="false"
        style="width: 120px;"
        @change="changeTime"
      />
      <el-button style="margin-left:  10px;" circle type="primary" icon="ArrowRightBold" @click="ArrowLeftBold(+1)" size='small'></el-button>
    </span>
    <span>
      <el-button  @click="obtainMonth()" type="primary" plain icon="Calendar">本月</el-button>
      <el-button v-hasPermi="['system:schedule:add']" style="margin-left:10px" @click="autoSchedu()" type="primary" icon="Clock">批量排班</el-button>
    </span>
    </div>
    <els-table
      :columns="columns"
      :tableData="tableData"
      @getTableData="getTableData"
      :pageSet="pageSet"
      :option="tableOption"
      :tableLoading="tableLoading"
      @cellStyle="cellStyle"
    ></els-table>
      <!-- 新增或编辑弹窗 -->
      <el-dialog
        v-model="dialogVisibleAddOrEdit"
        title="批量排班"
        destroy-on-close
        width="960">
        <el-alert title="此排班功能是针对四班三倒的排班方式" type="info" show-icon :closable="false"/>
        <els-form
        :fieldList="fieldList"
        :formOption="formOption"
        :formLoading="formLoading"
        :form="formData"
        @ok="submit"
        @cancel="cancel"
        @formChange="formChange"
        ref="elsForms"
        ></els-form>
      </el-dialog>
  </div>
</template>

<script setup name="Scheduling" lang="jsx">
import {queryAllList,classesList,batchGenerate,calendarList} from "@/api/produce/Scheduling";
import { init } from './index.jsx'
const { proxy } = getCurrentInstance();
const headerArr = ref([])
const tableLoading = ref(false)
const formLoading = ref(false)
const dialogVisibleAddOrEdit = ref(false)
const selectMonth= ref('') // 选择月份
const tableData = ref([])         // 表格数据
//表单
const formData = ref({})
//获取班组信息
const teamArr = ref([])
//获取班次信息
const classesArr = ref([])
// //表个接口获取数据并处理
const getTableData = (data)=>{
  tableLoading.value = true
  let year = data.substring(0, 4);
  let month = data.substring(5,7)
  calendarList({year:year, month:month}).then(res=>{
  tableLoading.value = false
    //一个月有多少天
      const dayAll = res.days
      //处理好的标头数组
      let arr = [
      {
        label:'日期',
        prop: `header`,
        minWidth: 70,
        align:"center",
        fixed:'left',
        children:[
          {
            label: `班组` ,
            slots: (row) => {
            return (<>
                <svg-icon icon-class="teamsIcon" class="sidebar-logo" />
                <span> {row.header}</span>
               </>)
               },
          }
        ],

      }
    ]
    //插入标头日期
    for(let i = 1; i <= dayAll; i++){
      arr.push({
        label: `${i}` ,
        prop: `day${i}`,
        minWidth: 50,
        align:"center",
        children:[],
      },)
    }
    //插入二级标头周几
    arr.forEach((item,index)=>{
      if(index > 0){
        item.children.push(
          {
            label: res.weekdays[index - 1],
            prop: `day${index}`,
            align:"center",
            minWidth: 58,
            slots: (row) => {
            return (<>
                <svg-icon v-show={row[`day${index}`] == '白'} icon-class="sun" class="sidebar-logo" />
                <svg-icon v-show={row[`day${index}`] == '中'} icon-class="middle" class="sidebar-logo" />
                <svg-icon v-show={row[`day${index}`] == '夜'} icon-class="Moon" class="sidebar-logo" />
                <svg-icon v-show={row[`day${index}`] == '休'} icon-class="rest" class="sidebar-logo" />
                <span> {row[`day${index}`]}</span>
               </>)
               }
          }
        )
        //如果是周6.7 竖列显示 灰色  给二级标头加一个别名
        if(item.children[0].label == '六' || item.children[0].label == '日'){
          item.children[0].className = 'weekdays'
        }
      }
    })
    headerArr.value = arr
    let dataList = []
    Object.keys(res.team1).forEach(j => {
      let obj = {
        header:`${j}`
      }
      res.team1[j].forEach((item,index)=>{
        obj[`day${item.order}`] = item.shiftName
      })
      dataList.push(obj)
    })
    tableData.value = dataList
  }).catch(err=>{
    console.log(err)
  })
}
const cellStyle = (val,cab)=>{
  //背景色 设计修改 暂时注释
  // if(val.row[`day${val.columnIndex}`] && val.row[`day${val.columnIndex}`] == '白' ){
  //   cab({background:"#EBF8E8"})
  // }else if(val.row[`day${val.columnIndex}`] && val.row[`day${val.columnIndex}`] == '中' ){
  //   cab({background:"#E6EFFC"})
  // }else if(val.row[`day${val.columnIndex}`] && val.row[`day${val.columnIndex}`] == '夜'){
  //   cab({background:"#E0E5EC"})
  // }else if(val.row[`day${val.columnIndex}`] && val.row[`day${val.columnIndex}`] == '休'){
  //   cab({background:"#FAFBFC"})
  // }
  if(val.row[`day${val.columnIndex}`] && val.row[`day${val.columnIndex}`] == '休'){
    cab({color:"#B3B7BE"})
  }
}
// 日历当中直接选择触发
const changeTime = (val) =>{
  getTableData(val)
}
//日期增加或减少
const ArrowLeftBold = (num) =>{
  let arr = selectMonth.value.split("-"); // 将 "yyyy-MM" 日期分解为 ["2021","09"]
	let year = parseInt(arr[0], 10);
	let month = parseInt(arr[1], 10);
	month = month + num;
	if (month > 12) {
		let newYear = parseInt((month - 1) / 12, 10);
		month = month % 12 == 0 ? 12 : month % 12;
		year += newYear;
	} else if (month <= 0) {
		month = Math.abs(month);
		let newYear = parseInt((month + 12) / 12, 10);
		let n = month % 12;
		if (n == 0) {
			year -= newYear;
			month = 12;
		} else {
			year -= newYear;
			month = Math.abs(12 - n);
		}
	}
	month = month < 10 ? "0" + month : month;
  getTableData(year + "-" + month)
	return selectMonth.value = year + "-" + month;
}

//获取本月 并加载当月数据
const obtainMonth = () =>{
  let date = new Date();
  let year = date.getFullYear();
  let month = (date.getMonth() + 1).toString().padStart(2, '0');
  getTableData(year + "-" + month)
  return selectMonth.value = year + "-" + month;
}
//批量排班 表单确认按钮
const submit = (val) =>{
  formLoading.value = true
  let dataArr = {
    deadLine:val.value.deadLine, //排班截至日期
    list:[
      {
        sfShiftId:val.value.oneClasses,//首班班次
        endTime:'',                    //班结束时间
        sfTeamId:val.value.oneClass,   //首班班组
        startTime:val.value.oneTime    //首班开始时间
      },
      {
        sfShiftId:val.value.twoClasses,//二班班次
        endTime:'',                    //二班结束时间
        sfTeamId:val.value.twoClass,   //二班班组
        startTime:val.value.twoTime    //二班开始时间
      },
      {
        sfShiftId:val.value.threeClasses,//三班班次
        endTime:'',                      //三班结束时间
        sfTeamId:val.value.threeClass,   //三班班组
        startTime:val.value.threeTime    //三班开始时间
      },
      {
        sfShiftId:val.value.fourClasses,//四班班次
        endTime:'',                     //四班结束时间
        sfTeamId:val.value.fourClass,   //四班班组
        startTime:val.value.fourTime    //四班开始时间
      },
    ]
  }
  batchGenerate(dataArr).then(res=>{
    dialogVisibleAddOrEdit.value = false
    formLoading.value = false
    proxy.$modal.msgSuccess("排班成功");
    getTableData(selectMonth.value)
  }).catch(err=>{
    formLoading.value = false
    console.log(err)
  })
}
//批量排版 表单取消按钮
const cancel = () =>{
  dialogVisibleAddOrEdit.value = false
}
// 批量排班
const autoSchedu = () => {
  dialogVisibleAddOrEdit.value = true
  //调取所有班组信息Api
  queryAllListApi()
  //调取所有班次信息Api
  classesListApi()
  teamsAndGroups.value = [null,null,null,null]

}
//查询所有班组信息
const queryAllListApi = () =>{
  queryAllList().then(res=>{
    res.data.forEach(item=>{
      item.value = item.id
      item.label = item.teamName
    })
    teamArr.value = res.data
  }).catch(err=>{
    console.log(err)
  })
}
//查询所有班次信息
const classesListApi = () =>{
  classesList().then(res=>{
    res.data.forEach(item=>{
      item.value = item.id
      item.label = item.shiftName
      item.timeSubstr = item.startTime
      if(item.orderSort == 1){
        elsForms.value.setValue( 'oneClasses',item.id)
      }
      if(item.orderSort == 2){
        elsForms.value.setValue( 'twoClasses',item.id)
      }
      if(item.orderSort == 3){
        elsForms.value.setValue( 'threeClasses',item.id)
      }
    })
    classesArr.value  = res.data
  }).catch(err=>{
    console.log(err)
  })
}
//修改表单参数
const elsForms = ref(null)
const formChange = (val) =>{
  // 选择首班开始时间
  if(val.field == "oneTime"){
    classesArr.value.forEach(item=>{
      //给首班开始时间进行时间处理
      if(item.id == elsForms.value.getValue('oneClasses')){
        elsForms.value.setValue( 'oneTime', val.val.substring(0, 10) + ' ' + item.timeSubstr)
        //因为第四班的休息时间和首班的开始时间相同 所有再次直接给4班的休息时间赋值
        elsForms.value.setValue( 'fourTime', val.val.substring(0, 10) + ' ' + item.timeSubstr)
      }
      //给二班开始时间进行时间处理
      if(item.id == elsForms.value.getValue('twoClasses')){
        elsForms.value.setValue( 'twoTime', val.val.substring(0, 10) + ' ' + item.timeSubstr)
      }
      //给三班开始时间进行时间处理
      if(item.id == elsForms.value.getValue('threeClasses')){
        //判断当前日期是否跨度到第二天
        let time = item.timeSubstr.substring(0, 2)
        // 如果时大于0并且小区8那么证明夜班已经是第二天了 进行日期加1从处理
        if(time*1 >= 0 && time*1 <= 8){
        var curDate = new Date(val.val);
        let dataTime = new Date((curDate/1000+86400)*1000)
        let year = dataTime.getFullYear()
        let month = dataTime.getMonth() + 1
        //月份补零
        if(month >= 1 && month <= 9){
          month = '0' + month
        }
        let strDate = dataTime.getDate()
        //日期补零
        if(strDate >= 1 && strDate <= 9){
          strDate = '0' + strDate
        }
        let timeval = year +'-'+  month + '-' + strDate
        elsForms.value.setValue( 'threeTime', timeval +  ' ' + item.timeSubstr)
        // 三班反之的话直接用当前日期时间
        }else{
        elsForms.value.setValue( 'threeTime', val.val.substring(0, 10) + ' ' +  item.timeSubstr)
        }
      }

    })
  }
  //选择班组
  if(val.field == "oneClass"){
    packageSelectTeam(0,val.val)
  }
  if(val.field == "twoClass"){
    packageSelectTeam(1,val.val)
  }
  if(val.field == "threeClass"){
    packageSelectTeam(2,val.val)
  }
  if(val.field == "fourClass"){
    packageSelectTeam(3,val.val)
  }
}
//定义两个数组  在批量排班时候 选择班组时作为辅助参数
const teamsAndGroups = ref([null,null,null,null])
const teamsArr = ref(['oneClass','twoClass','threeClass','fourClass'])
//选择班组时候 进行的规则方法 做一下封装 统一调用
const packageSelectTeam = (i,valTypes) =>{
  // 判断是否在第一个数组当中有存在的id 如果有的话检索出来把
  if(teamsAndGroups.value.some(it=>{return valTypes == it}) && teamsAndGroups.value[i] != valTypes){
        teamsAndGroups.value.forEach((it,index)=>{
          // 如果有的话检索出来
          if(it == valTypes){
            // 给存在null数组清空
            teamsAndGroups.value[index] = null
            // 给之前已选中的字段清空
            elsForms.value.setValue(teamsArr.value[index],'')
          }
        })
        proxy.$modal.msgWarning("当前选择班组已存在排班计划，已重新分配");
     }
    //  在次给新地赋值
     teamsAndGroups.value[i] = valTypes
}

obtainMonth()
const {
  columns,
  pageSet,
  tableOption,
  fieldList,
  formOption,
} = init({ headerArr ,teamArr,classesArr})
</script>

<style lang="scss" scoped>
.pickerBig{
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  .pickeTitle{
    display: inline-block;
    line-height: 36px;
    height: 30px;
    align-items: center;
    text-align: center;
    font-weight: 600;
  }
}
.el-alert--info.is-light {
  background-color:#E6EFFC;
  color: #1455d9;
  margin: 0 0 20px 0;
}
:deep(.weekdays){
  background:#f5f7fa;
}
/*::v-deep 这里主要的作用就是用来强制修改element默认的样式*/
:deep(.el-table thead.is-group th){
  background: none;
  padding: 0px;
}
:deep(.el-table thead.is-group tr:first-of-type th:first-of-type){
  border-bottom: none;/*中间的横线去掉*/
}
:deep(.el-table thead.is-group tr:first-of-type th:first-of-type div.cell){
  text-align: right;/*上边文字靠右*/
}
:deep(.el-table thead.is-group tr:last-of-type th:first-of-type div.cell){
  text-align: left;/*下边文字靠左*/
}
:deep(.el-table thead.is-group tr:last-of-type th:first-of-type:before){
  content: "";
  position: absolute;
  width: 1px;
  height: 160px;/*斜线的长度*/
  bottom: 0;
  right: 0;
  background-color: #EBEDEE;
  opacity: 1;
  display: block;
  transform: rotate(-45deg);/*调整斜线的角度*/
  -webkit-transform-origin: bottom;
  transform-origin: bottom;
}
</style>
