<template>
  <div style="padding: 0 20px">
    <div ref="lxHeader">
      <lx-header icon="md-apps" :text="type_name" style="margin-bottom: 10px; border: 0px; margin-top: 15px">
        <slot>
          <div style="display: flex;justify-content: flex-start;flex-wrap: wrap;">
            <el-select class='height32' style="width: 150px;margin-right: 10px;" filterable clearable v-model="select.unit_type" placeholder="任务类型">
                <el-option
                  v-for="item in unitTypeList"
                  :key="item.id" :label="item.value" :value="item.id">
                </el-option>
            </el-select>
            <el-select class='height32' style="width: 150px;margin-right: 10px;" filterable clearable v-model="select.audit_status" placeholder="任务状态">
              <el-option
                v-for="item in selectAuditStatusList"
                :key="item.id" :label="item.value" :value="item.id">
              </el-option>
            </el-select>
            <el-date-picker @change="changeDate" v-model="select.dateRange" type="daterange"
              :picker-options="pickerOptions" value-format="yyyy-MM-dd" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" align="right">
            </el-date-picker>
            <Input v-model="select.keyword" style="width: 150px;margin-right: 10px;" placeholder="关键字搜索" />

            <Button type="primary" @click="getList" style="margin-right: 10px;">查询</Button>
            <!-- <Button v-if="path_type!=5" type="primary" style="margin-right: 10px;"
              @click="editorUnit('','add')">添加</Button> -->
              <!-- <Button type="primary" v-if="path_type!=5" style='margin-right:10px' @click="chooseEditorUnit()">编辑</Button> -->

          </div>
        </slot>
      </lx-header>
    </div>

    <div class="tablewrap">
      <div class="tablemonth">
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;"></div>
        <el-checkbox-group v-model="selectMonth" @change="changeMonth">
            <el-checkbox v-for="item in allMonths" :label="item"></el-checkbox>
          </el-checkbox-group>
      </div>

      <div class="tablecontent">
        <div>{{selectMonth.join('、')}}共有{{currentTableList.length}}项任务，{{auditStatus2.length}}项未完成</div>
        <xy-table
          :list="currentTableList"
          :total="total"
          stripe
          :span-method="spanMethod"
          :showIndex='false'
          :isPage="false"
          @cell-dblclick='cellClicks'
          @selection-change='selectionChange'
          @pageSizeChange="e => {select.page_size = e,getList()}"
          @pageIndexChange="e => {select.page = e,getList()}"
          :table-item="table">
            <template v-slot:btns>
              <el-table-column align='center' fixed="right" label="操作" width="100" header-align="center">
                <template slot-scope="scope">
                  <template v-if="path_type!=5">
                    <div>
                      <Button type="primary" style='margin-right:5px;margin-bottom:5px;' size="small" @click="checkUnits(scope.row.id,'show')">查看</Button>
                    </div>
                    <div>
                      <Button style="margin-right:5px;margin-bottom:5px;" type="primary" size="small" @click="editorUnit(scope.row.id,'editor')">编辑</Button>
                    </div>
                    <div>
                      <Button v-if="scope.row.audit_admin_id==stateObj.login_id&&scope.row.audit_status==0" style="margin-right:5px;margin-bottom:5px;" type="primary" size="small" @click="checkUnits(scope.row.id,'check')">审核</Button>
                    </div>
                  </template>
                  <template v-else>
                      <div v-for="item in unitTypeList">
                        <Button v-if="scope.row.unit_type==item.id&&scope.row.audit_status==1" type="primary" size="small" style="margin-right:5px;margin-bottom:5px;" @click="openMyMission(item.value,scope.row)">{{item.remark}}</Button>
                       <!-- <Button v-if="scope.row.unit_type==item.id" type="primary" size="small" style="margin-right:5px;margin-bottom:5px;" @click="openAsks(scope.row)">开始答题</Button>
                        <Button type="primary" size="small" style="margin-right:5px;margin-bottom:5px;" @click="$refs['addPatrol'].mission_id=scope.row.id,$refs['addPatrol'].isShow=true,$refs['addPatrol'].type='add'">开展任务</Button>
                      -->
                      </div>
                      <div>
                        <!-- <Button style="margin-right:5px;margin-bottom:5px;" type="primary" size="small" @click="editorUnit(scope.row.id,'editor')">分发</Button> -->
                      </div>
                      <div>
                        <Button style='margin-right:5px;margin-bottom:5px;' type="primary" size="small" @click="checkUnits(scope.row.id,'show')">查看</Button>
                      </div>

                  </template>
                  <div>
                    <Button style='margin-right:5px;margin-bottom:5px;' size="small" @click="backPlan(scope.row)">归档</Button>
                  </div>
                </template>
              </el-table-column>
            </template>
          </xy-table>
      </div>
    </div>



    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%">
      <span>请确认是否将该任务归档到<span style="color:red">安全生产标准化台账管理</span>中？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>


    <addUnit ref='addUnit' @refresh='getList'></addUnit>

    <showPatrol ref='showPatrol'></showPatrol>
    <addPatrol ref='addPatrol' @refresh='getList'></addPatrol>
    <checkUnit ref='checkUnit' @refresh='getList'></checkUnit>
    <answerQuestion @refresh='getList' ref='answerQuestion'></answerQuestion>
  </div>
</template>

<script>
  import addUnit from '../list/components/addUnit.vue'
  import showPatrol from '../list/components/showPatrol.vue'
  import addPatrol from '../list/components/addPatrol.vue'
  import checkUnit from '../list/components/checkUnit.vue'
  import answerQuestion from '../list/components/answerQuestion.vue'
  import {
    listunit,
    del
  } from '@/api/task/unit.js'

  import {
    getparameteritem
  } from "@/api/system/dictionary.js";
  import state from '@/store/modules/user.js'
  import {contactGroup} from './js/index.js'
  import {
    getMergeCells,
    groupBy
  } from '@/utils/contactTable.js'
  export default {
    components: {
      addUnit,
      showPatrol,
      addPatrol,
      checkUnit,
      answerQuestion
    },
    data() {
      return {
        type_name: '',
        path_type:4,
        dialogVisible:false,
        stateObj:{},
        typeName: [{
          type: 1,
          name: '年度计划任务'
        },{
          type: 4,
          name: '专项专题任务'
        }, {
          type: 5,
          name: '我的待办任务'
        }],
        select: {
          keyword: '',
          page: 1,
          page_size: 9999,
          myself: 0,
          myself_department: 0,
          type: 1,
          unit_type: '',
          audit_status:'',
          dueDate:[],
          start_date:'',
          end_date:'',
          sort_name:'start_date',
          sort_type:'DESC',
          year:2024,
          month:"04"
        },
        total: 0,
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        selectAuditStatusList:[{
          id:4,
          value:'待办',
          type:'info'
        },{
          id:1,
          value:'开展中',
          type:''
        },{
          id:2,
          value:'办理中',
          type:'danger'
        },{
          id:3,
          value:'已完成',
          type:'success'
        }],
        auditStatusList:[{
          id:4,
          value:'待办',
          type:'info'
        },{
          id:1,
          value:'开展中',
          type:''
        },{
          id:2,
          value:'未完成',
          type:'danger'
        },{
          id:3,
          value:'已完成',
          type:'success'
        }],
        unitTypeList: [],
        askList:[],
        list: [],

        sectionList:[],
        currentTableList:[],
        auditStatus2:[],
        isIndeterminate:true,
        checkAll:false,
        selectMonth:[],
        allMonths : ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],

        table: [{
            label: "工作项目",
            prop: 'menu',
            // fixed:'left',
            align:'center',
            width:180,
            fixed:'left'
          },{
            label: "性质级别",
            prop: 'level',
            // fixed:'left',
            align:'left',
            width:180,
            fixed:'left'
          },{
            label: "任务名称",
            prop: 'name',
            // fixed:'left',
            align:'left',
            width:300,
          },{
            label: "任务内容及要求",
            prop: 'content',
            width: 200,
            align:'center',
          },{
            label: "开始日期",
            prop: 'start_date',
            width: 120,
            align:'center'
          }, {
            label: "结束日期",
            prop: 'end_date',
            width: 120,
            align:'center'
          },
          {
            label: "状态",
            prop: 'audit_status',
            width: 120,
            align:'center',
            customFn:(row)=>{
              return(<div>
              {
                this.auditStatusList.map(item=>{
                  if(item.id==row.audit_status){
                    return(<el-tag type={item.type}>{item.value}</el-tag>)
                  }
                })
              }
              </div>)
            }
          },
          // {
          //   label: "任务类型",
          //   prop: 'unit_type_detail.value',
          //   width: 120,
          //   align:'center',
          // }
           {
            label: "参与对象",
            prop: '_names',
            width: 360,
            align: 'left',
            customFn:row=>{
              return(<div  style={{"display": "flex","flex-wrap": "wrap"}}>
              {
                row._names?
                row._names.map(item=>{
                  return(<div>
                    {
                      item.admin_details?
                      // 小组
                      <div style={{"display": "flex"}}><div>{item.name}：</div>
                        <div  style={{"display": "flex","flex-wrap": "wrap"}}>{
                          item.admin_details.length>0?
                          item.admin_details.map(detail=>{
                            return(
                              <el-tag type={detail.hasDetail?'':'info'} style={{'margin':'0 5px 5px 0'}}>{detail.name}</el-tag>
                            )
                          })
                          :''
                        }
                        {
                          item.dep_details.length>0?
                          item.dep_details.map(detail=>{
                            return(
                              <el-tag type={detail.hasDetail?'':'info'} style={{'margin':'0 5px 5px 0'}}>{detail.name}</el-tag>
                            )
                          })
                          :''
                        }
                        </div>
                      </div>
                      :
                      // 其他
                      <el-tag type={item.hasDetail?'':'info'} style={{'margin':'0 5px 5px 0'}}>{item.name}</el-tag>
                    }
                  </div>)
                }):''
              }</div>)
            }
          },{
            label: "创建人",
            prop: 'admin.name',
            width: 120,
            align: 'center',
          },{
            label: "创建时间",
            prop: 'created_at',
            width: 120,
            align: 'center',
            formatter: (cell, data, value, index) => {
              return value?value.substring(0,11):''
            }
          }],
        }
      },
      computed: {
        // 获取所有单元格合并数据
        spanArr() {
          for(var k in this.currentTableList){
            if (!this.currentTableList.length) return []
            const mergeCols = ['menu','level'] // 需要合并的列（字段）
            const data = this.groupBy(this.currentTableList, 'menu')
            return getMergeCells(data, this.table, mergeCols)
          }
        }
      },
      created() {
          this.getLeads()
          this.stateObj = state.state
          let currentMonth = this.allMonths[(new Date()).getMonth()]
          // this.selectMonth = this.allMonths
          this.selectMonth.push(currentMonth)
          this.path_type = 1
          this.getUnitTypeList()
          this.getList()

        },
        watch: {},
        methods: {
          async getLeads(){
            // await this.$store.dispatch("user/getLeads")
          },
          backPlan(row){
            this.dialogVisible = true
          },
          async getUnitTypeList(){
            const res = await getparameteritem('unitTypeList')
            this.unitTypeList = res.detail
          },
          // 我的任务中的操作
          openMyMission(remark,e){
            switch(remark){
              case '检查':
                this.addPatrol(e)
                break;
              case '学习':
                this.openStudy(e)
                break;
              case '答题':
                this.openAnswers(e)
                break;
              case '培训':
                this.openTrain(e)
                break;
              case '资料收集':
                this.openUploads(e)
                break;
            }
          },

          addPatrol(scope){
            this.$refs['addPatrol'].login_id=this.stateObj.login_id
            this.$refs['addPatrol'].department_id = this.stateObj.department_id
            this.$refs['addPatrol'].mission_id=scope.id
            this.$refs['addPatrol'].isShow=true
            this.$refs['addPatrol'].type='add'
          },
          openAnswers(scope){
            this.$refs['answerQuestion'].mission_id=scope.id
            this.$refs['answerQuestion'].askList = scope.ask
            this.$refs['answerQuestion'].isShow=true
          },
          showPatrol(id, type) {
            this.$refs.showPatrol.id = id
            this.$refs.showPatrol.type = type
            this.$refs.showPatrol.isShow = true
          },
          openTrain(e){
            this.$refs.checkUnit.id = e.id
            this.$refs.checkUnit.type = 'train'
            this.$refs.checkUnit.isShow = true
          },
          openUploads(e){
            this.$refs.checkUnit.id = e.id
            this.$refs.checkUnit.type = 'uploads'
            this.$refs.checkUnit.isShow = true
          },
          openStudy(e){
            this.$refs.checkUnit.id = e.id
            this.$refs.checkUnit.type = 'study'
            this.$refs.checkUnit.isShow = true
          },

          // 新增编辑
          selectionChange(e){
            let arr = []
            if(e.length>0){
              for(var k of e){
                arr.push(k.id)
              }
            }else{
              arr = []
            }
            this.sectionList = arr
          },
          chooseEditorUnit(){
            if(this.sectionList.length>0){
              if(this.sectionList.length==1){
                this.editorUnit(this.sectionList[0],'editor')
              }else{
                this.$Message.warning('每次只能编辑一条任务');
              }
            }else{
              this.$Message.warning('请选择需要编辑的任务');
            }
          },

          editorUnit(id, type) {
            if(id){
              this.$refs.addUnit.id = id
            }
            this.$refs.addUnit.type = type
            this.$refs.addUnit.unitTypeList = this.unitTypeList
            this.$refs.addUnit.department_id = this.stateObj.department_id

            this.$refs.addUnit.isShow = true
          },
          // 审核 查看
          cellClicks(e){
            this.$refs.checkUnit.id = e.row.id
            this.$refs.checkUnit.type = 'show'
            this.$refs.checkUnit.isShow = true
          },
          checkUnits(id,type){
            this.$refs.checkUnit.id = id
            this.$refs.checkUnit.type = type
            this.$refs.checkUnit.isShow = true
          },
          changeDate(e){
            if(e){
              this.select.start_date = e[0];
              this.select.end_date = e[1];
            }else{
              this.select.start_date = "";
              this.select.end_date = "";
            }
          },
          spanMethod({
            row,
            colomn,
            rowIndex,
            columnIndex
          }) {
            return this.spanArr[rowIndex][columnIndex]
          },
          groupBy(arr, prop) {
            return arr.sort((a, b) => {
              if (a[prop] < b[prop]) {
                return 1;
              }
              if (a[prop] > b[prop]) {
                return -1;
              }
              return 0;
            });
          },

          async getList() {
            let res = await listunit({
              ...this.select
            })
            const allMonths = this.allMonths
            let monthObj = this.sortByMonth()

            //  判断小组中是否有人提交了检查
            //  处理参于人员选择
            for(var r of res.data){
              if(r.start_date){
                let dateArr = r.start_date.split("-")
                r.monthName = allMonths[parseInt(dateArr[1])-1]
                let _index = monthObj[r.monthName]<10?"0"+monthObj[r.monthName]:monthObj[r.monthName]
                r.monthIndex = parseInt(dateArr[0])+""+_index
              }


              var _names = []
              // 只有人员
              if(r.accept_admin_ids&&r.accept_admin_ids.length>0){
                r.accept_admin_detail.map(item=>{
                  let hasDetail = item.detail?true:false
                    _names.push({
                      'name':item.admin?.name,
                      'hasDetail':hasDetail
                    })
                })
                r._names = _names
              }
              // 部门
              if(r.accept_department_ids&&r.accept_department_ids.length>0){
                r.accept_department_detail.map(item=>{
                  let hasDetail = item.detail?true:false
                    _names.push({
                      'name':item.department?.name,
                      'hasDetail':hasDetail
                    })
                })
                r._names = _names
              }
              // 小组
              if(r.groups&&r.groups.length>0){
                let ab = contactGroup(r.groups)
                // ab.map(item=>{
                //   item.admin_details.map(a=>{
                //     r.grounp_admin_detail.map(g=>{
                //       if(a.name===g.admin.name){
                //         a.hasDetail = g.detail?true:false
                //       }
                //     })
                //   })
                //   item.dep_details.map(a=>{
                //     r.grounp_department_detail.map(g=>{
                //       if(a.name===g.department.name){
                //         a.hasDetail = g.detail?true:false
                //       }
                //     })
                //   })
                // })
                r._names = ab

                //   for(var g of r.groups){
                //     for(var de of g.details){
                //       if(g.type==1){
                //         let is_index = 0
                //         for(var a of r.grounp_admin_detail){
                //           if(de.name===a.admin?.name){
                //             if(a.detail){
                //               is_index++
                //             }
                //           }
                //         }
                //         de.hasDetail=is_index>0?true:false
                //       }
                //       if(g.type==2){
                //         let is_index = 0
                //         for(var dp of r.grounp_department_detail){
                //           if(de.name===dp.department.name){
                //             if(dp.detail){
                //               is_index++
                //             }
                //           }
                //         }
                //         de.hasDetail=is_index>0?true:false
                //       }
                //     }
                //   }
                //   // 处理过的groups
                // r.groups.map((item,index)=>{
                //   _names.push({
                //     group_name:item.name,
                //     details:item.details
                //   })
                // })
                // r._names = _names
              }
            }

            this.list = res.data
            let _arr = []
            let _arr2 = []
            _arr = this.filterBySelectedMonths(this.list,this.selectMonth)
            this.currentTableList = _arr
            _arr2 = _arr.filter(item=>item.audit_status===2)
            this.auditStatus2= _arr2



            this.total = res.total


          },
          handleCheckAllChange(val) {
              this.selectMonth = val ? this.allMonths : [];
              this.isIndeterminate = false;
              let _arr = []
              let _arr2 = []
              _arr = this.filterBySelectedMonths(this.list,this.selectMonth)
              this.currentTableList = _arr
              _arr2 = _arr.filter(item=>item.audit_status===2)
              this.auditStatus2= _arr2
            },
          changeMonth(e){
            let checkedCount = e.length;
            this.checkAll = checkedCount === this.allMonths.length;
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.allMonths.length;
            let _arr = []
            let _arr2 = []
            _arr = this.filterBySelectedMonths(this.list,this.selectMonth)
            this.currentTableList = _arr
            _arr2 = _arr.filter(item=>item.audit_status===2)
            this.auditStatus2= _arr2
          },
          filterBySelectedMonths(arr, selectMonth) {
              if (!selectMonth || selectMonth.length === 0) {
                  return arr;
              }

              // Ensure selectMonth is an array even if it's a single value
              if (!Array.isArray(selectMonth)) {
                  selectMonth = [selectMonth];
              }

              return arr.filter(obj => {
                  // Check if there's at least one common month between obj.month and selectMonth
                  // return obj.start_date.some(month => selectMonth.includes(month));
                  return selectMonth.some(selected => obj.monthName.includes(selected));
              });
          },
          sortByMonth(){
               const now = new Date();
               const currentMonth = now.getMonth(); // 获取当前月份（0-11，其中0代表一月）
               const allMonths = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
               const decemberAndPrevious = allMonths.slice(currentMonth);
               const monthArr = [...decemberAndPrevious, ...allMonths.slice(0, currentMonth)]
               const monthObj = {}
               monthArr.map((item,index)=>{
                 monthObj[item] = index
               })
               return monthObj
          },

        },
    }
</script>

<style scoped>
  .tablewrap{
    display:flex;
  }
  .tablemonth{
    width:10%;
    background: #fff;
    padding: 20px;
    margin-right:1%
  }
  .tablecontent{
    width:89%
  }
  ::v-deep .el-table .cell.el-tooltip {
    white-space: normal !important;
        width: 100% !important;
  }
  /deep/ .el-icon-circle-close {
    color: #fff
  }

  .expenditem {
    display: flex;
    font-size: 14px;
    padding: 10px;
    border-bottom: 1px solid #EBEEF5;
    padding-left: 110px;
    font-size: 16px;
  }

  .expenditem>div {
    margin-right: 15px;
    min-width: 200px;
  }

  .expenditem>div span.label {
    color: #97a8be
  }

  /deep/ .el-table__expanded-cell .expenditem:last-child {
    border-bottom: none;
  }

  /deep/ .ivu-page {
    text-align: right;
    padding: 15px;
  }
  /deep/ .el-range-editor.el-input__inner{
    height: 32px;
    line-height: 32px;
    width: 250px;
    margin-right:10px;
  }
  /deep/ .el-date-editor .el-range__icon,/deep/ .el-date-editor .el-range-separator,/deep/ .el-date-editor .el-range__close-icon{
    line-height: 25px;
  }
  /deep/ .height32 .el-input__inner{
    height:32px;
  }
  /deep/ .height32 .el-select__caret.el-input__icon.el-icon-arrow-up{
    line-height: 32px;
  }
  /deep/ .height32 .el-select__caret.el-input__icon.el-icon-circle-close{
    line-height: 32px;
  }
</style>
