<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <!-- <el-select
          v-model="query.buildId"
          filterable
          size="small"
          placeholder="请选择建筑名称"
          class="filter-item"
          style="width: 160px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in optionsObj.Build"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select> -->
        <el-input
          v-model="query.name"
          clearable
          size="small"
          placeholder="输入名称搜索"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <rrOperation />
      </div>
      <crudOperation :permission="permission" />
    </div>
    <!--表单组件-->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crudCU"
      :title="crud.status.title"
      width="600px"
    >
      <el-form ref="form" inline :model="form" :rules="rules" size="small" label-width="120px">
        <el-form-item label="管网编号" prop="code">
          <el-input v-model="form.code" style="width: 370px" />
        </el-form-item>
        <el-form-item label="管网名称" prop="name">
          <el-input v-model="form.name" style="width: 370px" />
        </el-form-item>
        <el-form-item label="管网类型" prop="type">
          <el-select
            v-model="form.type"
            filterable
            clearable
            size="small"
            placeholder="请选择管网类型"
            class="filter-item"
            style="width: 370px"
          >
            <el-option
              v-for="item in optionsObj.NetworkType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门" prop="department">
          <treeselect
            v-model="form.department"
            :load-options="loadDptChildren"
            :options="departmentOptions"
            style="width: 370px"
            placeholder="请选择部门"
          />
        </el-form-item>
        <el-form-item label="管网排序" prop="sort">
          <el-input-number
            v-model.number="form.sort"
            :min="0"
            :max="999"
            controls-position="right"
            style="width: 370px"
          />
        </el-form-item>
        <el-form-item label="上级管网" prop="parentId">
          <treeselect
            v-model="form.parentId"
            :load-options="loadChildren"
            :options="crud.data"
            style="width: 370px"
            placeholder="选择上级管网（顶级管网该项不选）"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU"
          >确认</el-button
        >
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      lazy
      :load="loadTableChildren"
      :data="crud.data"
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      @select="crud.selectChange"
      @select-all="crud.selectAllChange"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        v-for="item in networkTableOptions"
        :key="item.prop"
        :label="item.label"
        :prop="item.prop"
        :width="item.width"
        :align="item.align"
        :fixed="item.fixed"
        :sortable="item.sortable"
      >
      </el-table-column>
      <el-table-column
        v-if="checkPer(['admin', 'pipe:network:edit', 'pipe:network:del'])"
        label="操作"
        width="130px"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <udOperation
            :data="scope.row"
            :permission="permission"
            :disabled-dle="scope.row.id === 1"
            msg="确定删除吗,如果存在下级节点则一并删除，此操作不能撤销！"
          />
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import permission from '@/directive/permission'
import crudNetwork from '@/api/pipe/network'
import crudDept from '@/api/system/dept'
import { getOptions } from '@/api/pipe/public'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
// import { crudOperation, rrOperation, udOperation, pagination } from '@crud'
import crudComps from '@crud'
import DateRangePicker from '@/components/DateRangePicker'

// vue-treeselect
import Treeselect from '@riophae/vue-treeselect'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

// 表头配置
import { networkTableOptions } from '../tableConfig'

const defaultForm = {
  id: '',
  code: '',
  name: '',
  parentId: null,
  sort: 999,
  type: '',
  department: '',
}
export default {
  name: 'PipeNetwork',
  directives: { permission },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  components: {
    ...crudComps,
    DateRangePicker,
    Treeselect,
  },
  cruds() {
    return CRUD({
      title: '管网',
      url: 'pipe/network/getChildList',
      crudMethod: { ...crudNetwork },
    })
  },
  data() {
    return {
      networkTableOptions,
      rules: {
        code: [{ required: true, message: '请输入编号', trigger: 'blur' }],
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        type: [{ required: true, message: '请选择类型', trigger: 'blur' }],
        department: [{ required: true, message: '请选择所属部门', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入序号', trigger: 'blur', type: 'number' }],
      },
      permission: {
        add: ['admin', 'pipe:network:add'],
        edit: ['admin', 'pipe:network:edit'],
        del: ['admin', 'pipe:network:delete'],
      },
      optionsObj: { NetworkType: [] },
      departmentOptions: [],
    }
  },
  created() {
    this.getOptions()
  },
  watch: {},
  computed: {
    crudCU() {
      return this.crud.status.cu > 0
    },
  },
  methods: {
    [CRUD.HOOK.beforeToAdd]() {
      if (this.form.id) {
        delete this.form.id
      }
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      if (form.parentId == '0') {
        form.parentId = null
      }
      this.loadDpt(this.form.department)
    },
    // 提交前的验证
    [CRUD.HOOK.afterValidateCU]() {
      if (this.form.parentId !== null && this.form.parentId === this.form.id) {
        this.$message({
          message: '上级管网不能是自身',
          type: 'warning',
        })
        return false
      }
      return true
    },
    async getOptions() {
      Object.keys(this.optionsObj).forEach(async (key) => {
        try {
          let res = await getOptions(key)
          if (res.code === 20000) this.optionsObj[key] = res.data.content
        } catch (error) {
          console.log(error)
        }
      })
    },
    loadTableChildren(tree, treeNode, resolve) {
      const params = { id: tree.id }
      setTimeout(() => {
        crudNetwork.getChildren(params).then(res => {
          resolve(res.data.content)
        })
      }, 100)
    },
    loadChildren({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        crudNetwork.getChildren({ id: parentNode.id }).then((res) => {
          parentNode.children = res.data.content
          setTimeout(() => {
            callback()
          }, 100)
        })
      }
    },
    loadDpt(cid) {
      crudDept.getParentTree({ id: cid }).then((res) => {
        this.departmentOptions = res.data.content
        setTimeout(() => {
          callback()
        }, 100)
      })
    },
    loadDptChildren({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        crudDept.getDepts({ enabled: true, id: parentNode.id }).then((res) => {
          parentNode.children = res.data.content
          setTimeout(() => {
            callback()
          }, 100)
        })
      }
    },
  },
}
</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;
}
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}
</style>
