<template>
  <div>
    <xy-dialog ref="dialog" :width="80" :is-show.sync="isShow" :type="'form'" :title="typeName" :form="form"
      :rules='rules' @submit="submit">

      <template v-slot:lefts>
        <div>
          <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-input :disabled="isdisabled" v-model="form.name" 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-input :disabled="isdisabled" 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 v-if="!isdisabled" :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 v-else>
                <div v-for="item in pictureList">
                  <a :href="item.url" target="_blank">{{item.name}}</a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template v-slot:rights>
        <div>
          <div class="xy-table-item" style="align-items: start;">
            <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-checkbox :disabled="isdisabled" :indeterminate="isIndeterminateMonth" v-model="checkAllMonth"
                @change="handleCheckAllChangeMonth">全选
              </el-checkbox>
              <div style="margin: 15px 0;"></div>
              <el-checkbox-group :disabled="isdisabled" v-model="form.start_date" @change="handleCheckedDeptChangeMonth">
                <el-checkbox @change="handleCheckedDeptSingleChangeMonth" v-for="mon in monthsArr" :label="mon"
                  :key="mon">{{mon}}</el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </div>
        <div>
          <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 :disabled="isdisabled" style="width:48%;margin-right:2%" 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 :disabled="isdisabled" style="width:48%;" 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>



      </template>
      <template v-slot:audits v-if="type==='audit'">
        <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 style="width:80%;" v-model="audit_status_before" placeholder="请选择">
              <el-option :key="1" label="通过" :value="1">
              </el-option>
              <el-option :key="2" label="退回" :value="2">
              </el-option>
            </el-select>
          </div>
        </div>

      </template>

      <template v-slot:footerContent>
        <Button v-if="type=='audit'" type="primary" style='margin-left:5px;margin-bottom:5px;' @click="clickSubmit">审核</Button>
        </Button>
        <Button v-if="type!='audit' && form.audit_status!=0" type="primary" style='margin-left:5px;margin-bottom:5px;' @click="clickSubmit('save')">保存</Button>
        </Button>
        <Button v-if="(type!='audit' && form.audit_status!=0) || type=='add'" type="primary" style='margin-left:5px;margin-bottom:5px;' @click="clickSubmit('confirm')">提交</Button>
        </Button>
        <Button type="primary" ghost style='margin-left:5px;margin-bottom:5px;' @click="isShow=false">取消</Button>
        <Poptip v-if="type!='audit' && form.audit_status==2" transfer confirm title="确认要删除吗？" @on-ok="deleteList">
          <Button type="primary" style="margin-left:5px;margin-bottom:5px;" ghost>删除</Button>
        </Poptip>
      </template>

    </xy-dialog>

  </div>
</template>

<script>
  import {
    Message
  } from 'element-ui'
  import {
    save,
    get,
    del
  } from "@/api/task/plan.js";
  import {
    listdept
  } from "@/api/system/department.js"
  import {
    listCommonuser
  } from "@/api/common.js"
  import {
    getToken
  } from '@/utils/auth'
  import {
    contactUser,
    sortDepartment
  } from '../js/index.js'
  export default {
    components: {

    },
    data() {
      return {
        isShow: false,
        type: 'add',
        typeName:'',
        id: '',
        department_id: '',
        uploadOther: {
          token: ""
        },
        action: `${process.env.VUE_APP_BASE_API}api/admin/upload-file`,
        pictureList: [],
        deptOptions: [],
        userdata: [],
        userOptions: [],
        checkAllMonth: false,
        isIndeterminateMonth: true,
        isdisabled:false,
        form: {
          lefts: '',
          rights: '',
           audits:'',
          name: '',
          content: '',
          file_ids: '',
          start_date: [],
          main_department_id: '',
          main_admin_id: '',
          menu: '',
          level: '',
          menu_id: '',
          level_id: '',
          out_line_id: '',
          out_line_content: '',
          year: '',
          status: 2,
          audit_status:0,

        },
        audit_status_before:'',
        monthsArr: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
        rules: {
          name: [{
            required: true,
            message: '请输入计划名称'
          }],
          start_date: [{
            required: true,
            message: '请选择月份'
          }],
          main_admin_id: [{
            required: true,
            message: '请选择责任人'
          }]
        }
      }
    },
    created() {
      this.uploadOther.token = getToken();
      this.loadDeptOptions()
      this.loadUser()
    },
    methods: {
      setMenuLevel(row) {
        this.form.menu = row.menu ? row.menu : ''
        this.form.level = row.level ? row.level : ''
        this.form.menu_id = row.menu_id ? row.menu_id : ''
        this.form.level_id = row.level_id ? row.level_id : ''
        this.form.out_line_id = row.id ? row.id : ''
        this.form.out_line_content = row.out_line_content ? row.out_line_content : ''
        this.form.name = row.content ? row.content : '',
        this.form.content = row.flow ? row.flow : '',
        this.form.year = row.year ? row.year : new Date().getFullYear()
      },
      // 选择科室
      changeDeptOptions(e) {
        console.log("e",this.userdata)
        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
               console.log("item.manager_id",item.manager_id)
            }
          })
        }
      },
      loadDeptOptions() {
        listdept().
        then((res) => {
          for (var m of res) {
            m.checked = false;
          }
          this.deptOptions = res;
        }).catch(error => {
          console.log(error)
          reject(error)
        })
      },
      loadUser() {
        listCommonuser({
          page_size: 999,
        }).
        then((res) => {
          let data = res.data ? res.data.reverse() : [];
          let contactData = contactUser(data)
          this.userdata = sortDepartment(contactData, 'department_id')
        }).catch(error => {
          console.log(error)
        })
      },

      handleCheckAllChangeMonth(val) {
        let options = [];
        for (var m of this.monthsArr) {
          options.push(m);
        }
        this.form.start_date = val ? options : [];
        this.isIndeterminateMonth = false;
      },
      handleCheckedDeptSingleChangeMonth(v) {
        //如果出现取消的操作 就要执行删除
        console.log(v);
        var that = this;
        if (this.form.start_date)
          that.delDeptItemMonth();

      },
      //删除操作
      delDeptItemMonth() {
        for (var m of this.monthsArr) {
          if (this.form.start_date.indexOf(m) == -1) {
            var d = this.form.start_date.filter(function(t) {
              return t == m;
            })

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

          }
        }
      },
      handleCheckedDeptChangeMonth(value) {
        let checkedCount = value.length;
        this.checkAllMonth = checkedCount === this.monthsArr.length;
        this.isIndeterminateMonth = checkedCount > 0 && checkedCount < this.monthsArr.length;
      },
      handleRemove(file, fileList) {
        this.pictureList = fileList
      },
      handlesuccess(response, file, fileList) {
        this.pictureList = fileList
      },
      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
            }
          })
        }

      },
      async getDetail() {
        const res = await get(this.id)
        let that = this
        this.form = {
          lefts: '',
          rights: '',
          audits:'',
          menu: res?.menu,
          level: res?.level,
          menu_id: res?.menu_id,
          level_id: res?.level_id,
          out_line_id: res?.out_line_id,
          out_line_content: res?.out_line_content,
          name: res?.name,
          year: res.year ? res.year : new Date().getFullYear(),
          status: res.status ? res.status : 2,
          file_ids: res?.file_ids,
          content: res?.content,
          start_date: res.start_date ? res.start_date : [],
          main_department_id: res?.main_department_id,
          main_admin_id: res?.main_admin_id,
          audit_status:res.audit_status?res.audit_status:0,
        }
        for (var f of res.files) {
          this.pictureList.push({
            id: f.id,
            url: f.url,
            name: f.original_name
          })
        }
        // 责任部门 责任人
        if(res.main_department_id){
          this.userdata.map(item=>{
            if(item.department_id==res.main_department_id){
              this.userOptions = item.children
              setTimeout(function(){
                that.form.main_admin_id = res?.main_admin_id
                console.log("this.form.main_admin_id",that.form.main_admin_id)
              },1000)
            }
          })
        }
      },
      clickSubmit(opr) {
        if(opr==='save'){
          this.form.audit_status = 2
        }else if(opr==='confirm'){
          this.form.audit_status = 0
        }else{
          this.form.audit_status = 0
        }
        this.$refs.dialog.submit()
      },
      submit() {
        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 = []
        }
        // this.$refs.dialog.submit()
        // return
        if(this.type==='audit'){
          this.form.audit_status=this.audit_status_before
        }
        console.log("form", this.form)
        // return
        if (this.type === 'add') {
          save({
            ...this.form
          }).then(res => {
            Message({
              type: 'success',
              message: '新增计划成功'
            })
            this.isShow = false
            this.$emit('refresh')
          })
          return
        }
        if (this.type === 'editor' || this.type==='audit') {
          save({
            id: this.id,
            ...this.form
          }).then(res => {
            Message({
              type: 'success',
              message: this.type === 'editor'?'编辑计划成功':'审核成功'
            })
            this.isShow = false
            this.$emit('refresh')
          })
        }
      },

      deleteList() {
        var that = this;
        if (this.id) {
          del(this.id).then(response => {
            this.$Message.success('操作成功');
            this.isShow = false
            this.$emit('refresh')
          }).catch(error => {
            console.log(error)
            reject(error)
          })
        }
      },
    },
    watch: {
      isShow(newVal) {
        if (newVal) {
          if (this.type === 'editor' || this.type === 'audit') {
            if(this.type==='audit'){
              this.isdisabled = true
            }
            this.typeName = this.type === 'editor' ? '编辑计划' :'审核'
            this.getDetail()
          }
          if (this.type === 'add') {
            var date = new Date()
            this.typeName = '发起计划'
            this.form.year = date.getFullYear() + ''
          }
        } else {
          this.id = ''
          this.pictureList = []
          this.audit_status_before = ''
          this.checkAllMonth = false
          this.isIndeterminateMonth = true
          this.isdisabled = false
          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 .months_list {
    flex-basis: 100%;
  }

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