<template>
  <div>
    <xy-dialog ref="dialog" :is-show.sync="isShow" type="form" :subtitle="subtitle" :title="typeName" :form="form"
      :rules='rules' @submit="submit">
      <template v-slot:name>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>任务名称：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.name" placeholder="请输入任务名称" clearable style="width: 400px;"></el-input>
          </div>
        </div>
      </template>

      <template v-slot:start_date>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>开始日期：
          </div>
          <div class="xy-table-item-content">
            <el-date-picker style="width: 400px;" v-model="form.start_date" value-format="yyyy-MM-dd" type="date"
              placeholder="选择开始日期">
            </el-date-picker>
          </div>
        </div>
      </template>
      <template v-slot:unit_type>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>任务类型：
          </div>
          <div class="xy-table-item-content">
            <el-select @change="changeUnitType" v-model="form.unit_type" filterable clearable placeholder="请选择任务类型"
              style="width: 400px;">
              <el-option v-for="item in unitTypeList" :key="item.id" :label="item.value" :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:end_date>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>要求完成日期：
          </div>
          <div class="xy-table-item-content">
            <el-date-picker style="width: 400px;" v-model="form.end_date" value-format="yyyy-MM-dd" type="date"
              placeholder="选择要求完成日期">
            </el-date-picker>
          </div>
        </div>
      </template>

      <template v-slot:lefts>
        <div>
          <div class="xy-table-item"  v-if="showUnit4Type">
            <div class="xy-table-item-label">
              <span style="color: red;font-weight: 600;padding-right: 4px;"></span>任务类别：
            </div>
            <div class="xy-table-item-content">
              <el-select @change="changeUnit4Type" v-model="form.mission_type_id" filterable clearable placeholder="请选择任务类别"
                style="width: 400px;">
                <el-option v-for="item in unit4TypeList" :key="item.id" :label="item.value" :value="item.id">
                </el-option>
              </el-select>
            </div>
          </div>
        </div>
        <div v-if="showUnit4Type">
          <div class="xy-table-item">
            <div class="xy-table-item-label" style="font-weight: bold">
              <span style="color: red;font-weight: bold;padding-right: 4px;">*</span>工作项目：
            </div>
            <div class="xy-table-item-content">
              <el-select v-model="form.menu" @change="changeMenu" style="width: 400px;" placeholder="请选择">
                <el-option v-for="item in menuList" :key="item.id" :label="item.name" :value="item.name">
                </el-option>
              </el-select>
            </div>
          </div>
        </div>


        <div v-if="is_what_unitType=='学习'">
          <div class="xy-table-item">
            <div class="xy-table-item-label" style="font-weight: bold;">
              <span style="color: red;font-weight: 600;padding-right: 4px;"></span>学习时长：
            </div>
            <div class="xy-table-item-content">
              <span>需学习</span>
              <el-input style="margin:0 5px;width:100px" v-model="form.study_time" type='number' placeholder=""
                clearable></el-input>
              <span>分钟</span>
            </div>
          </div>
        </div>
        <div>
          <div class="xy-table-item">
            <div class="xy-table-item-label">
              <span style="color: red;font-weight: 600;padding-right: 4px;"></span>任务内容及要求：
            </div>
            <div class="xy-table-item-content">
              <el-input v-model="form.content" :rows='8' type='textarea' placeholder="请输入任务内容及要求" clearable
                style="width:400px"></el-input>
            </div>
          </div>
        </div>
        <div>
          <div class="xy-table-item">
            <div class="xy-table-item-label">
              <span style="color: red;font-weight: 600;padding-right: 4px;"></span>附件：
            </div>
            <div class="xy-table-item-content">
              <el-upload :action="action" class='upload-demo' :file-list="pictureList" ref="pictureUpload"
                style="width:400px" :auto-upload="true" :data="uploadOther" :on-success="handlesuccess"
                :on-remove="handleRemove">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </div>
          </div>
        </div>
      </template>

      <template v-slot:name7>
        <div v-if="type=='add'||type=='editor'">
          <div class="xy-table-item">
            <div class="xy-table-item-label">
              <span style="color: red;font-weight: bold;padding-right: 4px;">*</span>责任人(科室)：
            </div>
            <div class="xy-table-item-content" style="width:400px">
              <el-select style="width:48%;margin-right:2%" :disabled="form.main_department_id&&!stateObj.is_chuzhang?true:false" v-model="form.main_department_id" @change="changeDeptOptions"
                placeholder="请选择部门">
                <el-option v-for="item in deptOptions" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
              <el-select style="width:48%;" :disabled="form.main_admin_id&&!stateObj.is_chuzhang?true:false" v-model="form.main_admin_id" placeholder="请选择部门人员">
                <el-option v-for="item in userOptions" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </div>
          </div>
        </div>
        <div  v-if="showUnit4Type">
          <div class="xy-table-item">
            <div class="xy-table-item-label" style="font-weight: bold">
              <span style="color: red;font-weight: bold;padding-right: 4px;">*</span>性质级别：
            </div>
            <div class="xy-table-item-content">
              <el-select v-model="form.level" @change="changeLevel" style="width: 400px;" placeholder="请选择">
                <el-option v-for="(item,index) in levelList" :key="item.id" :label="item.name" :value="item.name">
                </el-option>
              </el-select>
            </div>
          </div>
        </div>
        <div  v-if="!plan_unit">
          <div v-if="type!='send'">
            <div class="xy-table-item">
              <div class="xy-table-item-label">
                <span style="color: red;font-weight: 600;padding-right: 4px;"></span>{{type=='pid'?'分解任务给':'参与对象'}}：
              </div>
              <div class="xy-table-item-content" style="width:400px">
                <el-radio-group v-model="form.name7" @change='changeName7'>
                  <!-- <el-radio :label="1">人员</el-radio>
                  <el-radio :label="2" v-if='form.type!=4'>部门</el-radio>
                  <el-radio :label="3" v-if='!(form.type==4||form.type==2)'>小组</el-radio> -->
                  <el-radio v-if="type!='send'" :label="3">小组</el-radio>
                  <el-radio v-if="type!='send'" :label="1">人员</el-radio>
                  <el-radio v-if="type!='send'" :label="2">部门</el-radio>
                </el-radio-group>
              </div>
            </div>
          </div>
          <div v-if='form.name7==2'>
            <div class="xy-table-item">
              <div class="xy-table-item-label">
                <span style="color: red;font-weight: 600;padding-right: 4px;"></span>
              </div>
              <div class="xy-table-item-content" style='min-width:400px'>
                <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选
                </el-checkbox>
                <div style="margin: 15px 0;"></div>
                <el-checkbox-group v-model="form.accept_department_ids" @change="handleCheckedDeptChange">
                  <el-checkbox @change="handleCheckedDeptSingleChange" v-for="dept in deptOptions" :label="dept.id"
                    :key="dept.id">{{dept.name}}</el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
          </div>
          <div v-if='form.name7==1'>
            <div class="xy-table-item">
              <div class="xy-table-item-label">
                <span style="color: red;font-weight: 600;padding-right: 4px;"></span>{{type!='send'?'':'承办人员：'}}
              </div>
              <div class="xy-table-item-content" style='min-width:400px'>
                <!-- <el-select style="width:400px" v-model="form.accept_admin_ids" clearable filterable multiple placeholder="请选择人员">
                  <el-option v-for="item in userdata" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select> -->
                <el-select-tree v-if="type!='send'" :datas='userdata' :valueArr='valueArr' :valueMultiple="valueMultiple"
                  @getValue="getSelectedValue"></el-select-tree>

                <el-select-tree v-if="type=='send'" :datas='douserdata' :valueArr='valueArr' :valueMultiple="valueMultiple"
                  @getValue="getSelectedValue"></el-select-tree>
              </div>
            </div>
          </div>


          <div v-if='form.name7==3'>
            <div class="xy-table-item">
              <div class="xy-table-item-label" style="width:0;min-width:0;">
                <span style="color: red;font-weight: 600;padding-right: 4px;"></span>
              </div>
              <div class="xy-table-item-content" style='min-width:100px;width:100%'>
                <Button type='primary'
                  @click="mission_groups_list.push({name:'',type:1,link_id:[],link_id_dep:[]})">新增小组</Button>
                  <el-table :data="mission_groups_list" style="width: 100%">
                        <el-table-column prop="name" label="组别" width="100">
                          <template slot-scope="scope">
                            <div>{{scope.row.name=mission_groups_name[scope.$index]}}</div>
                          </template>
                        </el-table-column>
                        <el-table-column prop="leader" label="组长" width="180">
                          <template slot-scope="scope">
                            <el-select-tree :datas='userdata'
                              style="width: 100%;min-width: 100%;"
                              :valueArr='scope.row.valueArr' :valueMultiple="scope.row.valueMultiple"
                              @getValue="(e)=>{return getSelectedgroupValue(e,scope.row)}"></el-select-tree>
                          </template>
                        </el-table-column>
                        <el-table-column prop="team" label="组员" width="210">
                          <template slot-scope="scope">
                            <el-select v-model="scope.row.link_id_dep" clearable collapse-tags filterable multiple
                              placeholder="请选择部门">
                              <el-option v-for="item in deptOptions" :key="item.id" :label="item.name" :value="item.id">
                              </el-option>
                            </el-select>
                          </template>
                        </el-table-column>
                        <el-table-column
                          prop="del"
                          label="操作"
                          width="80">
                          <template slot-scope="scope">
                            <Button style="margin-right:10px" @click="mission_groups_list.splice(scope.$index,1)">删除</Button>
                          </template>
                        </el-table-column>
                      </el-table>




                <!-- <div v-for="(item,index) in mission_groups_list" style='margin:10px;margin-left:0'>
                  <div>
                    <Button style="margin-right:10px" @click="mission_groups_list.splice(index,1)">删除</Button>
                    <div>小组：{{item.name=mission_groups_name[index]}}</div>
                    <el-select-tree style="width:48%;min-width:48%;margin-right:2%" :datas='userdata'
                      :valueArr='item.valueArr' :valueMultiple="item.valueMultiple"
                      @getValue="(e)=>{return getSelectedgroupValue(e,item)}"></el-select-tree>
                    <el-select style="width:48%;" v-model="item.link_id_dep" clearable collapse-tags filterable multiple
                      placeholder="请选择部门">
                      <el-option v-for="item in deptOptions" :key="item.id" :label="item.name" :value="item.id">
                      </el-option>
                    </el-select>

                  </div>

                </div> -->


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




      </template>
      <template v-slot:unitTypeList>
        <div v-if="is_what_unitType=='答题'">
          <div class="xy-table-item">
            <div class="xy-table-item-label" style="font-weight: bold;">
              <span style="color: red;font-weight: 600;padding-right: 4px;"></span>正确数：
            </div>
            <div class="xy-table-item-content">
              <span>需答对</span>
              <el-input style="margin:0 5px;width:100px" v-model="form.ask_number" type='number' placeholder=""
                clearable></el-input>
              <span>题</span>
            </div>
          </div>
        </div>
        <div v-if="is_what_unitType=='答题'">
          <div class="xy-table-item">
            <div class="xy-table-item-label">
              <span style="font-weight: 600;padding-right: 4px;">题库：</span>
            </div>
            <div class="xy-table-item-content" style='width:100%'>
              <div>
                <el-button style="margin-bottom:5px" @click="openQs" size="small" type="primary">建设题库</el-button>
                <div>
                  <xy-table :list="form.ask" stripe :table-item="askTable" :isPage='false'>
                    <template v-slot:btns></template>
                  </xy-table>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>


      <template v-slot:train_time v-if="is_what_unitType=='培训'">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>培训时间：
          </div>
          <div class="xy-table-item-content">
            <el-date-picker style="width: 400px;" v-model="form.train_time" format="yyyy-MM-dd HH:mm"
              value-format="yyyy-MM-dd HH:mm" type="datetime" placeholder="选择培训时间">
            </el-date-picker>
          </div>
        </div>
      </template>
      <template v-slot:train_company v-if="is_what_unitType=='培训'">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>培训单位：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.train_company" type='text' placeholder="请输入培训单位" clearable
              style="width: 400px;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:train_number v-if="is_what_unitType=='培训'">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>培训课时：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.train_number" type='text' placeholder="请输入培训课时" clearable
              style="width: 400px;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:train_person v-if="is_what_unitType=='培训'">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>授课人：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.train_person" type='text' placeholder="请输入授课人" clearable
              style="width: 400px;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:train_content v-if="is_what_unitType=='培训'">
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>培训内容：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.train_content" :rows='2' type='textarea' placeholder="请输入培训内容" clearable
              style="width: 400px;"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:footerContent>
        <Button type="primary" style='margin-left:5px;margin-bottom:5px;' @click="clickSubmit">确认</Button>
        </Button>
        <Button type="primary" ghost style='margin-left:5px;margin-bottom:5px;' @click="isShow=false">取消</Button>
        <Poptip v-if="type=='editor'" transfer confirm title="确认要删除吗？" @on-ok="deleteList">
          <Button type="primary" style="margin-left:5px;margin-bottom:5px;" ghost>删除</Button>
        </Poptip>
      </template>





    </xy-dialog>
    <addQuestion ref='addQuestion' @submitQs="submitQs"></addQuestion>
    <sendNotice ref="sendNotice"></sendNotice>
  </div>
</template>

<script>
  import {
    Message
  } from 'element-ui'
  import {
    getparameteritem
  } from "@/api/system/dictionary.js";
  import {
    save,
    get,
    del,
    updatemission
  } from "@/api/task/unit.js";
  import {
    save as saveLog
  } from "@/api/system/baseForm.js";
  import {
    listdept
  } from "@/api/system/department.js"
  import {
    listCommonuser
  } from "@/api/common.js"
  import {
    getToken
  } from '@/utils/auth'
  import {
    listplan
  } from '@/api/task/plan.js'
  import {
    leads
  } from '@/api/task/patrol.js'
  import addQuestion from './addQuestion.vue'
  import {
    contactGroup
  } from '../js/index.js'
  import elSelectTree from '@/components/selectTree'
  import {
    listregulation
  } from "@/api/lawsfile/regulation.js";
  import state from '@/store/modules/user.js'
  import sendNotice from './sendNotice.vue'
  // import mixins from '../mixins/mixins.js';
  export default {
    // mixins:[mixins],
    components: {
      addQuestion,
      elSelectTree,
            sendNotice
    },
    data() {
      return {
        isShow: false,
        type: 'add',
        stateObj:{},
        typeName:'新增任务',
        plan_unit:'', // 年度计划发布任务不用选参与对象
        subtitle:'',
        is_what_unitType: '',
        id: '',
        upload_link: '',
        hasPlanId: false,
        plan_id: '',
        department_id: '',
        uploadOther: {
          token: ""
        },
        action: `${process.env.VUE_APP_BASE_API}api/admin/upload-file`,
        pictureList: [],
        deptOptions: [],
        userOptions: [],
        deptOptionsList: [],
        checkAll: false,
        isIndeterminate: true,
        douserdata:[],
        userdata: [],
        userdatabefore: [],
        valueMultiple: [],
        valueArr: [],
        filterMethod(query, item) {
          return item.name.indexOf(query) > -1;
        },
        auditStatusList: [
          //   {
          //   id:0,
          //   value:'待审核'
          // },
          {
            id: 4,
            value: '待办'
          }, {
            id: 1,
            value: '开展中'
          }, {
            id: 2,
            value: '办理中'
          }, {
            id: 3,
            value: '已完成'
          }
        ],
        showUnit4Type:false,
        unitTypeList: [],
        unit4TypeList:[],
        missionPlanList: [],
        leads_list: {},
        menuList: [],
        levelList: [],
        form: {
          name: '',

          start_date: '',
          unit_type: '',
          end_date: '',

          lefts: '',
          name7: 3,
          audit_status: 4,
          unitTypeList: '',
          ask: [],
          study_time: '',
          train_time: '',
          train_company: '',
          train_number: '',
          train_person: '',
          train_content: '',

          is_need_answer: '',
          is_audit: 0,
          audit_admin_id: '',
          file_ids: '',
          content: '',
          end_content: '',
          accept_admin_ids: [],
          accept_department_ids: [],
          do_admin_ids: [],
          main_department_id: '',
          main_admin_id: '',
          mission_groups: [],
          mission_level: 0,

          mission_plan_id: '',
          out_line_id: '',
          type: 1,
          menu: '',
          level: '',
          menu_id:'',
          level_id:'',
          mission_type:'',
          mission_type_id:'',
          pid:0
        },
        mission_groups_list: [{
          name: '',
          type: 1,
          link_id: []
        }],
        mission_groups_name: ['一组', '二组', '三组', '四组', '五组', '六组', '七组', '八组', '九组', '十组'],
        rules: {
          name: [{
            required: true,
            message: '请输入任务名称'
          }],
          start_date: [{
            required: true,
            message: '请选择开始时间'
          }],
          end_date: [{
            required: true,
            message: '请选择结束时间'
          }],
          unit_type: [{
            required: true,
            message: '请选择任务类型'
          }],
          main_admin_id:[{
            required: true,
            message: '请选择责任人（科室）'
          }],
        },
        askTable: [{
            label: "标题",
            prop: 'qsForm.title',
            align: 'left',
          },
          {
            label: "类型",
            prop: 'qsForm.type_name',
            align: 'center',
            width: 120
          },
          {
            label: "答案",
            prop: 'qsForm.answer',
            align: 'center',
            width: 120,
            formatter: (cell, data, value, index) => {
              return value ? value.join('、') : ''
            }
          }
        ],
      }
    },
    created() {
      // getUser()
      this.uploadOther.token = getToken();
      this.stateObj = state.state
      this.loadUser()
      this.loadDeptOptions()
      // this.getLeads()
      this.getMissionPlan()
      this.getUnitTypeList()
      this.getMenus()
    },
    methods: {
      setNameContent(name, content) {
        this.form.name = name ? name : ''
        this.form.content = content ? content : ''
      },
      setMainId(dId,aId){
        if(dId){
          let that = this
          this.form.main_department_id = dId ? dId : ''
          this.form.main_admin_id = aId ? aId : ''
          this.userdata.map(item => {
            if (item.department_id == dId) {
              this.userOptions = item.children
              // console.log(" this.userOptions1", this.userOptions)
              // setTimeout(function() {
              //   that.form.main_admin_id = aId ? aId : ''
              // }, 1000)
            }
          })
        }

      },
      setMenuLevel(menu, level,menu_id,level_id) {
        this.form.menu = menu ? menu : ''
        this.form.level = level ? level : ''
        this.form.menu_id = menu_id?menu_id:''
        this.form.level_id = level_id?level_id:''
      },
      setType(type) {
        this.form.type = type ? type : 1
      },
      setoutLineId(id) {
        this.form.out_line_id = id ? id : ''
      },
      setPlanUnit(type){
        this.plan_unit = type?type:''
      },
      setMissionPlanId(id){
        this.form.mission_plan_id = id?id:''
      },
      async getLeads() {
        // const res = await leads()
        this.leads_list = state.state.leads_list.departmen

      },
      async getUnit4TypeList() {
        const res = await getparameteritem('missionType')
        this.unit4TypeList = res.detail
        this.showUnit4Type =true
      },
      async getMissionPlan() {
        const res = await listplan({
          page: 1,
          page_size: 9999
        })
        this.missionPlanList = res.data
      },
      changeUnitType(e) {
        this.unitTypeList.map(item => {
          if (e == item.id) {
            this.is_what_unitType = item.value
          }
        })


      },
      changeUnit4Type(e){
        if(e){
          this.unit4TypeList.map(item => {
            if (e == item.id) {
              this.form.mission_type = item.value
            }
          })
        }
      },
      async getMenus(){
        var that = this;
        await listregulation(1, 20).then(res => {
          this.menuList = res
        }).catch(error => {
          console.log(error)
        })
      },
      changeMenu(e) {
        if (e) {
          this.form.level = ''
          this.form.level_id = ''
          this.menuList.map(item => {
            if (e === item.name) {
              this.form.menu_id = item.id
              this.levelList = item.children ? item.children: [],
              this.menuSort = item.sort
            }
          })
        }
      },
      changeLevel(e){
        if(e){
          this.levelList.map((item,index)=>{
            if(e===item.name){
              this.form.level_id = item.id
            }
          })
        }
      },
      openQs() {
        this.$refs.addQuestion.qsShow = true
        this.$refs.addQuestion.topicList = this.form.ask
      },
      submitQs(e) {
        this.form.ask = e
      },
      changeName7(e) {
        if (e) {
          this.form.accept_department_ids = []
          this.form.accept_admin_ids = []
          this.form.mission_groups = []
          this.mission_groups_list = []
          this.valueArr = []
          this.valueMultiple = []
          this.$forceUpdate()
        }
      },
      changeAudit(e) {
        if (e == 1) {
          this.form.audit_status = 0
          this.form.audit_admin_id = ''
        } else {
          this.form.audit_status = 1
          this.form.audit_admin_id = 0
        }
      },
      // 选择科室
      loadDeptOptions() {
        listdept().
        then((res) => {
          for (var m of res) {
            m.checked = false;
            this.deptOptionsList.push(m)
          }
          this.deptOptions = res;
          this.deptOptionsList.unshift({
            id: 0,
            name: '处级'
          })
        }).catch(error => {
          console.log(error)
          reject(error)
        })
      },
      changeDeptOptions(e) {
        if (e) {
          this.form.main_admin_id = ''
          this.userdata.map(item => {
            if (item.department_id === e) {
              this.userOptions = item.children
              this.form.main_admin_id = item.manager_id
            }
          })
        }
      },
      async getUnitTypeList() {
        const res = await getparameteritem('unitTypeList')
        this.unitTypeList = res.detail
      },
      loadUser() {
        listCommonuser({
          page_size: 999,
        }).
        then((res) => {
          // this.userdata = res.data ? res.data.reverse() : [];
          let data = res.data ? res.data.reverse() : [];
          this.userdatabefore = data;
          let contactData = this.contactUser(data)
          this.userdata = this.sortDepartment(contactData, 'department_id')
          console.log("this.userdata11", this.userdata)
          // 非处长 承办人员只能选自己科室下的
          if(!this.stateObj.is_chuzhang){
            this.douserdata = this.userdata.filter(item=>item.department_id===this.stateObj.department_id)
            console.log("this.douserdata11",this.douserdata)
          }else{
            this.douserdata = this.userdata
          }

        }).catch(error => {
          console.log(error)
        })
      },
      getSelectedValue(value) {
        console.log('选中的结果值', value)

        if (value.length > 0) {
          let _arr = []
          value.map(item => {
            _arr.push(item.id)
          })
          if (this.type === 'send') {
            this.form.do_admin_ids = _arr
          } else {
            this.form.accept_admin_ids = _arr

          }
        } else {
          if (this.type === 'send') {
            this.form.do_admin_ids = []
          } else {
            this.form.accept_admin_ids = []

          }
        }
      },
      getSelectedgroupValue(value, item) {
        console.log('选中的结果值', value, item)
        if (value.length > 0) {
          value.map(item1 => {
            item.link_id.push(item1.id)
          })
        } else {
          item.link_id = []
        }
      },
      contactUser(arr) {
        let tempArr = [],
          newArr = []
        for (let i = 0; i < arr.length; i++) {
          if (tempArr.indexOf(arr[i].department_id) === -1) {
            newArr.push({
              department_id: arr[i].department_id,
              name: arr[i]['department']['name'],
              manager_id: arr[i]['department']['manager_id'],
              leader_id: arr[i]['department']['leader_id'],
              children: [arr[i]]
            })
            tempArr.push(arr[i].department_id);
          } else {
            for (let j = 0; j < newArr.length; j++) {
              if (newArr[j].department_id == arr[i].department_id) {
                newArr[j].children.push(arr[i])
              }
            }
          }
        }
        return newArr
      },
      sortDepartment(arr, key) {
        return arr.sort(function(a, b) {
          var x = a[key]
          var y = b[key]
          return ((x < y) ? -1 : (x > y) ? 1 : 0)
        })
      },
      handleCheckAllChange(val) {
        let options = [];
        for (var m of this.deptOptions) {
          options.push(m.id);
        }
        this.form.accept_department_ids = val ? options : [];
        this.isIndeterminate = false;
      },
      handleCheckedDeptSingleChange(v) {
        //如果出现取消的操作 就要执行删除
        console.log(v);
        var that = this;
        if (this.form.accept_department_ids)
          that.delDeptItem();

      },
      //删除操作
      delDeptItem() {
        for (var m of this.deptOptions) {
          if (this.form.accept_department_ids.indexOf(m.id) == -1) {
            var d = this.form.accept_department_ids.filter(function(t) {
              return t.department_id == m.id;
            })

            if (d.length != 0) {
              delDep(d[0].id).then(response => {}).catch(error => {
                console.log(error)
              })
            }

          }
        }
      },
      handleCheckedDeptChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.deptOptions.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.deptOptions.length;
      },
      // 新增之后 转办 也发送到大平台
      sendNotice(row){
        this.$refs.sendNotice.setForm(row)
        this.$refs.sendNotice.isShow = true
      },
      async getDetail() {
        const res = await get(this.id)
        this.form = {
          name: res?.name,

          start_date: res?.start_date,
          unit_type: res?.unit_type,
          end_date: res?.end_date,

          lefts: '',
          name7: res.accept_department_ids.length > 0 ? 2 : (res.accept_admin_ids.length > 0 ? 1 : (res
            .groups.length > 0 ? 3 : 3)),
          audit_status: res.audit_status === 0 ? 0 : res.audit_status,
          unitTypeList: '',
          ask: res.ask ? res.ask : [],
          study_time: res?.study_time,
          train_time: res?.train_time,
          train_company: res?.train_company,
          train_number: res?.train_number,
          train_person: res?.train_person,
          train_content: res?.train_content,

          is_need_answer: '',
          ask_number: res?.ask_number,
          is_audit: res.audit_admin_id ? 1 : 0,
          audit_admin_id: res.audit_admin_id ? res.audit_admin_id : '',

          file_ids: res?.file_ids,
          content: res?.content,
          end_type: res?.end_type,
          end_content: res?.end_content,

          accept_admin_ids: res?.accept_admin_ids,
          accept_department_ids: res?.accept_department_ids,
          do_admin_ids: res?.do_admin_ids,
          main_department_id: res?.main_department_id,
          main_admin_id: res?.main_admin_id,
          mission_groups: res?.groups,
          mission_level: 0,
          mission_plan_id: res?.mission_plan_id,
          out_line_id: res?.out_line_id,
          type: res?.type,
          menu: res?.menu,
          level: res?.level,
          menu_id:res?.menu_id,
          level_id:res?.level_id,
          mission_type:res?.mission_type,
          mission_type_id:res?.mission_type_id,
          pid:res.pid?res.pid:0
        }
        //
        if (this.type === 'send') {
          this.form.name7 = 1
        }
        if(this.type==='pid'){
          this.form.pid = this.id
          this.form.id = ''
          this.form.main_admin_id = ''
          this.form.main_department_id = ''
        }
        //选择的人员，设置人员选择器初始数据
        if (res.accept_admin_ids && res.accept_admin_ids.length > 0) {
          this.userdatabefore.map(item => {
            res.accept_admin_ids.map(item1 => {
              if (item.id == item1) {
                this.valueMultiple.push(item)
              }
            })
          })
          this.valueArr = res.accept_admin_ids
        }
        // 有do_admin_ids 放入到人员选择器初始数据
        if (this.type == "send" && res.do_admin_ids && res.do_admin_ids.length > 0) {
          this.userdatabefore.map(item => {
            res.do_admin_ids.map(item1 => {
              if (item.id == item1) {
                this.valueMultiple.push(item)
              }
            })
          })
          this.valueArr = res.do_admin_ids
          // res.accept_department_ids = []
        }
        // 责任部门 责任人 分解任务 需要重新制定责任人
        if(this.type==='pid'){
          this.form.main_department_id = this.stateObj.department_id
          this.userdata.map(item => {
            if (item.department_id == this.form.main_department_id) {
              this.userOptions = item.children
              this.form.main_admin_id = this.stateObj.login_id
            }
          })
        }else{
          if (res.main_department_id) {
            this.userdata.map(item => {
              if (item.department_id == res.main_department_id) {
                this.userOptions = item.children
                setTimeout(function() {
                  this.form.main_admin_id = res?.main_admin_id
                }, 1000)
              }
            })
          }
        }

        console.log("this.valueMultiple", this.valueMultiple)
        this.$forceUpdate()
        // this.valueMultiple = res?.accept_admin_ids
        // if(res.audit_status==5){
        //   this.auditStatusList.push({
        //     id:5,
        //     value:'审核不通过'
        //   })
        // }
        this.is_what_unitType = res.unit_type_detail ? res.unit_type_detail.value : ''
        this.mission_groups_list = []
        let group_list = contactGroup(res.groups)

        for (var g of group_list) {
          let admin_arr = {}
          admin_arr = {
            name: g.name,
            type: 1,
            link_id: [],
            link_id_dep: [],
            valueArr: [],
            valueMultiple: []
          }
          if (g.admin_details.length > 0) {
            for (var a of g.admin_details) {
              admin_arr.link_id.push(a.id)
              admin_arr.valueArr.push(a.id)
              admin_arr.valueMultiple.push(a)
            }
          }
          if (g.dep_details.length > 0) {
            for (var d of g.dep_details) {
              admin_arr.link_id_dep.push(d.id)
            }
          }
          this.mission_groups_list.push(admin_arr)
        }
        // this.mission_groups_list = res?.mission_groups
        for (var f of res.files) {
          this.pictureList.push({
            id: f.id,
            url: f.url,
            name: f.original_name
          })
        }
        // res.guide_upload ? this.guidePictureList.push(res.guide_upload) : ''
      },
      clickSubmit() {
        this.$refs.dialog.submit()
      },
      submit() {
        console.log("this.form", this.form)
        // return
        let _files = []

        if (this.pictureList.length > 0) {
          for (var h of this.pictureList) {
            if (h.response) {
              _files.push(h.response.id)
            } else {
              _files.push(h.id)
            }
          }
          this.form.file_ids = _files
        } else {
          this.form.file_ids = []
        }
        if (!this.form.main_admin_id) {
          Message({
            type: 'warning',
            message: `请选择责任人（科室）`
          })
          return
        }
        // if (this.form.is_audit == 0) {
        //   this.form.audit_admin_id = 0
        //   this.audit_status = 1
        // } else {
        //   this.audit_status = 0
        //   if (!this.form.audit_admin_id) {
        //     Message({
        //       type: 'warning',
        //       message: `请选择审批人`
        //     })
        //     return
        //   }
        // }
        // console.log("this.form",this.form)
        // return

        // 如果在年度计划大纲发起任务 不用验证参与人员
        if (this.form.name7 == 3 && !this.plan_unit) {
          if (this.mission_groups_list.length == 0) {
            Message({
              type: 'warning',
              message: `请新增小组`
            })
            return
          }
          let arr = []
          for (var k of this.mission_groups_list) {
            if (k.link_id.length == 0 && k.link_id_dep.length == 0) {
              Message({
                type: 'warning',
                message: `请选择${k.name}成员`
              })
              return
            } else {
              if (k.link_id_dep.length > 0) {
                arr.push({
                  name: k.name,
                  type: 2,
                  link_id: k.link_id_dep
                })
              } else {

              }
              arr.push(k)
            }
          }
          console.log("this.mission_plan_groups_list", arr, this.mission_groups_list)
          // return
          this.form.mission_groups = arr

        }
        if (this.is_what_unitType == '答题' && this.form.ask.length == 0) {
          Message({
            type: 'warning',
            message: `请增加题库题目`
          })
          return
        }
        if(!(this.form.audit_status==3||this.form.audit_status==5)){
          console.log("this.betweenSe",this.form.start_date, this.form.end_date)
          this.betweenSe(this.form.start_date, this.form.end_date)
        }
        console.log("this.form",this.form)
        // return
        // 新增的时候要调用 发送到大平台的接口
        if (this.type === 'add' || this.type=== 'pid') {
          this.form.do_admin_ids = []
          save({
            ...this.form
          }).then(res => {
            Message({
              type: 'success',
              message: '新增任务成功'
            })
            console.log("")
            saveLog({
              table_name:"missions_logs",
              mission_name:this.form.name,
              mission_id:this.form.pid>0?this.form.pid:res.model.id,
              op_name:this.type === 'add'?'新增任务':(this.type=== 'pid'?'任务分解':'新增任务'),
              remark:''
            }).then(res1=>{
              // if(this.plan_unit==='plan_unit'){

              // }else{
                if(res.mission_distribute && res.mission_distribute.length>0){
                  this.sendNotice({
                    id:res.model.id,
                    mission_distribute:res.mission_distribute
                  })
                }
              // }

              this.isShow = false
              this.$emit('refresh')
              this.$emit('toUnit', this.form.type)
            })

            // this.isShow = false
            // this.$emit('refresh')
            // this.$emit("uploadOa")
          })
          return
        }

        if (this.type === 'editor' || this.type === 'send') {
          save({
            id: this.id,
            ...this.form
          }).then(res => {
            Message({
              type: 'success',
              message: '编辑任务成功'
            })
            saveLog({
              table_name:"missions_logs",
              mission_id:this.id,
              mission_name:this.form.name,
              op_name:this.type === 'editor'?'编辑任务':(this.type=== 'send'?'任务转办':'编辑任务'),
              remark:''
            }).then(res1=>{
              console.log("this.type",this.type)
              if(this.type==="send"){
                if(res.mission_distribute && res.mission_distribute.length>0){
                  this.sendNotice({
                    id:res.model.id,
                    mission_distribute:res.mission_distribute
                  })
                }
              }
              this.isShow = false
              this.$emit('refresh')
            })

          })
        }
      },
      betweenSe(start, end) {
          const startTime = new Date(start + "T00:00:00");
          const endTime = new Date(end + "T23:59:59");
          const nowTime = new Date();
          nowTime.setHours(0, 0, 0, 0);
          if(endTime<startTime){
            Message({
              type:'warning',
              message: '任务完成时间不能小于开始时间'
            })
            return
          }
        if (nowTime < startTime) {
          this.form.audit_status = 4
        }
        if (nowTime > endTime) {
          this.form.audit_status = 1
        }
        if (nowTime >= startTime && nowTime <= endTime) {
          this.form.audit_status = 1
        }
      },
      handleRemove(file, fileList) {
        this.pictureList = fileList
      },
      handlesuccess(response, file, fileList) {
        this.pictureList = fileList
      },
      deleteList() {
        var that = this;
        if (this.id) {
          del(this.id).then(response => {
            this.$Message.success('操作成功');
            saveLog({
              table_name:"missions_logs",
              mission_id:this.id,
              mission_name:this.form.name,
              op_name:'删除任务',
              remark:''
            }).then(res=>{
              this.isShow = false
              this.$emit('refresh')
            })
          }).catch(error => {
            console.log(error)
            reject(error)
          })
        }
      }
    },
    watch: {
      upload_link(newval) {
        if (this.type === 'add') {
          if (newval) {
            console.log("file", newval)
            this.upload_link = newval
            this.pictureList.push({
              id: newval.id,
              name: newval.original_name,
              url: newval.url
            })
          } else {
            this.pictureList = []
            this.upload_link = ''
          }
        }

      },
      "form.type":function(val){
        if(val==4){
          this.getUnit4TypeList()
        }
      },
      // department_id(val){
      //   if(val){
      //       console.log('this.department_id',this.department_id)
      //       this.form.mission_level = this.department_id
      //   }else{
      //     this.form.mission_level = 0
      //   }
      // },

      isShow(newVal) {
        if (newVal) {
          switch(this.type){
            case 'add':
                this.typeName = '发布任务'
                break;
            case 'editor':
                this.typeName = '编辑任务'
                this.getDetail()
                break;
            case 'send':
                this.typeName = `任务转办 `
                this.subtitle = '注：可转派给承办人员'
                this.getDetail()
                break;
            case 'pid':
                this.typeName = `任务分解 `
                this.subtitle = '注：可按照任务内容以及要求进行子任务创建'

                this.getDetail()
                break;
            default:
                this.typeName = '发布任务'
                break;
          }

        } else {
          this.id = ''
          this.pictureList = []
          this.subtitle = ''
          this.mission_groups_list = [{
            name: '',
            type: 1,
            link_id: []
          }]
          this.department_id = ''
          this.plan_id = ''
          this.plan_unit = ''
          this.is_what_unitType = ''
          this.hasPlanId = false
          this.upload_link = ''
          this.valueMultiple = []
          this.valueArr = []
          this.checkAll = false
          this.isIndeterminate = true
          this.showUnit4Type = false
          // if(this.auditStatusList.length>5){
          //   this.auditStatusList.splice(5,1)
          // }


          this.$refs['dialog'].reset()
        }
      },
    }

  }
</script>

<style scoped lang="scss">
  ::v-deep .content,
  ::v-deep .end_type,
  ::v-deep .file_ids,
  ::v-deep .is_need_answer,
  ::v-deep .unitTypeList,
  ::v-deep .type // ::v-deep .mission_plan_id

    {
    flex-basis: 100%;
  }

  ::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>
