<template>
  <div class="drawer-container">
    <!-- 遮罩层 -->
    <div
      v-show="visible"
      :class="['drawer-mask', { 'drawer-mask-show': visible, 'drawer-mask-hide': !visible }]"
      @click="closeByMask"
    ></div>

    <!-- 抽屉内容 -->
    <div
      :class="['drawer-main', `drawer-${direction}`, { 'drawer-main-show': visible, 'drawer-main-hide': !visible }]"
      :style="mainStyle"
    >
      <div class="drawer-header">
        <span class="drawer-title">{{ title }}</span>
        <el-button
          v-if="showClose"
          class="drawer-close-btn"
          icon="el-icon-close"
          type="text"
          @click="closeByButton"
        ></el-button>
      </div>
      <div class="drawer-body">
        <div style="display: none;">
          <!--学生请假审批-->
          <stu-leave-apply ref="stuApplyRef" v-if="permissions.stuwork_pending_work_stuleaveapply"></stu-leave-apply>
          <!--班级请假审批-->
          <class-leave-apply ref="classLeaveRef" v-if="permissions.stuwork_pending_work_stuleaveapply"></class-leave-apply>
          <!--留宿申请审批-->
          <dorm-live-apply ref="dormLiveApplyRef" v-if="permissions.stuwork_pending_work_dormliveapply"></dorm-live-apply>
          <!-- 顶岗申请审批 -->
          <company-change ref="companyChangeRef"></company-change>
          <!-- 场地使用申请审批 -->
          <building-assembly-room-apply ref="buildingAssemblyRoomApplyRef"></building-assembly-room-apply>

          <!-- 固定资产调拨 -->
          <asset-d-b ref="assetDB" v-if="permissions.asset_assetassetstransfer_edit"></asset-d-b>
          <!-- 资产报废 -->
          <asset-b-f ref="assetBF" v-if="permissions.asset_assetassetsinvalid_edit"></asset-b-f>
          <!-- 资产预报废 -->
          <asset-y-b-f ref="assetYBF" v-if="permissions.asset_assetassetsinvalid_add"></asset-y-b-f>
          <!-- 入库单待处理 -->
          <asset-in ref="assetIn" v-if="permissions.asset_assetinbound_exam_dept || permissions.asset_assetinbound_exam_hq "></asset-in>
          <!-- 出库单待处理 -->
          <asset-out ref="assetOut" v-if="permissions.asset_assetassetsdetail_edit || permissions.asset_assetassets_exam"></asset-out>
          <!-- 采购申请单-->
          <purchasingrequisition ref="purchasingrequisition" ></purchasingrequisition>
          <!-- 采购流转单-->
          <purchasingwander ref="purchasingwander" v-if="permissions.finance_purchasingrequisition_look"></purchasingwander>
          <!-- 履约验收-->
          <purchasinglyys ref="purchasinglyys" v-if="permissions.finance_purchasinglypj_look"></purchasinglyys>
          <!-- 省常技12345-->
          <schoolBully ref="schoolBully"  v-if="permissions.stuwork_schoolbully_look"></schoolBully>
          <!-- 培训项目审核 -->
          <train-project-apply ref="trainProjectApplyRef"></train-project-apply>

          <!--培训项目到账-->
          <train-project-arrived-apply ref="trainProjectArrivedApplyRef"></train-project-arrived-apply>
        </div>
        <el-tabs v-model="activeName" @tab-click="changeTaskTab">
          <el-tab-pane label="已订阅任务" name="1">
            <el-table :data="tableData"  height="150" border v-loading="tableLoading">
              <el-table-column prop="label" label="任务类型" min-width="100" align="center"></el-table-column>
              <el-table-column prop="value" label="待办" min-width="80" align="center">
                <template v-slot="scope">
                  <el-tag size="mini" type="danger" v-if="taskNumMap[scope.row.type]">{{taskNumMap[scope.row.type]}}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" min-width="150">
                <template v-slot="scope">
                  <el-button type="text" size="mini" @click="handleShowDetail(scope.row)" icon="el-icon-view">查看</el-button>
                  <el-button type="text" size="mini" @click="handleIgnoreTask(scope.row,scope.$index)" icon="el-icon-close" >不再提醒</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="已取消订阅" name="2">
            <el-table :data="ignoreTask" border height="150" v-loading="tableLoading">
              <el-table-column label="任务类型" prop="label" min-width="100" align="center"></el-table-column>
              <el-table-column label="操作" min-width="150" align="center">
                <template v-slot="scope">
                  <el-button type="text" size="mini" @click="handleCancleIgnore(scope.row,scope.$index)" icon="el-icon-check">恢复</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>

      </div>
    </div>
  </div>
</template>

<script>
import StuLeaveApply from "@/page/task/stuLeaveApply.vue";
import ClassLeaveApply from "@/page/task/classLeaveApply.vue";
import {mapGetters} from "vuex";
import {getStuLeaveApplyTask} from "@/api/stuwork/stuleaveapply";
import {getClassLeaveApplyTask} from "@/api/stuwork/classleaveapply";
import {getStore, setStore} from "@/util/store";
import DormLiveApply from "@/page/task/dormLiveApply.vue";
import {getDormLiveApplyTask} from "@/api/stuwork/dormliveapply";
import * as taskApi from "@/api/activiti/task";
import purchasingrequisition from "@/page/task/purchasingrequisition.vue";
import assetOut from "@/page/task/assetOut.vue";
import purchasingwander from "@/page/task/purchasingwander.vue";
import CompanyChange from "@/page/task/companyChange.vue";
import assetIn from "@/page/task/assetIn.vue";
import buildingAssemblyRoomApply from "@/page/task/buildingAssemblyRoomApply.vue";
import schoolBully from "@/page/task/schoolBully.vue";
import assetYBF from "@/page/task/assetYBF.vue";
import purchasinglyys from "@/page/task/purchasinglyys.vue";
import assetDB from "@/page/task/assetDB.vue";
import assetBF from "@/page/task/assetBF.vue";
import {hasTimeOut} from "@/api/asset/assets/assetassets";
import {fetchListPage} from "@/api/asset/assetinbound/assetinbound";
import {pageIndex} from "@/api/asset/assetoutbound/assetoutbound";
import {waitingList} from "@/api/purchase/purchasinglypj";
import {fetchList} from "@/api/stuwork/schoolbully";
import trainProjectApply from "@/page/task/trainProjectApply.vue";
import trainProjectArrivedApply from "@/page/task/trainProjectArrivedApply.vue";

export default {
  name: 'CustomDrawer',
  components: {
    trainProjectArrivedApply,
    trainProjectApply,
    assetBF,
    assetDB,
    purchasinglyys,
    assetYBF,
    schoolBully,
    buildingAssemblyRoomApply,
    assetIn,
    CompanyChange,
    purchasingwander,
    assetOut,
    purchasingrequisition,
    DormLiveApply, ClassLeaveApply, StuLeaveApply},
  data() {
    return {
      timer:Object,
      activeName: '1',
      deleteTaskType:[],
      showCompent:{},
      taskNumMap:{},
      allTaskTable:[
        {label:"学生请假",type:"1",value:0},
        {label:"班级请假",type:"2",value:0},
        {label:"留宿申请",type:"3",value:0},
        {label:"单位申请",type:"4",value:0},
        {label:"场地使用申请",type:"5",value:0},
        {label:"资产调拨申请",type:"6",value:0},
        {label:"资产报废申请",type:"7",value:0},
        {label:"资产预报废",type:"8",value:0},
        {label:"资产入库申请",type:"9",value:0},
        {label:"资产出库申请",type:"10",value:0},
        {label:"采购申请",type:"11",value:0},
        {label:"采购审核",type:"12",value:0},
        {label:"履约验收",type:"13",value:0},
        {label:"省常技12345",type:"14",value:0},
        {label:"培训项目审核",type:"15",value:0},
        {label:"培训到账审核",type:"16",value:0},
      ],
      normalTaskTable:[],
      tableData:[
      ],
      ignoreTask:[
      ],
      tableLoading:false
    };
  },
  props: {
    visible: { // 控制抽屉显示
      type: Boolean,
      default: false
    },
    title: { // 抽屉标题
      type: String,
      default: '标题'
    },
    direction: { // 抽屉方向
      type: String,
      default: 'right', // 可选 'left', 'right', 'top', 'bottom'
      validator: (value) => ['left', 'right', 'top', 'bottom'].includes(value)
    },
    width: { // 抽屉宽度（左右方向时有效）
      type: String,
      default: '400px'
    },
    height: { // 抽屉高度（上下方向时有效）
      type: String,
      default: '300px'
    },
    showClose: { // 是否显示关闭按钮
      type: Boolean,
      default: true
    },
    maskClosable: { // 点击遮罩层是否可关闭
      type: Boolean,
      default: true
    },
    withHeader: { // 是否显示头部
      type: Boolean,
      default: true
    }
  },
  computed: {
    ...mapGetters(['permissions']),
    mainStyle() {
      // 根据方向设置宽度或高度
      const style = {};
      if (this.direction === 'left' || this.direction === 'right') {
        style.width = this.width;
      } else {
        style.height = this.height;
      }
      return style;
    }
  },
  watch:{
    visible:{
      immediate: true,
      handler(val){
        if (val){
          //初始化已订阅任务
          this.activeName='1'
          this.initNormalTask();
          //初始化未订阅任务
          this.$nextTick(()=>{
              this.initTaskTableData()
          })
        }
      }
    }
  },
  methods: {
    initTaskTableData(){
      this.tableLoading=this
      this.tableData=[]
      //查询已订阅任务的  任务值  将任务数为0的忽略掉
      let ignoreTypeList = getStore({name:"myTaskTable_ignore"})
      if (undefined == ignoreTypeList) {
        ignoreTypeList = [];
      }
      if (!ignoreTypeList.includes("1")) {
        if (this.$refs.stuApplyRef) {
          this.getStuLeaveData();
        }
      }
      if (!ignoreTypeList.includes("2")) {
        if(this.$refs.classLeaveRef){
          this.getClassLeaveData()
        }
      }
      if (!ignoreTypeList.includes("3")) {
        if (this.$refs.dormLiveApplyRef) {
          this.getDormApply()
        }
      }
      if (!ignoreTypeList.includes("4")) {
        if (this.$refs.companyChangeRef) {
          this.getCompanyChangeTask()
        }
      }
      if (!ignoreTypeList.includes("5")) {
        if (this.$refs.buildingAssemblyRoomApplyRef) {
          this.getBuildingAssemblyRoomApply();
        }
      }
      if (!ignoreTypeList.includes("6")) {
        if (this.$refs.assetDB) {
          this.getAssesstsTransferTask()
        }
      }
      if (!ignoreTypeList.includes("7")) {
        if (this.$refs.assetBF) {
          this.getAssetBfList();
        }
      }
      if (!ignoreTypeList.includes("8")) {
        if (this.$refs.assetYBF) {
          this.getYbFData()
        }
      }
      if (!ignoreTypeList.includes("9")) {
        if (this.$refs.assetIn) {
          this.getAssetInList()
        }
      }
      if (!ignoreTypeList.includes("10")) {
        if (this.$refs.assetOut) {
          this.getAssetOutList()
        }
      }
      if (!ignoreTypeList.includes("11")) {
        if (this.$refs.purchasingrequisition) {
          this.getPurchaseList()
        }
      }
      if (!ignoreTypeList.includes("12")) {
        if (this.$refs.purchasingwander) {
          this.getPruchaseWarningList()
        }
      }
      if (!ignoreTypeList.includes("13")) {
        if (this.$refs.purchasinglyys) {
          this.getPurchaseLyysData();
        }
      }
      if (!ignoreTypeList.includes("14")) {
        if (this.$refs.schoolBully) {
          this.getSchoolBully()
        }
      }
      if (!ignoreTypeList.includes("15")) {
        if (this.$refs.trainProjectApplyRef) {
          this.getTrainProjectApply()
        }
      }
      if (!ignoreTypeList.includes("16")) {
        if (this.$refs.trainProjectArrivedApplyRef) {
          this.getTrainProjectArrived()
        }
      }
      setTimeout(()=>{
        this.tableLoading=false
      },1500);
    },
    changeTaskTab(tab){
      if (tab.name == '1') {
        this.initNormalTask()
        this.initTaskTableData()
      }
      if (tab.name == '2') {
        this.initIgnoreTask();
      }
    },
    initNormalTask(){
      this.normalTaskTable=[]
      let ignoreTypeList = getStore({name:"myTaskTable_ignore"})
      for (let item of this.allTaskTable) {
        if (!ignoreTypeList||!ignoreTypeList.includes(item.type)) {
          this.normalTaskTable.push(item)
        }
      }
      this.initIgnoreTask();
    },
    initIgnoreTask(){
      this.ignoreTask=[]
      //存在忽略的订阅任务  则清除数据
      let ignoreTypeList = getStore({name:"myTaskTable_ignore"})
      for (let item of this.allTaskTable) {
        if (ignoreTypeList && ignoreTypeList.includes(item.type)) {
          this.ignoreTask.push(item)
        }
      }
    },
    //任务查询集合 start
    getStuLeaveData() {
      getStuLeaveApplyTask({}).then(response => {
        this.taskNumMap['1']=response.data.data.length
        //忽略 没有任务数的 订阅任务
        this.removeTaskTableColumen(response.data.data, "1")
      })
    },
    getClassLeaveData(){
      getClassLeaveApplyTask().then(response=>{
        this.taskNumMap['2']=response.data.data.length
        //忽略 没有任务数的 订阅任务
        this.removeTaskTableColumen(response.data.data, "2")
      })
    },
    getDormApply(){
      getDormLiveApplyTask().then(response => {
        this.taskNumMap['3']=response.data.data.length
        //忽略 没有任务数的 订阅任务
        this.removeTaskTableColumen(response.data.data, "3")
      })
    },
    getCompanyChangeTask(){
      taskApi.fetchList({"current":1,"size":9999,"procDefKey":"work_stu_company_change"}).then(response => {
        this.taskNumMap['4']=response.data.data.records.length
        //忽略 没有任务数的 订阅任务
        this.removeTaskTableColumen(response.data.data.records, "4")
      })
    },
    getBuildingAssemblyRoomApply(){
      taskApi.fetchList({"current":1,"size":9999,"procDefKey":"building_assembly_room_apply"}).then(response => {
        this.taskNumMap['5']=response.data.data.records.length
        //忽略 没有任务数的 订阅任务
        this.removeTaskTableColumen(response.data.data.records, "5")
      })
    },
    getAssesstsTransferTask(){
      taskApi.fetchList({"current":1,"size":9999,"procDefKey":"assetsTransfer"}).then(response => {
        this.taskNumMap['6']=response.data.data.records.length
        //忽略 没有任务数的 订阅任务
        this.removeTaskTableColumen(response.data.data.records, "6")
      })
    },
    getAssetBfList(){
      taskApi.fetchList({"current":1,"size":9999,"procDefKey":"asset_invalid"}).then(response => {
        this.taskNumMap['7']=response.data.data.records.length
        //忽略 没有任务数的 订阅任务
        this.removeTaskTableColumen(response.data.data.records, "7")
      })
    },
    getYbFData(){
      let page={currentPage:1,pageSize:10}
      hasTimeOut(Object.assign({
        current: page.currentPage,
        size: page.pageSize
      }, {})).then(response => {
        this.taskNumMap['8']=response.data.data.total
        //忽略 没有任务数的 订阅任务
        this.removeTaskTableColumenForLength(response.data.data.total, "8")
      })
    },
    getAssetInList(){
      let page={currentPage:1,pageSize:10}
      fetchListPage(Object.assign({
        current: page.currentPage,
        size: page.pageSize
      }, {})).then(response => {
        this.taskNumMap['9']=response.data.data.total
        //忽略 没有任务数的 订阅任务
        this.removeTaskTableColumenForLength(response.data.data.total, "9")
      })
    },
    getAssetOutList(){
      let page={currentPage:1,pageSize:10}
      pageIndex(Object.assign({
        current: page.currentPage,
        size: page.pageSize
      }, {})).then(response => {
        this.taskNumMap['10']=response.data.data.total
        //忽略 没有任务数的 订阅任务
        this.removeTaskTableColumenForLength(response.data.data.total, "10")
      })
    },
    getPurchaseList(){
      taskApi.fetchList({"current":1,"size":9999,"procDefKey":"process"}).then(response => {
        this.taskNumMap['11']=response.data.data.records.length
        //忽略 没有任务数的 订阅任务
        this.removeTaskTableColumen(response.data.data.records, "11")
      })
    },
    getPruchaseWarningList(){
      taskApi.fetchList({"current":1,"size":9999,"procDefKey":"processWander"}).then(response => {
        this.taskNumMap['12']=response.data.data.records.length
        //忽略 没有任务数的 订阅任务
        this.removeTaskTableColumen(response.data.data.records, "12")
      })
    },
    getPurchaseLyysData(){
      waitingList().then(response => {
        this.taskNumMap['13']=response.data.data.length
        //忽略 没有任务数的 订阅任务
        this.removeTaskTableColumen(response.data.data, "13")

      });
    },
    getSchoolBully(){
      let page={currentPage:1,pageSize:10}
      fetchList(Object.assign({
        current: page.currentPage,
        size: page.pageSize
      }, {isContact:0})).then(response => {
        this.taskNumMap['14']=response.data.data.total
        //忽略 没有任务数的 订阅任务
        this.removeTaskTableColumenForLength(response.data.data.total, "14")
      })
    },
    getTrainProjectApply(){
      taskApi.fetchList({"current":1,"size":9999,"procDefKey":"train_project_approval"}).then(response => {
        this.taskNumMap['15']=response.data.data.records.length
        //忽略 没有任务数的 订阅任务
        this.removeTaskTableColumen(response.data.data.records, "15")
      })
    },
    getTrainProjectArrived(){
      taskApi.fetchList({"current":1,"size":9999,"procDefKey":"train_project_money_arrived"}).then(response => {
        this.taskNumMap['16']=response.data.data.records.length
        //忽略 没有任务数的 订阅任务
        this.removeTaskTableColumen(response.data.data.records, "16")
      })
    },
    removeTaskTableColumen( data,targetType){
      if (data.length > 0) {
        for (let index in this.normalTaskTable) {
          if (this.normalTaskTable[index].type == targetType) {
            this.tableData.push(this.normalTaskTable[index])
          }
        }
      }
    },
    removeTaskTableColumenForLength( dataLength,targetType){
      if (dataLength >0) {
        for (let index in this.normalTaskTable) {
          if (this.normalTaskTable[index].type == targetType) {
            this.tableData.push(this.normalTaskTable[index])
          }
        }
      }
    },
    handleShowDetail(row){
      if (row.type == '1') {
        this.$refs.stuApplyRef.handleShowList();
      }
      if (row.type == '2') {
        this.$refs.classLeaveRef.handleShowList();
      }
      if (row.type == '3') {
        this.$refs.dormLiveApplyRef.handleShowList();
      }
      if (row.type == '4') {
        this.$refs.companyChangeRef.handleShowList();
      }
      if (row.type == '5') {
        this.$refs.buildingAssemblyRoomApplyRef.handleShowList();
      }
      if (row.type == '6') {
        this.$refs.assetDB.handleShowList();
      }
      if (row.type == '7') {
        this.$refs.assetBF.handleShowList();
      }
      if (row.type == '8') {
        this.$refs.assetYBF.handleShowList();
      }
      if (row.type == '9') {
        this.$refs.assetIn.handleShowList();
      }
      if (row.type == '10') {
        this.$refs.assetOut.handleShowList();
      }
      if (row.type == '11') {
        this.$refs.purchasingrequisition.handleShowList();
      }
      if (row.type == '12') {
        this.$refs.purchasingwander.handleShowList();
      }
      if (row.type == '13') {
        this.$refs.purchasinglyys.handleShowList();
      }
      if (row.type == '14') {
        this.$refs.schoolBully.handleShowList();
      }
      if (row.type == '15') {
        this.$refs.trainProjectApplyRef.handleShowList();
      }
      if (row.type == '16') {
        this.$refs.trainProjectArrivedApplyRef.handleShowList();
      }
    },
    handleIgnoreTask(row,index){
      let ignoreTypeList = getStore({name:"myTaskTable_ignore"})
      if (undefined == ignoreTypeList) {
        ignoreTypeList = [];
      }
      ignoreTypeList.push(row.type);
      setStore({name:"myTaskTable_ignore",content:ignoreTypeList, type: "session"});
      this.tableData.splice(index,1)
    },
    handleCancleIgnore(row,index){
      let ignoreTask = getStore({name:"myTaskTable_ignore"})
      if (ignoreTask) {
        let index=ignoreTask.indexOf(row.type)
        ignoreTask.splice(index,1)
      }
      setStore({name:"myTaskTable_ignore",content:ignoreTask, type: "session"});
      this.ignoreTask.splice(index,1)
    },
    handleClick(){

    },
    closeByMask() {
      if (this.maskClosable) {
        this.$emit('update:visible', false); // 支持 .sync 修饰符
        this.$emit('close', 'mask');
      }
    },
    closeByButton() {
      this.$emit('update:visible', false);
      this.$emit('close', 'button');
    }
  }
};
</script>

<style scoped>
.drawer-container {
  font-family: inherit; /* 继承 Element UI 的字体 */
}

.drawer-mask {
  //position: fixed;
  //top: 0;
  //left: 0;
  //width: 100%;
  //height: 100%;
  //background-color: rgba(0, 0, 0, 0.5);
  //z-index: 2000; /* 确保遮罩层在抽屉之下，但在其他页面内容之上 */
  //transition: opacity 0.3s ease;
}

.drawer-mask-show {
  opacity: 1;
}

.drawer-mask-hide {
  opacity: 0;
  pointer-events: none; /* 隐藏时不允许交互 */
}

.drawer-main {
  position: fixed;
  z-index: 2001; /* 在遮罩层之上 */
  background: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.drawer-right {
  top: 65%;
  right: 0;
  height: 34%;
  transform: translateX(100%);
}

.drawer-left {
  top: 0;
  left: 0;
  height: 30%;
  transform: translateX(-100%);
}

.drawer-top {
  top: 0;
  left: 0;
  width: 100%;
  transform: translateY(-100%);
}

.drawer-bottom {
  bottom: 0;
  left: 0;
  width: 100%;
  transform: translateY(100%);
}

.drawer-main-show {
  transform: translateX(0) translateY(0); /* 显示时复位 */
  opacity: 1;
}

.drawer-main-hide {
  /* 根据方向隐藏 */
  opacity: 0;
  pointer-events: none;
}
.drawer-right.drawer-main-hide {
  transform: translateX(100%);
}
.drawer-left.drawer-main-hide {
  transform: translateX(-100%);
}
.drawer-top.drawer-main-hide {
  transform: translateY(-100%);
}
.drawer-bottom.drawer-main-hide {
  transform: translateY(100%);
}

.drawer-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 10px;
  border-bottom: 1px solid #ebeef5;
  font-size: 14px;
  font-weight: bold;
  color: #303133;
  flex-shrink: 0; /* 防止头部被压缩 */
}

.drawer-title {
  line-height: 1;
}

.drawer-close-btn {
  padding: 0;
  margin-left: auto; /* 将关闭按钮推到右侧 */
}

.drawer-body {
  flex: 1; /* 占据剩余空间 */
  padding: 10px;
  overflow-y: auto; /* 内容过多时允许滚动 */
}
</style>
