<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div>
        <el-tooltip class="item" effect="dark" content="注意，每次展开子类时都会应用此条件。例如" placement="bottom-start">
          <div slot="content">
            <div>注意：每次展开子类时都会应用此条件。</div>
            <br>
            <div>例如：想要查询“某某车间”下全部子部门</div>
            <div>1. 填写“车间”；</div>
            <div>2. 点“搜索”；</div>
            <div>3. 点“重置”，或删除文本框内容，不要点搜索；</div>
            <div>4. 展开“XX车间”。</div>
          </div>
          <el-input v-model="searchParam.nameLike" clearable size="small" placeholder="部门名称" style="width: 200px;" class="filter-item" />
        </el-tooltip>
        <el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="searchSubmit">搜索</el-button>
        <el-button class="filter-item" size="mini" type="warning" icon="el-icon-refresh-left" @click="searchParamReset">重置</el-button>
      </div>
      <el-button class="filter-item" size="mini" type="primary" icon="el-icon-plus" @click="doAdd(null)">新增</el-button>
    </div>
    <!--弹出框1-->
    <el-dialog append-to-body :close-on-click-modal="true" :visible.sync="dialog1Show" :title="editState==1?'新增':editState==2?'修改':'查看'" width="480px">
      <el-form ref="dialog1Form" :hide-required-asterisk="!dialog1Editing" :model="dialog1Data" :rules="dialog1Rules" size="mini" label-width="180px" style="margin-right: 80px;">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="部门名称：" prop="name">
              <span v-show="!dialog1Editing">{{ dialog1Data.name }}</span>
              <el-input v-show="dialog1Editing" v-model="dialog1Data.name" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="排序：" prop="orders">
              <span v-show="!dialog1Editing">{{ dialog1Data.orders }}</span>
              <el-input-number v-show="dialog1Editing" v-model="dialog1Data.orders" style="width:100%;" :min="0" :max="999999" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item v-show="editState==1&&dialog1Data.pid==0" label="部门：" prop="pid">
              <span>顶级部门</span>
            </el-form-item>
            <el-form-item v-show="editState==1&&dialog1Data.pid!=0" label="上级部门：" prop="pid">
              <span>{{ dialog1Data._pName }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div v-show="dialog1Editing" slot="footer" class="dialog-footer">
        <el-button type="text" @click="dialog1Show=false">取消</el-button>
        <el-button :loading="dialog1Saving" type="primary" @click="dialog1Submit">确认</el-button>
      </div>
    </el-dialog>
    <!--弹出框2-->
    <el-dialog append-to-body :close-on-click-modal="true" :visible.sync="dialog2Show" :title="'确认删除'" width="580px">
      <div>
        <span>确认要删除部门：</span><span style="font-weight: bold;">{{ dialog2Data.name }}</span><span>吗？</span>
      </div>
      <div>
        <span>注意：会连同下属部门一同删除！</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="dialog2Show=false">取消</el-button>
        <el-button :loading="dialog2Saving" type="primary" @click="dialog2Submit">确认</el-button>
      </div>
    </el-dialog>
    <!--表格-->
    <el-table ref="table" v-loading="searching" :data="tableData" row-key="id" lazy :load="loadTableChild" :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column :show-overflow-tooltip="true" prop="name" label="部门名称" width="600px" />
      <el-table-column :show-overflow-tooltip="true" prop="note" label="排序" align="orders" />
      <el-table-column label="操作" width="400px" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" round @click="doAdd(scope.row)">添加下级</el-button>
          <el-button size="mini" round @click="doEdit(scope.row.id,false)">查看</el-button>
          <el-button size="mini" round @click="doEdit(scope.row.id,true)">修改</el-button>
          <el-button size="mini" round @click="doDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import staffDepartmentApi from '@/api/kd/staffDepartment'
import { mapGetters } from 'vuex'
const searchParam = {// 默认搜索条件
  page: 1,
  count: 100, // 100个以代替全部，超出时先做提示处理
  searchCount: true
}
export default {
  name: 'EStaffDepartment', // 本页面名
  components: {},
  data() {
    return {
      selectedMine: {},
      searching: false,
      searchParam: {},
      searchResultList: [],
      dialog1Show: false,
      dialog1Editing: false,
      dialog1Saving: false,
      dialog1Data: {},
      dialog1Rules: {
        name: [
          { required: true, message: '请填写' }
        ],
        orders: [
          { required: true, message: '请填写' }
        ]
      },
      editState: 0, // （刚打开窗口时）记录了上次窗口作用；（保存编辑时）记录了当前窗口作用； 0无 1新增 2修改 3查看
      addingData: {}, // 上次正在新增时的内容，下次打开dialog1窗口时记录下来
      dialog2Show: false,
      dialog2Saving: false,
      dialog2Data: {}
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ]),
    tableData() {
      // 此处对返回值进行算法重组
      return this.searchResultList
    }
  },
  mounted() {
    const selectedMineJson = window.localStorage.getItem('kd.selected.mine')
    let noMine = false
    if (!selectedMineJson) {
      noMine = true
    } else {
      const selectedMine = JSON.parse(selectedMineJson)
      if (!selectedMine || selectedMine.enterpriseId !== this.user.enterpriseId) {
        noMine = true
      } else {
        this.selectedMine = selectedMine
      }
    }
       // if (noMine) {
    //   this.$message.error('当前未选择矿山')
    //   this.$router.replace('/dashboard')
    // }
    this.searchParamReset()
    this.searchSubmit()
  },
  methods: {
    searchParamReset() {
      this.searchParam = JSON.parse(JSON.stringify(searchParam))
    },
    searchSubmit() {
      this.searching = true
      this.searchParam.mineType = this.selectedMine.mineType
      this.searchParam.mineId = this.selectedMine.id
      this.searchParam.pid = 0
      staffDepartmentApi.getPage(this.searchParam).then(response => {
        this.searching = false
        if (response.total > this.searchParam.count) {
          this.$message.warning('顶级部门数量超过' + this.searchParam.count + '个！请联系管理员帮忙查询！')
        }
        response.results.forEach(r => {
          r.hasChildren = true
        })
        this.searchResultList = []
        this.$nextTick(() => {
          this.searchResultList = response.results
        })
      }).catch(() => {
        this.searching = false
      })
    },
    loadTableChild(tree, treeNode, resolve) {
      const searchParam = JSON.parse(JSON.stringify(this.searchParam))
      searchParam.pid = tree.id
      staffDepartmentApi.getPage(searchParam).then(response => {
        if (response.total > this.searchParam.count) {
          this.$message.warning(tree.name + '下属部门数量超过' + this.searchParam.count + '个！请联系管理员帮忙查询！')
        }
        response.results.forEach(r => {
          r.hasChildren = true
        })
        if (response.results.length === 0) {
          this.$set(tree, 'hasChildren', false)
        } else {
          resolve(response.results)
        }
      }).catch(() => {
        this.$set(tree, 'hasChildren', false)
      })
    },
    dialog1Submit() {
      this.$refs['dialog1Form'].validate(valid => {
        if (!valid) {
          return
        } else {
          this.dialog1Saving = true
          if (this.editState === 1) { // 新增
            this.dialog1Data.mineType = this.selectedMine.mineType
            this.dialog1Data.mineId = this.selectedMine.id
            staffDepartmentApi.add(this.dialog1Data).then(() => {
              this.dialog1Show = false
              this.$message.success('保存成功')
              setTimeout(() => { // 立即清除会导致输入框Validate一闪变红
                this.dialog1Data = {}
                this.dialog1Saving = false
              }, 500)
              this.searchSubmit()
            }).catch(() => {
              this.dialog1Saving = false
            })
          } else if (this.editState === 2) { // 修改
            staffDepartmentApi.set(this.dialog1Data).then(() => {
              this.dialog1Show = false
              this.$message.success('修改成功')
              setTimeout(() => { // 立即清除会导致输入框Validate一闪变红
                this.dialog1Data = {}
                this.dialog1Saving = false
              }, 500)
              this.searchSubmit()
            }).catch(() => {
              this.dialog1Saving = false
            })
          } else {
            this.$message.error('出错啦，请重试')
            this.dialog1Saving = false
          }
        }
      })
    },
    beforeDialog1Open() { // 窗口打开前的统一操作
      if (this.editState === 1) {
        this.addingData = this.dialog1Data
      }
    },
    doAdd(parent) {
      this.beforeDialog1Open()
      this.editState = 1
      this.dialog1Editing = true
      this.dialog1Data = this.addingData // 初始值：上次编辑的内容
      if (parent === null) {
        this.dialog1Data.pid = 0
      } else {
        this.dialog1Data.pid = parent.id
        this.dialog1Data._pName = parent.name
      }
      this.dialog1Show = true
      this.$nextTick(() => {
        this.$refs['dialog1Form'].clearValidate()
      })
    },
    doEdit(id, isEdit) {
      this.beforeDialog1Open()
      this.editState = isEdit ? 2 : 3
      staffDepartmentApi.getById(id).then(response => {
        this.dialog1Data = response
        this.dialog1Editing = isEdit
        this.dialog1Show = true
        this.$nextTick(() => {
          this.$refs['dialog1Form'].clearValidate()
        })
      }).catch(() => {
        this.searchSubmit()
      })
    },
    dialog2Submit() {
      this.dialog2Saving = true
      staffDepartmentApi.del(this.dialog2Data).then(() => {
        this.dialog2Show = false
        this.$message.success('删除成功')
        this.dialog2Data = {}
        this.dialog2Saving = false
        this.searchSubmit()
      }).catch(() => {
        this.dialog2Saving = false
      })
    },
    doDelete(id) {
      staffDepartmentApi.getById(id).then(response => {
        this.dialog2Data = response
        this.dialog2Show = true
      }).catch(() => {
        this.searchSubmit()
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  ::v-deep .el-input-number .el-input__inner {
    text-align: left;
  }
  ::v-deep .vue-treeselect__control,::v-deep .vue-treeselect__placeholder,::v-deep .vue-treeselect__single-value {
    height: 30px;
    line-height: 30px;
  }
</style>
