<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;">
            <!-- <DatePicker style='width:200px;margin-right: 10px;' placeholder="年份" placement="bottom" format='yyyy'
              type="year" @on-change="changeYear"></DatePicker> -->
            <el-date-picker
                  class='height32'
                  type="month"
                  v-model="myMonth"
                  @change="changeMyMonth"
                  format="yyyy-MM"
                  value-format="MM"
                  style="width: 150px;margin-right: 10px;"
                  placeholder="选择月份">
                </el-date-picker>
            <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' v-if="path_type!=5" 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 v-if="showSelectMonth" @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> -->
            <el-select class='height32' style="width: 150px;margin-right: 10px;" filterable clearable
              v-model="select.main_department_id" placeholder="责任人(科室)">
              <el-option v-for="item in deptOptions" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>

            <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==4" type="primary" style="margin-right: 10px;"
              @click="editorUnit('','add',4)">添加</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="tablecontent" :style="{'width':showSelectMonth?'89%':'100%'}">
        <div class="topwrap">
          <div>
            共有<span style="font-size: 24px;color:red;margin:0 5px">{{list.length}}</span>项任务，
            待执行<span style="font-size: 24px;color:red;margin:0 5px">{{auditStatus4}}</span>项，
            执行中<span style="font-size: 24px;color:red;margin:0 5px">{{auditStatus1}}</span>项，
            完成<span style="font-size: 24px;color:red;margin:0 5px">{{auditStatus5}}</span>项
          </div>
        </div>
        <xy-table :showIndex="false" :list="list" :defaultExpandAll="false"
          :isPage="false"
         :treeProps="treeProps" :total="total" stripe @cell-dblclick='cellClicks'
          @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 v-if="!(scope.row.audit_status==3||scope.row.audit_status==5) && (scope.row.admin_id==stateObj.login_id )">
                    <Button style="margin-right:5px;margin-bottom:5px;" type="primary" size="small"
                      @click="editorUnit(scope.row.id,'editor')">编辑任务</Button>
                  </div>

                  <!-- <div v-if="scope.row.admin_id==stateObj.login_id || stateObj.is_chuzhang || stateObj.is_guiji)">
                      <Button style="margin-right:5px;margin-bottom:5px;" type="primary" size="small"
                        @click="editorUnit(scope.row.id,'editor')">编辑任务</Button>
                    <Button style='margin-right:5px;margin-bottom:5px;' size="small"
                      @click="backPlan(scope.row)">归档</Button>
                  </div> -->
                </template>
                <!-- 我的任务 -->
                <template v-else>
                  <!-- 任务是发给部门的，只有指定部门科长能看见，需要再次分发人员 -->
                  <!-- 转办就给 责任人 -->
                  <!-- 任务发给部门的科长，责任人，都能进行任务分解，任务转办，执行任务的操作 -->
                  <div v-if="scope.row.pid>0 && scope.row.notices.length==0 && !(scope.row.audit_status==3||scope.row.audit_status==5) || scope.row.type==4">
                    <Button style='margin-right:5px;margin-bottom:5px;' type="primary" size="small"
                      @click="sendNotice(scope.row)">督办提醒</Button>
                  </div>
                  <div>
                    <Button style='margin-right:5px;margin-bottom:5px;' type="primary" size="small"
                      @click="checkUnits(scope.row.id,'show')">查看任务</Button>
                  </div>
                </template>

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


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

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

<script>
  import addUnit from '../list/components/addUnit.vue'
  import addBackPlan from '../list/components/addBackPlan.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 sendNotice from '../list/components/sendNotice.vue'
  import {
    listunit,
    del,
    unDoTotal
  } from '@/api/task/unit.js'
  import {
    listdept
  } from "@/api/system/department.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,
      addBackPlan,
      showPatrol,
      addPatrol,
      checkUnit,
      answerQuestion,
      sendNotice
    },
    data() {
      return {
        type_name: '',
        path_type: 4,
        dialogVisible: false,
        stateObj: {},
        deptOptions:[],
        treeProps:{children: 'mychildren', hasChildren: 'hasChildren'},
        typeName: [{
          type: 1,
          name: '任务追踪'
        }, {
          type: 4,
          name: '专项专题任务'
        }, {
          type: 5,
          name: '我的待办任务'
        }],
        myMonth:'',
        isMyPage:true,
        select: {
          keyword: '',
          page: 1,
          page_size: 999,
          myself: 0,
          myself_department: 0,
          type: '',
          unit_type: '',
          audit_status: '',
          dueDate: [],
          start_date: '',
          end_date: '',
          // sort_name: 'start_date',
          // sort_type: 'ASC',
          year: new Date().getFullYear(),
          month: '',
          pid:'',
          main_department_id:''
        },
        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: 5,
          value: '已归档',
          type: 'success'
        }, {
          id: 3,
          value: '待归档',
          type: 'danger'
        }],
        auditStatusList: [{
          id: 4,
          value: '待办',
          type: 'info'
        }, {
          id: 1,
          value: '办理中',
          type: ''
        }, {
          id: 5,
          value: '已归档',
          type: 'success'
        }, {
          id: 3,
          value: '待归档',
          type: 'danger'
        }],
        unitTypeList: [],
        askList: [],
        myListFinishStatus:true,
        list: [],
        myListFinish:[],
        sectionList: [],
        currentTableList: [],
        auditStatus1: 0, // 办理中
        auditStatus4: 0, // 待办
        auditStatus5: 0, //已完成
        isIndeterminate: true,
        checkAll: false,
        showSelectMonth:false,
        selectMonth: [],
        allMonths: [{
          id: "01",
          value: '一月'
        }, {
          id: "02",
          value: '二月'
        }, {
          id: "03",
          value: '三月'
        }, {
          id: "04",
          value: '四月'
        }, {
          id: "05",
          value: '五月'
        }, {
          id: "06",
          value: '六月'
        }, {
          id: "07",
          value: '七月'
        }, {
          id: "08",
          value: '八月'
        }, {
          id: "09",
          value: '九月'
        }, {
          id: "10",
          value: '十月'
        }, {
          id: "11",
          value: '十一月'
        }, {
          id: "12",
          value: '十二月'
        }],
        table: [
          {
          label: "",
          prop: 'pindex',
          // fixed:'left',
          width:80
        },
        {
          label: "任务名称",
          prop: 'name',
          width: 200,
          // fixed:'left',
          align: 'left',
        }, {
          label: "任务内容及要求",
          prop: 'content',
          minWidth: 200,
          align: 'left',
        }, {
          label: "任务类型",
          prop: 'unit_type_detail.value',
          width: 120,
          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> {
        // 有转办人，转办人不显示 已转办 任务为结束。
       //  row.do_admin_ids.length>0 && !row.do_admin_ids.includes(this.stateObj.login_id) && !(row.audit_status==3||row.audit_status==5)?
        // <el-tag type ='info'>已转办</el-tag>
       //  :
            this.auditStatusList.map(item => {
                if (item.id == row.audit_status) {
                  return ( <el-tag type = {
                      item.type
                    }> {
                      item.value
                    } </el-tag>)
                  }
                })
            } </div>)
          }
        }, {
          label: "责任人(科室)",
          prop: 'main_admin.name',
          width: 120,
          align: 'center',
        }],
      }
    },
        computed: {
        },
        created() {
          this.getLeads()
          this.loadDeptOptions()
          this.stateObj = state.state
          let currentMonth = (new Date()).getMonth() + 1 < 10 ? "0" + ((new Date()).getMonth() + 1) : (new Date())
            .getMonth() + 1
          // this.selectMonth.push(currentMonth)
          // this.selectMonth.push(currentMonth)
          // this.select.month = currentMonth
          if (this.$route.path) {
            let path = this.$route.path.split("_")
            this.select.type = path[1]
            this.path_type = path[1]
            if (path[1] == 5) {
              this.showSelectMonth = false
              this.select.type = ''
              this.select.myself = 1
              // this.select.pid = 0
              // if(!this.stateObj.is_manger){
              this.isMyPage = false
              this.select.page_size = 999
              this.select.pid = ''
              // this.treeProps = {children: 'mychildren', hasChildren: 'hasChildren' }
              // }
              this.type_name = '我的待办任务'
              this.path_type = path[1]
              this.select.month = ''
              this.table.splice(this.table.length-1,1)

            }
            if (path[1] == 4) {
              this.selectMonth = []
              // this.allMonths.map(item=>{
              //   this.selectMonth.push(item.id)
              // })
              // this.select.month = this.selectMonth.join(',')
              this.select.type = 4
              this.type_name = '专项专题任务'
              this.path_type = path[1]
              this.table.splice(1,0,{
                label: "任务类别",
                prop: 'mission_type',
                width: 120,
                align: 'center'
              })
              // this.table.unshift({
              //   label: "任务类别",
              //   prop: 'mission_type',
              //   width: 120,
              //   align: 'left'
              // })
            }
            if (path[1] == 1) {
              this.showSelectMonth = false
              this.select.type = ''
              // this.select.pid = ''
              // this.treeProps = {children: 'nochildren', hasChildren: 'hasChildren' }
              this.type_name = '任务跟踪'
              this.path_type = path[1]
            }
          }
          this.getUnitTypeList()
          this.getUnDoTotal()
          this.getList()

        },
        watch: {},
        methods: {
          loadDeptOptions() {
            listdept().
            then((res) => {
              this.deptOptions = res;
            }).catch(error => {
              console.log(error)
              reject(error)
            })
          },
          changeYear(e) {
            if (e) {
              this.select.year = e
            }
          },
          changeMyMonth(e){
            console.log(e)
            if(e){
              this.select.month = e
              // this.select.month = e.join(",")
            }else{
              this.select.month = ''
            }
          },
          async getLeads() {
            // await this.$store.dispatch("user/getLeads")
          },
          sendNotice(row){
            this.$refs.sendNotice.setForm(row)
            this.$refs.sendNotice.isShow = true
          },
          backPlan(row) {
            this.$refs.addBackPlan.upload_link = row.files
            this.$refs.addBackPlan.setTitle(row.name, row.id, row.level)
            // this.other_file_id  = id
            // this.other_file_status = status
            this.$refs.addBackPlan.isShow = 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 '资料收集':
              case '方案':
              case '会议':
                this.openUploads(e)
                break;
              // case '方案':
              //   this.openCases(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
          },
          openCases(e) {
            this.$refs.checkUnit.id = e.id
            this.$refs.checkUnit.type = 'cases'
            this.$refs.checkUnit.isShow = true
          },
          openStudy(e) {
            this.$refs.checkUnit.id = e.id
            this.$refs.checkUnit.type = 'study'
            this.$refs.checkUnit.isShow = true
          },
          editorUnit(id, type , formtype) {
            if (id) {
              this.$refs.addUnit.id = id
            }
            if(formtype){
              this.$refs.addUnit.setType(4)
              this.$refs.addUnit.setMainId(this.stateObj.department_id,this.stateObj.login_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.url_type = this.path_type
            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.url_type = this.path_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 = "";
            }
          },
          // 获取未完成的任务数量
          getUnDoTotal(){
            unDoTotal({
              ...this.select,
              audit_status:1
            }).then(res=>{
              // this.auditStatus1 = res.total
            })
          },
          async getList() {
            let res = await listunit({
              ...this.select
            })
            // 我的任务中 选择accept_department_ids部门的，只有选择到的科室负责人能看到 is_manger = true
            //  且具体执行人为空
            //  责任人看到所有
            let spliceIndex = []
            let _arr = []
            res.data.map((r,index)=>{
              console.log("r.rowKey",r.rowKey)
              let doAdmins = r.do_admin_ids ? r.do_admin_ids : []
              if(this.path_type == 5 && r.accept_department_ids.length > 0){
                console.log("id",r.id)
                let isDepartment = r.accept_department_ids.indexOf(this.stateObj.department_id)!=-1 ? true : false
                let isDomains = doAdmins.indexOf(this.stateObj.login_id)!=-1 ? true : false
                let isMainId = r.main_admin_id==this.stateObj.login_id?true:false
                if(!isMainId){
                  if(doAdmins.length==0){
                    if(!(isDepartment && this.stateObj.is_manger)){
                      spliceIndex.push(index)
                    }
                  }else{
                    if(!((isDepartment && this.stateObj.is_manger)||isDomains)){
                      spliceIndex.push(index)
                    }
                  }
                }
              }
            })
          let my_arr = [] // 接收我的任务中我已完成的  还要去除 参与人已经完成掉的
          let my_no_arr = [] // 接收我的任务中未完成的
            if(this.path_type == 5){
              const newArr = res.data.filter((_, index) => !spliceIndex.includes(index));
              newArr.map(item=>{
                // 已归档 或已完成
                if(item.audit_status==5 || item.audit_status==3 ){
                  console.log("item.mission_finished",item.id,item.mission_finished)
                  my_arr.push(item)
                }else{
                  // 参与对象中 我提交已审核的 keep_status = 2
                  // item.mission_distribute.map(md=>{
                  //   if(md.accept_admin_id===this.stateObj.login_id && md.keep_status ==2){
                  //     my_arr.push(item)
                  //   }else{
                  //     my_no_arr.push(item)
                  //   }
                  // })
                   my_no_arr.push(item)

                }
              })
              _arr = this.buildTree(my_no_arr)
              my_arr = this.buildTree(my_arr)
            }else{
              _arr = this.buildTree(res.data)
            }
            _arr.map((r,index)=>{
              r.pindex = index+1
            })
            my_arr.map((r,index)=>{
              r.pindex = index+1
            })
            this.list = _arr
            this.myListFinish = my_arr
            let auditStatus1 = this.list.filter(item=>item.audit_status===1)
            let auditStatus4 = this.list.filter(item=>item.audit_status===4)
            let auditStatus5 = this.list.filter(item=>item.audit_status===5)
            // this.list.map(item=>{
            //   if(item.audit_status===1){
            //     auditStatus1++
            //   }
            // })
            this.auditStatus1 = auditStatus1.length
            this.auditStatus4 = auditStatus4.length
            this.auditStatus5 = auditStatus5.length
            console.log("spliceIndex",this.list)


            this.total = res.total

          },

          buildTree(items) {
            const tree = [];
            const map = {};

            items.forEach(item => {
              map[item.id] = item;
            });

            items.forEach(item => {
              const parent = map[item.pid];
              if (parent) {
                (parent.mychildren || (parent.mychildren = [])).push(item);
              } else {
                tree.push(item);
              }
            });

            return tree;
          },
          handleCheckAllChange(val) {
            if (val) {
              let _sm = []
              this.allMonths.map(item => {
                _sm.push(item.id)
              })
              this.selectMonth = _sm
              this.select.month = this.selectMonth.join(',')
              this.getUnDoTotal()
              this.getList()

            } else {
              this.selectMonth = []
              this.select.month = ''
            }
            this.isIndeterminate = false;
          },
          changeMonth(e) {
            let checkedCount = e.length;
            this.checkAll = checkedCount === this.allMonths.length;
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.allMonths.length;
            console.log("this.selectMonth", this.selectMonth)
            this.select.month = this.selectMonth.join(",")
            this.getUnDoTotal()
            this.getList()
          },

        },
      }
</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/ .height32 .el-input__icon.el-icon-date{
    line-height: 32px;
  }
  /deep/ .height32.el-date-editor--month .el-input__icon{
    line-height: 32px;
  }
  /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;
  }
  .topwrap{
	  display: flex;
	  align-items: center;
	  justify-content: space-between;
  }
  .myListFinish {
    display: flex;
    align-items: center;
	margin:15px 0;
  }

  .myListFinish>div {
    padding: 10px 20px;
    font-size: 16px;
    background-color: #fff;
    color: #333;
	cursor: pointer;
  }

  .myListFinish>div:first-child {
    border-radius: 10px 0 0 10px;

  }

  .myListFinish>div:last-child {
    border-radius: 0 10px 10px 0;

  }

  .myListFinish>div.tabcur {
    background: #0077CC;
    color: #fff
  }

</style>
