<template>
  <div class="layer-container">
    <div class="head-container">
      <el-input
        v-model="name"
        clearable
        size="small"
        placeholder="输入类型"
        prefix-icon="el-icon-search"
        class="filter-item"
        @input="getLayerDatas"
      />
      <div class="opt-box">
        <el-button
          v-permission="permission.add"
          class="filter-item"
          size="mini"
          type="primary"
          :disabled="!selectedData.id"
          @click="toAdd"
        >
          新增
        </el-button>
        <el-button
          v-permission="permission.edit"
          class="filter-item"
          size="mini"
          type="success"
          :disabled="!selectedData.id"
          @click="toEdit"
        >
          修改
        </el-button>
        <el-button
          slot="reference"
          v-permission="permission.del"
          class="filter-item"
          type="danger"
          size="mini"
          :loading="delAllLoading"
          :disabled="!selectedData.id"
          @click="toDelete"
        >
          删除
        </el-button>
      </div>
    </div>

    <el-tree
      :data="layerDatas"
      :load="getLayerDatas"
      :props="defaultProps"
      :expand-on-click-node="false"
      lazy
      highlight-current
      @node-click="handleNodeClick"
    />
    <!-- 选择提醒部门 -->
    <select-department title="选择提醒部门" ref='selectDepartment' @getData="selectDept"/>
    <!-- 选择提醒人员 -->
    <select-view title="选择提醒人员" dataM='form' ref="selectRemindUsers" dataType="person" @getData="selectRemindUsers" checkFlag=2></select-view>
    <!--表单渲染-->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="closeDialog"
      :visible.sync="dialogShow"
      :title="dialogTitle"
      width="480px"
    >
      <el-form ref="form" :model="formData" :rules="rules" size="small" label-width="100px">
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="到期提醒" prop="expireRemind">
          <el-radio v-model="formData.expireRemind" label="1">是</el-radio>
          <el-radio v-model="formData.expireRemind" label="0">否</el-radio>
        </el-form-item>
        <div v-if="formData.expireRemind == '1'">
          <el-form-item label="提前提醒量（天）" prop="remindTime">
            <el-input v-model="formData.remindTime" placeholder="请输入最小1最大365的数字"/>
          </el-form-item>
          <el-form-item label="提醒人员" prop="remindUserIds">
            <div class="check-users" style="display:flex;overflow:hidden;zoom:1">
              <el-button type="primary" @click="openSelectUser" style="width:56px;height:32px">选择</el-button>
              <div style="margin:0 0 2px 6px;float:left;">
                <el-tag
                  :key="tag"
                  v-for="tag in remindUsers"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(remindUsers,tag)"
                  style="margin:2px 0 0 4px;">
                  {{tag.name}}
                </el-tag>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="提醒部门" prop="departmentName">
            <el-input v-model="formData.departmentName" :disabled="true" style="width:130px"/>
            <el-button type="primary" @click="openSelectDepartment">选择</el-button>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="closeDialog">取消</el-button>
        <el-button :loading="submitLoading" type="primary" @click="doSubmit">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import permission from '@/directive/permission'
import { getLayerTree, add, edit, del } from '@/api/patrolManage/patrolObjectType'
import SelectUser from '@/views/common/selectUser'
import SelectArea from '@/views/common/selectArea'
import SelectDepartment from '@/views/common/selectDepartment'
import SelectView from '@/views/common/selectView'

const defaultForm = {
  id: '',
  name: '',
  code: '',
  parentId: '',
  sort: 999,
  desc: '',
  enable: 1,
  display: '1',

  expireRemind:'1',
  remindTime:'30',
  departmentId:'',
  departmentName:'',
  remindUserIds:'',
}
export default {
  name: 'deviceType',
  directives: { permission },
  components: {
    SelectUser,
    SelectDepartment,
    SelectView
  },
  data() {
    return {
      name: '', //左侧树形图搜索条件
      layerDatas: [],
      defaultProps: {
        // tree组件懒加载默认参数
        children: 'children',
        label: 'name',
        isLeaf: 'leaf'
      },
      permission: {
        add: ['admin', 'patrolObjectType:add'],
        edit: ['admin', 'patrolObjectType:edit'],
        del: ['admin', 'patrolObjectType:del']
      },
      rules: {
        name: [{ required: true, message: '请输入类型名称', trigger: 'blur' }],
        expireRemind: [{ required: true, message: '请选择到期提醒', trigger: 'blur' }],
        remindTime: [{ required: true, message: '请输入到期天数', trigger: 'blur' }],
        remindUserIds: [{ required: true, message: '请选择提醒人员', trigger: 'blur' }],
        departmentId: [{ required: true, message: '请选择提醒部门', trigger: 'blur' }]
      },
      delAllLoading: false,
      downloadLoading: false,
      submitLoading: false,
      dialogShow: false,
      dialogTitle: '新增类型',
      formData: {},
      selectedData: {},
      remindUsers:[],
    }
  },
  methods: {
    // 获取左侧部门数据
    getLayerDatas(node, resolve) {
      // console.log(node);
      const sort = 'id,desc'
      const params = { sort: [sort], id: '0' }
      if (typeof node !== 'object') {
        if (node) {
          params['name'] = node
        }
      } else if (node.level !== 0) {
        params['id'] = node.data.id
      }
      setTimeout(() => {
        getLayerTree(params).then(res => {
          let content = res.data.content
          content.forEach(item => {
            if (!!item.children?.length) {
              item.leaf = false
            } else {
              item.leaf = true
            }
          })
          if (resolve) {
            resolve(content)
          } else {
            this.layerDatas = content
          }
        })
      }, 100)
    },
    // 切换部门
    handleNodeClick(data) {
      // console.log(data);
      this.selectedData = data
      this.$emit('changeLayer', data)
    },
    toAdd() {
      const { id, name } = this.selectedData
      this.$confirm(`是否在【${name}】下创建新类型？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.dialogTitle = '新增类型'
          this.formData = Object.assign({}, defaultForm, { parentId: id })
          this.dialogShow = true
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    toEdit() {
      this.dialogTitle = '编辑类型'
      this.formData = this.selectedData
      this.dialogShow = true
    },
    async toDelete() {
      const { id } = this.selectedData
      const ids = [id]
      try {
        await del(ids)
        this.getLayerDatas()
      } catch (err) {
        console.log(err)
      }
    },
    async doSubmit() {
      console.log(this.formData)
      try {
        if (!this.formData.id) {
          await add(this.formData)
        } else {
          await edit(this.formData)
        }
        this.closeDialog()
        this.getLayerDatas()
      } catch (err) {
        console.log(err)
      }
    },
    closeDialog() {
      this.selectedData = {}
      this.dialogShow = false
    },
    selectRemindUsers(list){
      this.remindUsers=list
      console.log(list)
      if (list) {
        for (let i = 0; i < list.length; i++) {
          this.formData.checkItem.push({
            objectId:list[i].id,objectName:list[i].name
          }) 
        }
      }
    },
    selectDept(list){
      console.log(list)
      this.formData.departmentId = list[0].id
      this.formData.departmentName= list[0].departmentName
    },
    openSelectUser(){
      this.$refs.selectRemindUsers.openOrClose = true
    },
    openSelectDepartment(){
      this.$refs.selectDepartment.openOrClose = true
    },
    handleClose(list,tag) {
      list.splice(list.indexOf(tag), 1);
    },
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .vue-treeselect__control,
::v-deep .vue-treeselect__placeholder,
::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
.layer-container {
  .opt-box {
    display: flex;
  }
}
</style>
