<template>
  <div>
    <el-card class="no-bottom">
      <el-form
        ref="form"
        :model="form"
        label-width="80px"
        inline
      >
        <el-form-item
          label="部门名称:"
          prop="input"
        >
          <el-input v-model="form.input" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="margin-top-20">
      <div class="buttons-group" style="margin-bottom: 20px">
        <el-button v-permission="'OrgMgr_add'" type="primary" icon="el-icon-plus" @click="showAddRow">增加部门</el-button>
      </div>

      <el-table
        ref="tableData"
        :data="tableData"
        border
        row-key="id"
        default-expand-all
        :expand-row-keys="expandRowKeys"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
        <el-table-column
          type="index"
          label="序号"
          width="50px"
          align="center"
        />
        <el-table-column
          prop="departmentName"
          label="部门名称"
          min-width="160px"
        />
        <el-table-column
          prop="principal"
          label="负责人"
        />
        <el-table-column
          prop="phone"
          label="电话"
        />
        <el-table-column
          prop="remark"
          label="备注"
        />
        <el-table-column
          label="操作"
          width="140px"
          align="center"
        >
          <template slot-scope="props">
            <el-button
              v-permission="'OrgMgr_update'"
              :disabled="props.row.category === '0'"
              type="text"
              @click="editItem(props.row.id)"
            >编辑</el-button>
            <el-popconfirm
              v-permission="'OrgMgr_delete'"
              title="确定要删除此条记录吗？"
              :disabled="props.row.category === '0'"
              @onConfirm="deleteItem(props.row.id)"
            >
              <el-button
                slot="reference"
                v-permission="'OrgMgr_delete'"
                :disabled="props.row.category === '0'"
                type="text"
              >删除</el-button>
            </el-popconfirm>
            <el-button
              v-permission="'OrgMgr_info'"
              type="text"
              @click="checkDetail(props.row)"
            >查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      :title="add ? '增加部门' : '编辑部门'"
      :visible.sync="dialogVisible"
      width="700px"
    >
      <el-form
        ref="addForm"
        :model="addForm"
        label-width="90px"
        :rules="rules"
      >
        <el-form-item
          label="部门名称:"
          prop="departmentName"
        >
          <el-input v-model="addForm.departmentName" />
        </el-form-item>
        <el-form-item
          v-if="treeShow"
          label="上级部门:"
          prop="parentId"
        >
          <div>
            <el-tree
              ref="tree"
              :data="organizationList"
              :props="defaultProps"
              default-expand-all
              highlight-current
              node-key="id"
              check-strictly
              show-checkbox
              :default-checked-keys="defaultCheckedKeys"
              @check-change="handleCheckChange"
              @node-click="handleNodeClick"
            />
          </div>
        </el-form-item>
        <el-form-item
          label="负责人:"
          prop="principal"
        >
          <el-input v-model="addForm.principal" />
        </el-form-item>
        <el-form-item
          label="电话:"
          prop="phone"
        >
          <el-input v-model="addForm.phone" />
        </el-form-item>
        <el-form-item
          label="排序:"
          prop="orderNum"
        >
          <el-input-number
            v-model="addForm.orderNum"
            :min="1"
            :max="10"
            label="描述文字"
          />
        </el-form-item>
        <el-form-item
          label="备注:"
          prop="remark"
        >
          <el-input
            v-model="addForm.remark"
            type="textarea"
            maxlength="300"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRow">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="查看详情"
      :visible.sync="detailDialog"
      width="700px"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="descriptionItem">
            <div class="descriptionLabel">部门名称:</div>
            <div class="descriptionContent">{{ detail.departmentName }}</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="descriptionItem">
            <div class="descriptionLabel">分类:</div>
            <div class="descriptionContent">{{ tagName(detail) }}</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="descriptionItem">
            <div class="descriptionLabel">负责人:</div>
            <div class="descriptionContent">{{ detail.principal }}</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="descriptionItem">
            <div class="descriptionLabel">电话:</div>
            <div class="descriptionContent">{{ detail.phone }}</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="descriptionItem">
            <div class="descriptionLabel">人数:</div>
            <div class="descriptionContent">{{ detail.userCount }}</div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="descriptionItem">
            <div class="descriptionLabel">备注:</div>
            <div class="descriptionContent">{{ detail.remark }}</div>
          </div>
        </el-col>
      </el-row>
      <span slot="footer">
        <div class="buttons-group" style="text-align: center">
          <el-button type="primary" @click="detailDialog = false">确 定</el-button>
        </div>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
import {
  listTree,
  save,
  deleteRow,
  info,
  update,
  chooseList
} from '@/api/system-management/organization-management'

export default {
  name: 'OrganizationManagement',
  data() {
    return {
      form: {
        input: null,
        category: null
      },
      tableData: [],
      expandAll: true,
      expandRowKeys: [],
      addForm: {
        departmentName: null,
        parentId: null,
        category: null,
        principal: null,
        phone: null,
        remark: null,
        orderNum: null
      },
      dialogVisible: false,
      add: true,
      treeShow: true,
      organizationList: [],
      defaultProps: {
        children: 'children',
        label: 'departmentName'
      },
      currentNodeKey: null,
      defaultCheckedKeys: [],
      rules: {
        departmentName: [
          { required: true, message: '请输入组织名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择分类', trigger: 'blur' }
        ],
        parentId: [
          { required: true, message: '请选择上级部门', trigger: 'blur' }
        ],
        orderNum: [
          { required: true, message: '请输入显示排序', trigger: 'blur' }
        ]
      },
      detailDialog: false,
      detail: {
        departmentName: null,
        parentId: null,
        category: null,
        principal: null,
        phone: null,
        remark: null,
        orderNum: null,
        userCount: null
      }
    }
  },
  created() {
    this.getOrganizationList()
  },
  methods: {
    checkDetail(row) {
      this.detail = row
      this.detailDialog = true
    },
    handleCheckChange(data, checked, indeterminate) {
      if (checked === true) {
        this.addForm.parentId = data.id
        this.$refs.tree.setCheckedNodes([data])
      }
    },
    handleNodeClick(data, checked, node) {
      this.addForm.parentId = data.id
      this.$refs.tree.setCheckedNodes([data])
    },
    addRow() {
      this.$refs.addForm.validate()
        .then(_ => {
          if (this.add) {
            save(this.addForm)
              .then(res => {
                this.$message.success('操作成功')
                this.getOrganizationList()
                this.dialogVisible = false
              })
              .catch(err => {
                this.$message.error('操作失败')
                console.error(err.message)
              })
          } else {
            const params = {
              ...this.addForm,
              id: this.currentRow
            }
            update(params)
              .then(res => {
                this.$message.success('操作成功')
                this.getOrganizationList()
                this.dialogVisible = false
              })
              .catch(err => {
                this.$message.error('操作失败')
                console.error(err.message)
              })
          }
        })
        .catch(_ => {})
    },
    tagType(data) {
      const typeName = {
        '1': 'danger',
        '2': '',
        '3': 'success'
      }
      return typeName[data.category]
    },
    tagName(data) {
      const tagName = {
        '1': '集团',
        '2': '分公司',
        '3': '部门'
      }
      return tagName[data.category]
    },
    getOrganizationList() {
      listTree({ parentId: 0 })
        .then(res => {
          const { data } = res
          this.tableData = data
        })
        .catch(err => {
          this.$message.error('操作失败')
          console.error(err.message)
        })
    },
    resetForm() {
      this.$refs['form'].resetFields()
    },
    doExpandAll(arg) {
      if (arg) {
        this.expandRowKeys = ['1']
      } else {
        this.expandRowKeys = []
      }
    },
    search() {
      // 获取完整数据
      listTree({ parentId: 0 })
        .then(res => {
          const { data } = res
          this.tableData = data
          // 过滤关键字
          let filter = (this.form.input === null) ? this.tableData : this.filter(this.tableData)
          // 返回一维数组
          const flatten = (this.form.category === null) ? filter : this.flatten(filter)
          // 过滤分类
          filter = (this.form.category === null) ? flatten : _.filter(flatten, v => v.category === this.form.category)
          this.tableData = (this.form.input === null) ? filter : this.filter(filter)
        })
        .catch(err => {
          this.$message.error('操作失败')
          console.error(err.message)
        })
    },
    flatten(array) {
      const arr = []
      array.forEach(v => {
        arr.push(v)
        if (v.children && v.category !== this.form.category) {
          arr.push(...this.flatten(v.children))
        }
      })
      return arr
    },
    filter(array) {
      const arr = []
      array.forEach(v => {
        if (v.departmentName.indexOf(this.form.input) >= 0) {
          arr.push(v)
        } else if (v.children) {
          arr.push(...this.filter(v.children))
        }
      })
      return arr
    },
    showAddRow() {
      this.treeShow = true
      chooseList({ departmentId: '' })
        .then(res => {
          const { data } = res
          this.organizationList = data
          this.dialogVisible = true
          this.add = true
          this.addForm = {
            departmentName: null,
            parentId: null,
            category: null,
            principal: null,
            phone: null,
            remark: null,
            orderNum: null
          }
          this.defaultCheckedKeys = []
        })
        .catch(err => {
          this.$message.error('操作失败')
          console.error(err.message)
        })
    },
    editItem(id) {
      this.currentRow = id
      chooseList({ departmentId: id })
        .then(res => {
          const { data } = res
          this.organizationList = data
        })
        .then(_ => info({ departmentId: id }))
        .then(res => {
          const { data } = res
          const { departmentName, parentId, category, principal, phone, remark, orderNum } = data
          this.addForm = {
            departmentName,
            parentId,
            category,
            principal,
            phone,
            remark,
            orderNum
          }
          this.defaultCheckedKeys = [parentId]
          this.dialogVisible = true
          this.add = false
        })
        .catch(err => {
          this.$message.error('操作失败')
          console.error(err.message)
        })
    },
    deleteItem(id) {
      deleteRow({ departmentId: id })
        .then(res => {
          this.$message.success('操作成功')
          this.getOrganizationList()
        })
        .catch(err => {
          this.$message.error('操作失败')
          console.error(err.message)
        })
    }
  }
}
</script>

<style scoped lang="scss">
  .descriptionItem{
    padding-bottom: 16px;
    .descriptionLabel{
      display: inline-block;
      color: rgba(0, 0, 0, 0.85);
      font-weight: normal;
      font-size: 14px;
      line-height: 1.5;
      white-space: nowrap;
      width: 90px;
    }
    .descriptionContent{
      display: inline-block;
      color: rgba(0, 0, 0, 0.65);
      font-size: 14px;
      line-height: 1.5;
    }
  }

</style>
