<template>
  <div style="padding: 0 20px">
    <div ref="lxHeader">
      <lx-header icon="md-apps" text="问题管理" style="margin-bottom: 10px; border: 0px; margin-top: 15px">
        <slot>
          <div style="display: flex;justify-content: flex-start;flex-wrap: wrap;">
            <DatePicker style='width:200px;margin-right: 10px;' placeholder="年份" placement="bottom" format='yyyy'
              type="year" @on-change="changeYear"></DatePicker>
            <Select filterable clearable style='width:150px;margin-right: 10px;' v-model="select.status" placeholder="检查状态">
              <Option v-for="item in statusList" :value="item.id">{{item.value}}</Option>
            </Select>
           <Select filterable clearable style='width:150px;margin-right: 10px;' v-model="select.mission_id" placeholder="问题来源">
              <Option v-for="item in missionList" :value="item.id">{{item.name}}</Option>
            </Select>
            <Select filterable clearable style='width:150px;margin-right: 10px;' v-model="select.ask_id" placeholder="问题类型">
              <Option v-for="item in askList" :value="item.id">{{item.value}}</Option>
            </Select>
            <Select filterable clearable style='width:150px;margin-right: 10px;' v-model="select.accept_department_ids" placeholder="责任部门">
              <Option v-for="item in depList" :value="item.id">{{item.name}}</Option>
            </Select>
            <el-cascader :show-all-levels="false" class="height32" v-model="siteName" clearable :options="siteList" :props="{'label':'name','value':'id'}"
              placeholder="请选择检查地点" style="width: 150px;margin-right: 10px;" @change="changeSite"></el-cascader>
            <Input v-model="select.keyword" clearable style="width: 150px;margin-right: 10px;" placeholder="关键字搜索" />

            <Button type="primary" @click="select.page=1,getList()">查询</Button>
            <Button type="primary" style="margin-left: 10px;" @click="editorPatrol('','add')">添加</Button>
            <!-- <Button type="primary" style='margin-left:10px;' @click="chooseEditorPatrol()">编辑</Button> -->

            <Button type="primary"  style="margin-left: 10px;" @click="importTable(new Date().getTime().toString())">导出</Button>

            <!-- <Poptip v-if='is_guiji||is_chuzhang' transfer confirm title="确认要删除吗？" @on-ok="deleteList">
              <Button type="primary" style="margin-left:10px;" ghost>删除</Button>
            </Poptip> -->
          </div>
        </slot>
      </lx-header>
    </div>
      <!-- @cell-click="cellClicks" -->
    <div class="tablewrap">
      <!-- <div class="tablemonth">
        <el-checkbox v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;"></div>
        <el-tree
          ref="missiontree"
          :props="{
            label: 'name',
            children: 'pid_details'
          }"
          :data="missionList"
          show-checkbox
          node-key="id"
          :default-checked-keys="selectMission"
          @check-change="changeMonth">
        </el-tree>
      </div> -->

      <div class="tablecontent">
        <xy-table
          :list="list"
          :total="total"
          stripe
          :showIndex='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' label="操作" fixed="right" width="80" header-align="center">
              <template slot-scope="scope">
                <div v-if="(is_guiji||is_chuzhang||scope.row.is_myself)&&!(scope.row.status==5||scope.row.status==6)">
                  <Button  type="primary" style='margin-right:5px;margin-bottom:5px;' size="small" @click="showPatrol(scope.row.id,'show')">办理</Button>
                </div>
                <div v-else>
                  <Button size="small" style='margin-right:5px;margin-bottom:5px;' @click="showPatrol(scope.row.id,'show')">查看</Button>

                </div>
                <!-- <Button type="primary" style='margin-right:5px;margin-bottom:5px;' size="small" @click="showPatrol(scope.row.id,'show')">查看</Button> -->
                <!-- <Button v-if="scope.row.status==1&&((scope.row.check_leader==1&&is_leader&&scope.row.leader_status===null)||(scope.row.check_main==1&&is_main_leader&&scope.row.main_status===null))" type="primary" style='margin-right:5px;margin-bottom:5px;' size="small" @click="showPatrol(scope.row.id,'leader')">确认</Button> -->
                <!-- <Button v-if="scope.row.status==9&&((scope.row.re_check_leader==1&&is_leader&&scope.row.re_leader_status===null)||(scope.row.re_check_main==1&&is_main_leader&&scope.row.re_main_status===null))" type="primary" style='margin-right:5px;margin-bottom:5px;' size="small" @click="showPatrol(scope.row.id,'leaderconfirm')">审核</Button> -->
                <div v-if='is_guiji||is_chuzhang||login_id==scope.row.admin_id'>
                  <Button type="primary" style='margin-right:5px;margin-bottom:5px;' size='small' @click="editorPatrol(scope.row.id,'editor')">编辑</Button>
                </div>
                <div  v-if='is_guiji||is_chuzhang'>
                  <Poptip transfer confirm title="确认要删除吗？" @on-ok="deleteList(scope.row.id)">
                    <Button type="primary" style='margin-right:5px;margin-bottom:5px;' size='small' ghost>删除</Button>
                  </Poptip>
                </div>

              </template>
            </el-table-column>
          </template>

          </xy-table>
      </div>
    </div>




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

<script>
  import addPatrol from '../list/components/addPatrol.vue'
  import showPatrol from '../list/components/showPatrol.vue'
  import {
    listpatrol,del,leads
  } from '@/api/task/patrol.js'
  import {getInfo} from "@/api/user.js";
  import {
    getparameteritem
  } from "@/api/system/dictionary.js";
  import {listunit} from '@/api/task/unit.js'
  import {
    listaddress
  } from '@/api/address'
  import {
    listdept
  } from "@/api/system/department.js"
  import * as XLSX from "xlsx";
  import {
    saveAs
  } from "file-saver";
  import state from '@/store/modules/user.js'
  import {
    getMergeCells,
    groupBy
  } from '@/utils/contactTable.js'
  export default{
    components:{
      addPatrol,
      showPatrol
    },
    data(){
      return{
        year:(new Date()).getFullYear(),
        missionList:[],
        depList:[],
        askList:[],
        siteList: [],
        siteListArr:[],
        siteName:'',
        select:{
          keyword:'',
          page:1,
          page_size:10,
          status:'',
          myself:0,
          mission_id:'',
          site_id:'',
          accept_department_ids:'',
          ask_id:'',
          sort_name:'date',
          sort_type:"DESC",
          // pid:0
          // myself_update:0
        },
        sectionList:[],
        total:0,
        statusLabel:[
        //   {
        //   id:-1,
        //   value:'已撤回'
        // },
        {
          id:0,
          value:'整改中',
          type:''
        },{
          id:1,
          value:'整改中',
          type:''
        },{
          id:2,
          value:'待接收',
          type:'danger'
        },{
          id:3,
          value:'整改中',
          type:''
        },{
          id:4,
          value:'整改中',
          type:''
        },{
          id:5,
          value:'已整改',
          type:'success'
        },{
          id:6,
          value:'退回',
          type:'info'
        },{
          id:7,
          value:'整改中',
          type:''
        },{
          id:8,
          value:'整改中',
          type:''
        },{
          id:9,
          value:'整改中',
          type:''
        }],
        statusList:[
          {
            id:2,
            value:'待接收'
          },{
            id:'0,1,2,3,4,7,8,9',
            value:'整改中'
          },{
            id:5,
            value:'已整改'
          },{
            id:6,
            value:'退回'
          }
        ],
        currentTableList:[],
        isIndeterminate:true,
        checkAll:false,
        selectMission:[],
        table:[{
          label:"问题描述",
          prop:'ask_introduce',
          align:'left'
        },{
          label:"问题类型",
          prop:'ask.value',
          width:80,
        },{
          label:"问题来源",
          prop:'missionName',
          // width:180,
          align:'left',
          width:240,
        },{
          label:"发现日期",
          prop:'date',
          width:110,
        },{
          label:"责任科室",
          prop:'ask_department',
          width:200,
          align:'center',
          customFn: (row) => {

            return(<div style={
              {
                'display':'flex',
                'flex-wrap':'wrap',
                "justify-content": "center"
              }
            }>
              {
                row.accept_department_ids_details&&row.accept_department_ids_details.length>0?
                row.accept_department_ids_details.map(item=>{
                      return(<el-tag style={{'margin':'3px'}}>{item.name}</el-tag>)
                  })
                :(row.accept_admin_ids_details&&row.accept_admin_ids_details.length>0?

                row.accept_admin_ids_details.map(item=>{
                      return (<el-tag style={{'margin':'3px'}}>{item.name}</el-tag>)
                })
                :row.ask_department)
              }

            </div>)
          }
        },{
          label:"上报人",
          prop:'up_admin.name',
          width:100,
        }],
        list:[],

        // 权限判断
        leads_list:{},

        login_id:'',
        department_id:'',
        is_leader:false,
        is_main_leader:false,
        is_guiji:false,
        is_chuzhang:false,
        // is_my_inspection:false
        // 导出
        importtable:[{
          label:"任务名称",
          prop:'mission_name',
        },{
          label:"发现时间",
          prop:'date',
        },{
          label:"检查站点/地点",
          prop:'site_name',

        },{
          label:"问题描述",
          prop:'ask_introduce',
        },{
          label:"问题类型",
          prop:'ask_value',
        },{
          label:"整改意见",
          prop:'tips',
        },{
          label:"责任科室",
          prop:'department_names',
        },{
          label:"计划整改日期",
          prop:'plan_end_date',
        },{
          label:"整改情况",
          prop:'fix_status_name',
        },{
          label:"完成日期",
          prop:'fix_end_date',
        },{
          label:"上报人",
          prop:'up_admin_name',
        }],
      }
    },
    // computed: {
    //   // 获取所有单元格合并数据
    //   spanArr() {
    //     for(var k in this.list){
    //       if (!this.list.length) return []
    //       const mergeCols = ['missionName'] // 需要合并的列（字段）
    //       // const data = groupBy(this.list, 'monthIndex')
    //       // console.log("data",data)
    //       return getMergeCells(this.list, this.table, mergeCols)
    //     }
    //   }
    // },
    created(){

      // this.getUserId()
      this.getLeads()
      this.getList()
      this.init()
      // this.$nextTick(() => {
      //   this.getMissonList()
      // });
    },
    methods: {
      init(){
        this.getMissonList()
        this.getDep()
        this.getAddress()
        this.getAsk()
      },
      changeYear(e){
        if(e){
          this.year = e
          this.getMissonList()
        }
      },
      selectionChange(e){
        console.log(e)
        let arr = []
        if(e.length>0){
          for(var k of e){
            arr.push(k)
          }
        }else{
          arr = []
        }
        this.sectionList = arr
      },
      // async getUserId(){
      //    const res = await getInfo()
      //    this.login_id = res.id
      //    this.department_id = res.department_id
      //    this.getList()
      //    this.getLeads()
      //    this.getDep()
      // },
      async getLeads(){
        // await this.$store.dispatch("user/getLeads")
         let obj = state.state
         console.log("obj",obj)
         this.login_id = obj.login_id
         this.department_id = obj.department_id
         this.leads_list = obj.leads_list
         this.is_guiji = obj.is_guiji
         this.is_chuzhang = obj.is_chuzhang
         this.is_leader = obj.is_leader
         this.is_main_leader = obj.is_main_leader
         // const res = await leads()
         // console.log("this.login_id",this.login_id)
         // this.leads_list = res
         // // 登陆人是否是规计科
         // for(var g of res.guiji){
         //   if(this.login_id==g.id){
         //     this.is_guiji = true
         //   }
         // }
         // // 登陆人是否是处长室
         // for(var c of res.chuzhang){
         //   if(this.login_id==c.id){
         //     this.is_chuzhang = true
         //   }
         // }
         // // 是否分管领导
         // if(this.login_id==res.guiji_leader.id){
         //   this.is_leader = true
         // }
         // // 是否处长
         // if(this.login_id==res.chuzhang_leader.id){
         //   this.is_main_leader = true
         // }

      },
      spanMethod({
        row,
        colomn,
        rowIndex,
        columnIndex
      }) {
        return this.spanArr[rowIndex][columnIndex]
      },
      async getList(){
         const res = await listpatrol({...this.select})
         for(var k of res.data){
           k.missionName = k.mission?k.mission.name:'日常巡查'
           console.log("k.missionName",k.missionName)
           k.is_myself = false
           if(k.status==2||k.status==3||k.status==4||k.status==7){
             if(k.accept_admin_ids&&k.accept_admin_ids.length>0){
               for(var a of k.accept_admin_ids){
                 if(this.login_id==a){
                   k.is_myself = true
                 }
               }
             }
             if(k.accept_department_ids&&k.accept_department_ids.length>0){
               for(var d of k.accept_department_ids){
                 if(this.department_id==d){
                   k.is_myself = true
                 }
               }
             }
           }
         }
         this.list = res.data
         // this.currentTableList = this.filterBySelectedMonths(this.list,this.selectMission)
         // console.log("currentTableList",this.currentTableList)
         this.total = res.total
      },
      handleCheckAllChange() {
        // let _checkAll = this.checkAll ? false : true
        // console.log("_checkAll",_checkAll)
        // this.checkAll = _checkAll
        console.log("this.checkAll",this.checkAll)
        this.select.page=1
        if(this.checkAll){
          let _sm = []
          this.missionList.map(item=>{
            _sm.push(item.id)
            if(item.pid_details_count>0){
              item.pid_details.map(p=>{
                _sm.push(p.id)
              })
            }
          })
          this.selectMission = _sm
          this.select.mission_id = ''
          this.$refs.missiontree.setCheckedKeys(_sm);
          this.getList()
        }else{
          this.selectMission = []
          this.select.mission_id = ''
          this.$refs.missiontree.setCheckedKeys([]);
          this.getList()
        }

        this.isIndeterminate = true;
          // let _arr = []
          // _arr = this.filterBySelectedMonths(this.list,this.selectMission)
          // this.currentTableList = _arr
        },
      changeMonth(data, checked, indeterminate){
        console.log(data, checked, indeterminate);
        // if(!this.checkAll){
          if(checked){
            if(this.selectMission.indexOf(data.id)==-1){
              this.selectMission.push(data.id)
            }
          }else{
            this.selectMission.map((item,index)=>{
              if(item===data.id){
                this.selectMission.splice(index,1)
              }
            })
          }
          this.select.mission_id = this.selectMission.join(',')
                  this.select.page=1
          this.getList()


        console.log("this.selectMission",this.selectMission)
      },
      filterBySelectedMonths(arr, selectMission) {
          if (!selectMission || selectMission.length === 0) {
              return arr;
          }

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

          return arr.filter(obj => {
              // Check if there's at least one common month between obj.month and selectMission
              return selectMission.some(selected => obj.missionName.includes(selected));
          });
      },
      async getMissonList(){
        console.log("this.unitTypeList",this.unitTypeList)
        const res = await getparameteritem('unitTypeList')
        for(var k of res.detail){
          if(k.remark=='检查'){
            const res1 = await listunit({
              page:1,
              page_size:999,
              unit_type:k.id,
              year:this.year,
              pid:''
            })

            this.missionList = res1.data
            this.missionList.unshift({
              id:0,
              name:'日常巡查'
            })
          }
        }
      },
      getDep(){
          listdept().
          then((res) => {
            this.depList = res;
          }).catch(error => {
            console.log(error)
            reject(error)
          })
      },
      getAddress() {
        listaddress({
          page: 1,
          page_size: 9999
        }).then(res=>{
          this.siteListArr = res.data
          let arr = this.contactSite(res.data)
          this.siteList = arr
        })

      },
      changeSite(e){
        if(e){
          this.select.site_id = e[1]
        }
      },
      contactSite(arr) {
        let tempArr = [],
          newArr = []
        for (let i = 0; i < arr.length; i++) {
          if (tempArr.indexOf(arr[i].type) === -1) {
            newArr.push({
              type: arr[i].type,
              name: arr[i]['type_detail']['value'],
              children: [arr[i]]
            })
            tempArr.push(arr[i].type);
          } else {
            for (let j = 0; j < newArr.length; j++) {
              if (newArr[j].type == arr[i].type) {
                newArr[j].children.push(arr[i])
              }
            }
          }
        }
        return newArr
      },
      async getAsk(label) {
        const res = await getparameteritem('askList')
        this.askList = res.detail
      },
      chooseEditorPatrol(){
        if(this.sectionList.length>0){
          if(this.sectionList.length==1){
            if((this.is_guiji||this.is_chuzhang||this.login_id==this.sectionList[0].admin_id)){
              this.editorPatrol(this.sectionList[0].id,'editor')
            }else{
              this.$Message.warning('没有权限编辑该检查');
              return
            }
            // if(!(this.sectionList[0].status==0)){
            //   this.$Message.warning('该检查不可编辑');
            //   return
            // }
            // this.editorPatrol(this.sectionList[0].id,'editor')
          }else{
            this.$Message.warning('每次只能编辑一件检查');
          }
        }else{
          this.$Message.warning('请选择需要编辑的检查');
        }
      },
      editorPatrol(id,type){
        if(type=='editor'){
          this.$refs.addPatrol.id= id
           this.$refs.addPatrol.mission_id = id
        }
        if(type=='add'){
          this.$refs.addPatrol.mission_id = 0
        }
        this.$refs.addPatrol.type= type
        this.$refs.addPatrol.department_id = this.department_id
        this.$refs.addPatrol.login_id=this.login_id
        this.$refs.addPatrol.isShow=true
      },
      cellClicks(e){
        this.$refs.showPatrol.id= e.row.id

        // this.$refs.showPatrol.id= id
        // this.$refs.showPatrol.type= type
        this.$refs.showPatrol.is_leader=this.is_leader
        this.$refs.showPatrol.is_main_leader=this.is_main_leader
        this.$refs.showPatrol.is_guiji=this.is_guiji
        this.$refs.showPatrol.is_chuzhang=this.is_chuzhang
        this.$refs.showPatrol.login_id=this.login_id
        this.$refs.showPatrol.department_id=this.department_id
        this.$refs.showPatrol.isShow = true
      },
      showPatrol(id,type){
        this.$refs.showPatrol.id= id
        this.$refs.showPatrol.type= type
        this.$refs.showPatrol.is_leader=this.is_leader
        this.$refs.showPatrol.is_main_leader=this.is_main_leader
        this.$refs.showPatrol.is_guiji=this.is_guiji
        this.$refs.showPatrol.is_chuzhang=this.is_chuzhang
        this.$refs.showPatrol.login_id=this.login_id
        this.$refs.showPatrol.department_id=this.department_id
        this.$refs.showPatrol.isShow = true
      },
      async importTable(sheetName) {
        const res = await listpatrol(Object.assign(this.select, {
          page: 1,
          page_size: 99999
        }))
        if (res.data) {
          let headers = this.importtable.map(i => {
            return {
              key: i.prop,
              title: i.label
            }
          })
          for(var k of res.data){
            k.mission_name = k.mission?k.mission.name:''
            k.site_name = k.site?k.site.name:k.address
            k.ask_value = k.ask?k.ask.value:''
            k.up_admin_name  = k.up_admin?k.up_admin.name:''
            if(k.accept_department_ids_details&&k.accept_department_ids_details.length>0){
              let arr = []
              k.accept_department_ids_details.map(item=>{
                  arr.push(item.name)
              })
              k.department_names = arr.join(',')
            }else if(k.accept_admin_ids_details&&k.accept_admin_ids_details.length>0){
              let arr = []
              k.accept_admin_ids_details.map(item=>{
                  arr.push(item.name)
              })
              k.department_names = arr.join(',')
            }else{
              k.department_names = k.ask_department
            }
            if(k.fix_status===null){
              this.statusLabel.map(s=>{
                  if(s.id==k.status){
                    k.fix_status_name = s.value
                  }
              })
              // for(var s of this.statusLabel){
              //   if(item.id==k.status){
              //     k.fix_status_name = item.value
              //   }
              // }
            }else{
              k.fix_status_name = k.fix_status==1?'已完成':'已列计划'
            }

          }
          const data = res.data.map(row => headers.map(header => row[header.key]));
          data.unshift(headers.map(header => header.title));
          const wb = XLSX.utils.book_new();
          const ws = XLSX.utils.aoa_to_sheet(data);
          XLSX.utils.book_append_sheet(wb, ws, sheetName);
          const wbout = XLSX.write(wb, {
            bookType: 'xlsx',
            bookSST: true,
            type: 'array'
          });
          saveAs(new Blob([wbout], {
            type: 'application/octet-stream'
          }), `检查问题${sheetName}.xlsx`);
        }
      },

      deleteList(id){
        var that = this;
        del(id).then(response => {
          this.$Message.success('操作成功');
          that.getList();
        }).catch(error => {
          console.log(error)
          reject(error)
        })
        // if (this.sectionList.length>0) {
        //   let arr = []
        //   this.sectionList.map(item=>{
        //     arr.push(item.id)
        //   })
        //   del(arr.join(',')).then(response => {
        //     this.$Message.success('操作成功');
        //     that.getList();
        //   }).catch(error => {
        //     console.log(error)
        //     reject(error)
        //   })
        // }else{
        //   this.$Message.warning('请选择要删除的数据');
        // }
      }
    },
    watch:{}
  }
</script>

<style scoped>
  .tablewrap{
    display:flex;
  }
  .tablemonth{
    width:15%;
    background: #fff;
    padding: 20px;
    margin-right:1%;
  }
  .tablecontent{
    width:100%
  }
  /deep/ .el-tree-node{
    white-space: normal;
  }
  /deep/ .el-tree-node__content{
        height: auto;
        align-items: start;
  }
  /deep/ .el-table .cell.el-tooltip{
    white-space: normal;
  }
  /deep/ .tablemonth .el-checkbox{
    /* width:100%; */
        padding: 4px 0;
  }
  /deep/ .tablemonth .el-checkbox__input{
    vertical-align: top!important;
  }
  /deep/ .tablemonth .el-checkbox__label {
    text-wrap:wrap;
  }
  /deep/ .el-tree-node__label{
    /* text-wrap:wrap; */
  }
   /deep/ .v-table .el-table__body .missionName>div{
     /* white */
     /* vertical-align: top!important; */
   }
  /deep/ .el-icon-circle-close{
      color:#fff
  }
  /deep/ .height32 .el-input__inner{
        height: 32px;
        vertical-align: top;
  }
  /deep/  .height32 .el-input__suffix{
        height: 32px;
        top: -4px;
        color:#808695
  }
  /deep/ .height32 .is-reverse{
    line-height: 32px;
  }
/*  /deep/ .el-table__body tr.el-table__row--striped td {
    background-color: #C0C4CC!important;
  } */
</style>
