<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.departmentName"
          clearable
          size="small"
          placeholder="输入部门名称搜索"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <date-range-picker v-model="query.createTime" class="date-item" />
        <!-- <el-select
          v-model="query.enabled"
          clearable
          size="small"
          placeholder="状态"
          class="filter-item"
          style="width: 90px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in enabledTypeOptions"
            :key="item.key"
            :label="item.display_departmentName"
            :value="item.key"
          />
        </el-select> -->
        <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="500px"
    >
      <el-form ref="form" inline :model="form" :rules="rules" size="small" label-width="80px">
        <el-form-item label="部门名称" prop="departmentName">
          <el-input v-model="form.departmentName" style="width: 370px" />
        </el-form-item>
        <el-form-item label="部门排序" prop="departmentSort">
          <el-input-number
            v-model.number="form.departmentSort"
            :min="0"
            :max="999"
            controls-position="right"
            style="width: 370px"
          />
        </el-form-item>
        <!-- <el-form-item label="顶级部门">
          <el-radio-group v-model="form.isTop" style="width: 140px">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="enabled">
          <el-radio
            v-for="item in dict.dept_status"
            :key="item.id"
            v-model="form.enabled"
            :label="item.value"
            >{{ item.label }}</el-radio
          >
        </el-form-item> -->
        <el-form-item label="上级部门" prop="parentId">
          <treeselect
            v-model="form.parentId"
            :load-options="loadDepts"
            :options="depts"
            style="width: 370px"
            placeholder="选择上级部门（顶级部门该项不选）"
          />
        </el-form-item>
        <el-form-item label="部门电话" prop="telephone">
          <el-input v-model="form.telephone" style="width: 370px" />
        </el-form-item>
        <el-form-item label="部门传真" prop="fax">
          <el-input v-model="form.fax" style="width: 370px" />
        </el-form-item>
        <el-form-item label="部门Email" prop="email">
          <el-input v-model="form.email" style="width: 370px" />
        </el-form-item>
        <el-form-item style="margin-bottom: 0" label="备注" prop="remark">
          <el-input v-model="form.remark" style="width: 370px" />
        </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="getDeptDatas"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      :data="crud.data"
      row-key="id"
      @select="crud.selectChange"
      @select-all="crud.selectAllChange"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column :selectable="checkboxT" type="selection" width="55" align="center" />
      <el-table-column
        v-for="item in deptTableOptions"
        :key="item.prop"
        :label="item.label"
        :prop="item.prop"
        :width="item.width"
        :align="item.align"
        :fixed="item.fixed"
        :sortable="item.sortable"
      >
        <!-- <template slot-scope="scope">
          <span v-if="item.prop == 'enabled'">
            <el-switch
              v-model="scope.row.enabled"
              :disabled="scope.row.id === 1"
              active-color="#409EFF"
              inactive-color="#F56C6C"
              @change="changeEnabled(scope.row, scope.row.enabled)"
            />
          </span>
          <span v-else>{{ scope.row[item.prop] }}</span>
        </template> -->
      </el-table-column>
      <el-table-column
        v-if="checkPer(['admin', 'system:department:edit', 'system:department: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 crudDept from '@/api/system/dept'
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 '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'

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

const defaultForm = {
  id: '',
  departmentName: '',
  subCount: 0,
  parentId: null,
  departmentSort: 999,
  // enabled: 'true'
}
export default {
  name: 'Dept',
  directives: { permission },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  components: {
    ...crudComps,
    DateRangePicker,
    Treeselect,
  },
  cruds() {
    return CRUD({ title: '部门', url: 'system/department/getList', crudMethod: { ...crudDept } })
  },
  data() {
    return {
      deptTableOptions,
      depts: [],
      rules: {
        departmentName: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        departmentSort: [
          {
            required: true,
            message: '请输入序号',
            trigger: 'blur',
            type: 'number',
          },
        ],
      },
      permission: {
        add: ['admin', 'system:department:add'],
        edit: ['admin', 'system:department:edit'],
        del: ['admin', 'system:department:del']
      }
      // enabledTypeOptions: [
      //     { key: 'true', display_name: '正常' },
      //     { key: 'false', display_name: '禁用' }
      // ],
    }
  },
  computed: {
    crudCU() {
      return this.crud.status.cu > 0
    },
  },
  methods: {
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
        this.getDepts(form.id)
    },
    // 提交前的验证
    [CRUD.HOOK.afterValidateCU]() {
      if (!this.form.parentId) {
        this.form.parentId = '0'
      }

      if (this.form.parentId !== null && this.form.parentId === this.form.id) {
        this.$message({
          message: '上级部门不能为自身',
          type: 'warning',
        })
        return false
      }
      return true
    },
    getDeptDatas(tree, treeNode, resolve) {
      const params = { id: tree.id }
      setTimeout(() => {
        crudDept.getDepts(params).then((res) => {
          resolve(res.data.content)
        })
      }, 100)
    },
    /**
     * 编辑时获取下拉框的菜单树
     * 接口获取的是完整数据（偷懒）
     */
    getSupDepts(id) {
      crudDept.getDeptsTree({ id: '0' }).then((res) => {
        const date = res.data.content
        this.buildDepts(date)
        this.depts = date
      })
    },
    buildDepts(depts) {
      depts.forEach((data) => {
        // if (!data.hasChildren) {
        //   delete data.children
        // }
        if (data.children) {
          this.buildDepts(data.children)
        }
        // if (data.hasChildren && !data.children) {
        //   data.children = null
        // }
      })
    },
    getDepts(cid) {
      crudDept.getParentTree({ id: cid }).then(res => {
        this.depts = res.data.content
      })
    },
    // 获取弹窗内部门数据
    loadDepts({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        crudDept.getDepts({ enabled: true, id: parentNode.id }).then((res) => {
          parentNode.children = res.data.content.map(function (obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 100)
        })
      }
    },
    // 改变状态
    changeEnabled(data, val) {
      this.$confirm(
        '此操作将 "' +
          this.dict.label.dept_status[val] +
          '" ' +
          data.departmentName +
          '部门, 是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          crudDept
            .edit(data)
            .then((res) => {
              this.crud.notify(
                this.dict.label.dept_status[val] + '成功',
                CRUD.NOTIFICATION_TYPE.SUCCESS
              )
            })
            .catch((err) => {
              data.enabled = !data.enabled
              console.log(err.response.data.message)
            })
        })
        .catch(() => {
          data.enabled = !data.enabled
        })
    },
    checkboxT(row, rowIndex) {
      // return row.id !== 1
      return true
    },
  },
}
</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>
