<template>
<div>
    <xy-dialog ref="dialog" :is-show.sync="isShow" type="form" title="查看" :form="form"
      >
      <template v-slot:contents>
        <el-divider>计划信息</el-divider>
         <el-descriptions class="margin-top" :column="4" border>
           <el-descriptions-item span="2">
             <template slot="label">
               计划名称：
             </template>
             {{showform.name?showform.name:''}}
           </el-descriptions-item>
           <el-descriptions-item span="2">
             <template slot="label">
               计划年份：
             </template>
             {{showform.year?showform.year:''}}
           </el-descriptions-item>
           <el-descriptions-item span="2">
             <template slot="label">
               计划类型：
             </template>
              <span v-for="(item,index) in showform.type_detail">
                <span v-if="index===showform.type_detail.length-1">{{item.value}}</span>
                <span v-else>
                  {{item.value}}、
                </span>

              </span>
             <!-- {{showform.type_detail?showform.type_detail.value:''}} -->
           </el-descriptions-item>

           <el-descriptions-item span="2">
             <template slot="label">
               月份：
             </template>
             {{showform.start_date?showform.start_date.join("、"):''}}
           </el-descriptions-item>
          <!-- <el-descriptions-item span="2">
             <template slot="label">
               计划状态：
             </template>
             <div v-for="item in statusList">
               <span v-if="showform.status==item.id">
                 {{item.value}}
               </span>
             </div>
           </el-descriptions-item> -->
           <!-- <el-descriptions-item span="2">
             <template slot="label">
               结束日期：
             </template>
             {{showform.end_date?showform.end_date:''}}
           </el-descriptions-item> -->
           <el-descriptions-item span='4'>
             <template slot="label">
               附件：
             </template>
             <div v-for="item in pictureList">
               <a target="_blank" :href="item.url">{{item.name}}</a>
             </div>
           </el-descriptions-item>
           <el-descriptions-item span='4'>
             <template slot="label">
               参与对象：
             </template>
             <div v-if="showform.accept_admin&&showform.accept_admin.length>0">
               <el-tag style='margin-right:10px' v-for='item in showform.accept_admin'>
                 {{item.name}}
               </el-tag>
             </div>
             <div v-if="showform.accept_department&&showform.accept_department.length>0">
               <el-tag style='margin-right:10px' v-for='item in showform.accept_department'>
                 {{item.name}}
               </el-tag>
             </div>
             <div v-if="showform.groups&&showform.groups.length>0">
               <div v-for="group in showform.group_details">
                 {{group.name}}:
                     <el-tag v-for="detail in group.admin_details"
                       style="margin-right: 5px;margin-bottom: 2px;">{{detail.name}}</el-tag>
                     <el-tag v-for="detail in group.dep_details"
                       style="margin-right: 5px;margin-bottom: 2px;">{{detail.name}}</el-tag>

               </div>
             </div>
           </el-descriptions-item>
           <el-descriptions-item span='4'>
             <template slot="label">
               说明
             </template>
             {{showform.content?showform.content:''}}
           </el-descriptions-item>
         </el-descriptions>
         <!-- <el-divider>计划内容</el-divider>
          <xy-table
             height="300px"
            :list="showform.months_list"
            stripe
            :isPage="false"
            :table-item="table">
            <template v-slot:btns>
              <div></div>
            </template>
          </xy-table> -->
      </template>
      <template v-slot:missionlist>
          <el-divider>任务情况</el-divider>
          <Button :disabled="hasLocked" type="primary" style='margin-right:5px;margin-bottom:5px;'
            @click="editorPlan('','add')">添加子任务</Button>
          <xy-table :list="mission_log" :height="'600px'" :table-item="missionLogTable" :showIndex='false' :isPage='false' :span-method="spanMethod">
            <template v-slot:btns>
              <el-table-column align='center' label="操作" width="100" header-align="center">
                <template slot-scope="scope">
                  <div>
                    <Button type="primary" style='margin-right:5px;margin-bottom:5px;' size="small"
                      @click="editorPlan(scope.row.id,'editor')">编辑</Button>
                  </div>
                  <div>
                    <Button type="primary" style='margin-right:5px;margin-bottom:5px;' size="small"
                      @click="backPlan(scope.row)">归档</Button>
                  </div>
                  <div>
                    <Poptip transfer confirm title="确认要删除吗？" @on-ok="deleteList(scope.row.id)">
                       <Button type="primary" style="margin-right:5px;margin-bottom:5px;" size="small" >删除</Button>
                    </Poptip>
                  </div>

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

      <template  v-slot:footerContent>
        <!-- {{showform.is_lock}} -->
        <Button v-if="stateObj.login_id==showform.admin_id||stateObj.is_guiji||stateObj.is_chuzhang" :type="showform.is_lock?'':'primary'"
        :style="showform.is_lock?'background:#ccc;border:1px solid #ccc;color:#fff;margin-left:5px;margin-bottom:5px;':'margin-left:5px;margin-bottom:5px;'"
        @click="changeLock">锁定</Button>
        <Button type="primary" ghost style='margin-left:5px;margin-bottom:5px;' @click="isShow=false">取消</Button>
      </template>

    </xy-dialog>
    <addUnit ref='addUnit' @refresh='getMission'></addUnit>
    <checkUnit ref='checkUnit' @refresh='getMission'></checkUnit>
    <addOutline ref="addOutline"  @refresh='getMission'></addOutline>

    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%">
      <span>请确认是否将该任务归档到<span style="color:red">{{messageInfo}}</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>


  </div>
</template>

<script>
  import {
    Message
  } from 'element-ui'
  import {
    getparameteritem
  } from "@/api/system/dictionary.js";
  import {
    get,
    save
  } from "@/api/task/plan.js";
  import {
    listunit
  } from '@/api/task/unit.js'
  import addUnit from '../../list/components/addUnit.vue'
  import checkUnit from '../../list/components/checkUnit.vue'
  import state from '@/store/modules/user.js'
  import addOutline from '../../list/components/addOutline.vue'
  import imports from '@/components/imports/imports.vue'
  import {
    index,
    show,
    destroy
  } from '@/api/task/newplan.js'
  import {
    getMergeCells,groupBy
  } from '@/utils/contactTable.js'
  export default {
    components: {
      addUnit,
      checkUnit,
      addOutline
    },
    data() {
      return {
        isShow: false,
        dialogVisible:false,
        messageInfo:'',
        id:'',
        select: {
          keyword: '',
          table_name:'new_plans',
          page: 1,
          page_size: 99999,
          sort_name: 'created_at',
          sort_type: 'ASC'
        },
         menuList:[],
        pictureList:[],
        stateObj:{},
        statusList:[{
          id:0,
          value:'未完成'
        },{
          id:1,
          value:'未开展'
        },{
          id:2,
          value:'开展中'
        },{
          id:3,
          value:'已完成'
        }],
        hasLocked:false,
        showform:{},
        form: {
          contents:'',
          missionlist:'',
          plan_type:'',
          name: '',
          year:'',
          type: '',
          start_date: '',
          status:1,
          end_date: '',
          // count:'',
          lefts:'',
          name7: 1,
          file_ids: '',
          content: '',
          accept_admin_ids: [],
          accept_department_ids: [],
          is_lock:null
        },
        auditStatusList:[{
          id:0,
          value:'待审核',
          type:'warning'
        },{
          id:4,
          value:'待办',
          type:'info'
        },{
          id:1,
          value:'开展中',
          type:''
        },{
          id:2,
          value:'办理中',
          type:'danger'
        },{
          id:3,
          value:'已完成',
          type:'success'
        },{
          id:5,
          value:'审核不通过',
          type:'warning'
        }],
        table:[{
            label: "月份",
            prop: 'month',
            width: 120,
            align:'center'
          },{
            label: "内容",
            prop: 'list',
            align:'left',
            customFn:(row)=>{
              return(<div>
              {
                row.list.map((item,index)=>{
                  return(<div style={{'margin':'5px'}}>{index+1}、<span style={{'width':'85%','display':'inline-block'}}>{item.content}</span>
                   <el-button style={{"margin-left":'5px',"height":'40px'}} type='primary' size='small' on={
                    {
                      ["click"]:(e)=> this.editorUnit,
                    }
                   } >添加任务</el-button>
                  </div>)
                })
              }

              </div>)
            }
          }],
        mission_log:[],
        missionLogTable:[{
            label: "工作项目",
            prop: 'menu',
            align:'center',
            fixed:'left',
            width: 120
          }, {
            label: "性质级别",
            prop: 'level',
            width: 120,
            align:'center',
            fixed:'left'
          }, {
            label: "主要内容",
            prop: 'content',
            align: 'left',
            width:240
          }, {
            label: "工作周期",
            prop: 'period',
            width: 120
          }, {
            label: "工作要求",
            prop: 'require',
            width:240
          }, {
            label: "完成时间",
            prop: 'end_time',
            width: 120,
            align:'center'
          }, {
            label: "责任科室",
            prop: 'duty_dep_id',
            width: 120
          }, {
            label: "参与科室",
            prop: 'join_dep_id',
            width: 120,
          },{
            label: "具体流程概述",
            prop: 'flow',
                        width:240
          },{
            label: "所需资源概述",
            prop: 'resource',
                        width:240
          }],
      }
    },
    computed: {
      // 获取所有单元格合并数据
      spanArr() {
        if (!this.missionLogTable.length) return []
        const mergeCols = ['menu', 'level'] // 需要合并的列（字段）
        const data = groupBy(this.mission_log, 'menu')
        return getMergeCells(data, this.missionLogTable, mergeCols)
      }
    },
    created() {
      this.stateObj = state.state
      this.getMenuList()
    },
    methods: {
      backPlan(row){
        this.messageInfo = `${row.menu}-${row.level}`
        this.dialogVisible = true
      },
      editorUnit(type, plan_id) {
        this.$refs.addUnit.type = type
        if(type==='editor'){
          this.$refs.addUnit.id=plan_id
        }else{
          this.$refs.addUnit.plan_id = this.id
        }

        this.$refs.addUnit.isShow = true
      },
      checkUnits(id,type){
        this.$refs.checkUnit.id = id
        this.$refs.checkUnit.type = type
        this.$refs.checkUnit.isShow = true
      },
      async getMission(){
        const res = await index({

          ...this.select,
          filter:[{
            "key":'mission_plan_id',
            "op":"eq",
            "value":this.id
          }],
        })
        this.mission_log = res.data

      },
      spanMethod({
        row,
        colomn,
        rowIndex,
        columnIndex
      }) {

        return this.spanArr[rowIndex][columnIndex]
      },

      async getMenuList(){
        const res = await getparameteritem('main_level')
        this.menuList = res.detail
      },
      changeYear(e) {
        this.select.year = e
      },
      editorPlan(id, type) {
        if(id){
          this.$refs.addOutline.id = id
        }
        this.$refs.addOutline.setMissionId(this.id)
        this.$refs.addOutline.setName(this.showform.name)
        this.$refs.addOutline.type = type
        this.$refs.addOutline.menuList = this.menuList
        this.$refs.addOutline.isShow = true
      },
      deleteList(id) {
        var that = this;
        if (id) {
          destroy({
            id:id,
            table_name:this.select.table_name
          }).then(response => {
            this.$Message.success('操作成功');
            that.getMission();
          }).catch(error => {
            console.log(error)
            reject(error)
          })
        }
      },



      changeLock(){
        if(this.showform.is_lock===1){
          this.showform.is_lock = 0
          this.form.is_lock = 0
          this.hasLocked = false
        }else{
          this.showform.is_lock = 1
          this.form.is_lock = 1
          this.hasLocked = true
        }
        console.log(this.form)
        // return
        save({
          id: this.id,
          ...this.form
        }).then(res => {
          Message({
            type: 'success',
            message: this.hasLocked?'锁定成功':'解锁成功'
          })
        })
      },
      async getDetail() {
        const res = await get(this.id)
        this.showform = res
        // this.showform.is_lock = 1
        this.form = {
          contents:'',
          missionlist:'',
          plan_type:res?.plan_type,
          name: res?.name,
          year:res.year?res.year:new Date().getFullYear(),
          type: res?.type,
          start_date: res?.start_date,
          status:res.status?res.status:1,
          end_date: res?.end_date,
          name7: res.accept_department.length > 0 ? 2 : 1,
          file_ids: res?.file_ids,
          content: res?.content,
          accept_admin_ids: res?.accept_admin_ids,
          accept_department_ids: res?.accept_department_ids,
          is_lock:res?.is_lock
        }
        for (var f of res.files) {
          this.pictureList.push({
            id: f.id,
            url: f.url,
            name: f.original_name
          })
        }
        let group_details = []
        if(res.groups.length>0){
          this.showform.group_details = this.contactGroup(res.groups)
        }
        console.log(this.showform.group_details)
        this.getMission()
      },
      contactGroup(arr) {
        let tempArr = [],
          newArr = []
        for (let i = 0; i < arr.length; i++) {
          if (tempArr.indexOf(arr[i].name) === -1) {
            if(arr[i].type===1){
              newArr.push({
                type: arr[i].type,
                name: arr[i]['name'],
                admin_details: arr[i].details,
                 dep_details: []
              })
            }else{
              newArr.push({
                type: arr[i].type,
                name: arr[i]['name'],
                admin_details:[],
                dep_details: arr[i].details
              })
            }

            tempArr.push(arr[i].name);
          } else {
            for (let j = 0; j < newArr.length; j++) {
              if (newArr[j].name == arr[i].name) {
                if(arr[i].type===1){
                  newArr[j].admin_details.push(...arr[i].details)
                }else{
                  newArr[j].dep_details.push(
                    ...arr[i].details
                  )
                }
              }
            }
          }
        }
        return newArr
      },
    },
    watch: {
      isShow(newVal) {
        if (newVal) {
            this.getDetail()

        } else {
          this.id = ''
          this.pictureList = []
          this.showform = {}
          this.mission_log = []
          this.$refs['dialog'].reset()
        }
      }
    }

  }
</script>

<style scoped lang="scss">
  ::v-deep .contents,
  ::v-deep .end_type,
  ::v-deep .file_ids,
  ::v-deep .is_need_answer,
  ::v-deep .missionlist{
    flex-basis: 100%;
  }
    ::v-deep .missionlist{
      width:100%;
      height:600px
    }
    ::v-deep .el-table .cell.el-tooltip{
      white-space: normal!important;
    }
  ::v-deep .el-divider__text{
    font-size: 20px;
  }
  ::v-deep .el-descriptions :not(.is-bordered) .el-descriptions-item__cell{
    width:16%
  }
  ::v-deep .plan_type {
    display: none;
  }
  ::v-deep .el-form>div{
        align-items: flex-start!important;
  }
  .xy-table-item{
    padding-right:0
  }
  ::v-deep .xy-table-item-label {
    padding-right:0
  }

  .img__delete {
    transform: scale(0.8, 0.8);

    position: absolute;
    top: 4px;
    right: 4px;
  }

  ::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  ::v-deep .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  ::v-deep .el-upload--picture-card {
    font-size: 28px;
    color: #8c939d;
    width: 80px !important;
    height: 80px !important;
    line-height: 80px !important;
    text-align: center;
  }

  ::v-deep .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px !important;
    height: 80px !important;
    line-height: 80px !important;
    text-align: center;
  }

  ::v-deep .avatar {
    width: 80px !important;
    display: block;
    border-radius: 6px;
  }

  // ::v-deep .xy-table-item-label {
  //   width: 160px !important;
  // }

  ::v-deep .el-date-editor .el-range-separator {
    width: auto !important;
  }

  ::v-deep .el-input-number .el-input__inner {
    text-align: left !important;
  }

  .searchCompanys {
    display: flex;
    justify-content: space-between;
    margin-bottom: 16px;

    .el-input {
      width: 80%
    }
  }
</style>
