<template>
<div>
    <xy-dialog ref="dialog" :is-show.sync="isShow" type="form" :title="type === 'add' ? '发起计划' : '编辑计划'" :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: bold;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:year>
        <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-date-picker style="width: 400px;" v-model="form.year" value-format="yyyy" type="year"
              placeholder="选择计划年份">
            </el-date-picker>
          </div>
        </div>
      </template>
      <template v-slot:type>
        <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.type" filterable clearable placeholder="请选择计划类型" style="width: 400px;">
              <el-option v-for="item in planTypeList" :key="item.id" :label="item.value" :value="item.id">
              </el-option>
            </el-select>
          </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: bold;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:status>
        <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.status" filterable clearable placeholder="请选择计划状态" style="width: 400px;">
              <el-option v-for="item in statusList" :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: bold;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:count>
        <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.count" placeholder="请输入预期任务数量" clearable style="width: 400px;"></el-input>

          </div>
        </div>
      </template> -->
      <!-- <template v-slot:is_audit>
        <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-radio-group v-model="form.is_audit" @change='changeAudit'>
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </div>
        </div>
      </template>
      <template v-slot:audit_admin_id  v-if="form.is_audit==1">
        <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-select v-model="form.audit_admin_id" filterable clearable placeholder="请选择审批人" style="width: 400px;">
              <el-option v-for="item in userdata" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
      </template> -->
      <template v-slot:lefts>
        <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>

        <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='2' type='textarea' placeholder="请输入说明" clearable
                style="width:400px"></el-input>
            </div>
          </div>
        </div>
      </template>
     <!-- <template v-slot:file_ids>
        <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:600px" :auto-upload="true" :data="uploadOther" :on-success="handlesuccess"
              :on-remove="handleRemove">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </div>
        </div>
      </template>
      <template v-slot:content>
          <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>



      </template> -->
      <template v-slot:name7>
        <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" style="width:400px">
              <el-radio-group v-model="form.name7" @change='changeName7'>
                <el-radio :label="1">人员</el-radio>
                <el-radio :label="2">部门</el-radio>
              </el-radio-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>
            </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-transfer filterable :titles="['待选择', '已选择']" :props="{key: 'id',label: 'name'}"
                :filter-method="filterMethod" :format="{ noChecked: '${total}',hasChecked: '${checked}/${total}' }"
                filter-placeholder="请选择参与人员" v-model="form.accept_admin_ids" :data="userdata">
              </el-transfer> -->
            </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>

      </template>
      <template  v-slot:footerContent>
        <Button type="primary"
          style='margin-left:5px;margin-bottom:5px;' @click="submit">确认</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>

  </div>
</template>

<script>
  import {
    Message
  } from 'element-ui'
  import {
    getparameteritem
  } from "@/api/system/dictionary.js";
  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'

  export default {
    components: {
    },
    data() {
      return {
        isShow: false,
        type: 'add',
        id: '',
        plan_type:1,
        department_id:'',
        uploadOther: {
          token: ""
        },
        action: `${process.env.VUE_APP_BASE_API}api/admin/upload-file`,
        pictureList: [],
        deptOptions: [],
        checkAll: false,
        isIndeterminate: true,
        userdata: [],
        filterMethod(query, item) {
          return item.name.indexOf(query) > -1;
        },
        planTypeList: [],
        statusList:[{
          id:0,
          value:'未完成'
        },{
          id:1,
          value:'未开展'
        },{
          id:2,
          value:'开展中'
        },{
          id:3,
          value:'已完成'
        }],
        form: {
          plan_type:'',
          name: '',
          year:'',
          type: '',
          start_date: '',
          status:1,
          end_date: '',
          // count:'',
          lefts:'',
          name7: 1,
          file_ids: '',
          content: '',
          accept_admin_ids: [],
          accept_department_ids: [],
        },
        rules: {
          name: [{
            required: true,
            message: '请输入计划名称'
          }],
          status: [{
            required: true,
            message: '请选择计划状态'
          }],
          year: [{
            required: true,
            message: '请选择计划年份'
          }],
          start_date: [{
            required: true,
            message: '请选择开始时间'
          }],
          end_date: [{
            required: true,
            message: '请选择结束时间'
          }],
          type: [{
            required: true,
            message: '请选择任务类型'
          }]
        }
      }
    },
    created() {
      this.uploadOther.token = getToken();
      this.getPlanList()
      this.loadDeptOptions()
      this.loadUser()
    },
    methods: {
      async getPlanList(){
        const res = await getparameteritem('planType')
        this.planTypeList = res.detail
      },
      changeName7(e) {
        if (e) {
          this.form.accept_department_ids = []
          this.form.accept_admin_ids = []
        }
      },
      // 选择科室
      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,
          department_id:this.department_id
        }).
        then((res) => {
          this.userdata = res.data ? res.data.reverse() : [];
        }).catch(error => {
          console.log(error)
        })
      },
      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;
      },

      async getDetail() {
        const res = await get(this.id)
        this.form = {
          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,

          lefts:'',
          name7: res.accept_department.length > 0 ? 2 : 1,
          file_ids: res?.file_ids,
          content: res?.content,
          accept_admin_ids: res?.accept_admin,
          accept_department_ids: res?.accept_department,
        }
        for (var f of res.files) {
          this.pictureList.push({
            id: f.id,
            url: f.url,
            name: f.original_name
          })
        }
      },
      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 = []
        }

        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') {
          save({
            id: this.id,
            ...this.form
          }).then(res => {
            Message({
              type: 'success',
              message: '编辑计划成功'
            })
            this.isShow = false
            this.$emit('refresh')
          })
        }
      },
      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('操作成功');
            this.isShow = false
            this.$emit('refresh')
          }).catch(error => {
            console.log(error)
            reject(error)
          })
        }
      }
    },
    watch: {
      isShow(newVal) {
        if (newVal) {
          if (this.type === 'editor') {
            this.getDetail()
          }
          if(this.type==='add'){
            var date = new Date()
            this.form.year = date.getFullYear()+''
          }
        } else {
          this.id = ''
          this.plan_type = 1
          this.pictureList = []
          this.$refs['dialog'].reset()
        }
      },
      plan_type(newval){
        if(newval){
          this.form.plan_type=newval
        }
      }
    }

  }
</script>

<style scoped lang="scss">
  ::v-deep .content,
  ::v-deep .end_type,
  ::v-deep .file_ids,
  ::v-deep .is_need_answer{
    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>
