<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"
          @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"
    />
    <!--表单渲染-->
    <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="80px">
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
      </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'
const defaultForm = {
  //主要参数
  id: 0,
  name: '',
  parentId: 0,

  children:[],
  iChildren:[
    { 
      id:0,
      parentId:0,
      iChildren:[]
    }
  ],
  label:'',

  code: '',
  sort: 999,
  desc: '',
  enable: 1,
  display: '1'
}
export default {
  name: 'patrolObjectType',
  directives: { permission },
  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' }]
      },
      delAllLoading: false,
      downloadLoading: false,
      submitLoading: false,
      dialogShow: false,
      dialogTitle: '新增巡检对象类型',
      formData: {},
      selectedData: {}
    }
  },
  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
      if ( name == undefined) {
          this.$confirm(`是否在最外下创建新巡检对象类型？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              this.dialogTitle = '新增巡检对象类型'
              this.formData = Object.assign({}, defaultForm, { parentId: id })
              this.dialogShow = true
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消'
              })
            })
        } else {
        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, name } = this.selectedData
      const ids = [id]

      this.$confirm(`是否删除【${name}】巡检对象类型？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

      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
    }
  }
}
</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>
