<template>
  <div class="icons-container">
    <el-container>
      <el-aside width="300px" style="background-color:#fff">
        <el-input
          v-model="filterText"
          placeholder="输入关键字进行过滤"
          style="margin:10px 0"/>
        <el-tree
          v-loading="treeLoading"
          ref="tree"
          :data="treeData"
          :props="defaultProps"
          :filter-node-method="filterNode"
          class="filter-tree"
          @node-click="handleNodeClick"/>
      </el-aside>
      <el-main>
        <el-table
          v-loading="listLoading"
          ref="multipleTable"
          :data="varList"
          :header-cell-style="{
            'font-weight': 'bold',
            'color': '#000'
          }"
          tooltip-effect="dark"
          border
          fit
          highlight-current-row
        >
          <el-table-column type="index" prop="numb" label="序号" width="50" align="center" />
          <el-table-column label="名称" >
            <template slot-scope="{row}">
              <div class="link-type" @click="getList(row.DEPARTMENT_ID)">{{ row.NAME }}</div>
            </template>
          </el-table-column>
          <el-table-column v-if="DEPARTMENT_ID != '0'" prop="HEADMAN" label="负责人"/>
          <el-table-column v-if="DEPARTMENT_ID != '0'" :formatter="(row) => formatStateLabel(row)" prop="DEPT_LEVEL" label="部门级别"/>
          <el-table-column v-if="DEPARTMENT_ID != '0'" prop="DEPT_SORT" label="排序" width="100" />
          <el-table-column v-if="DEPARTMENT_ID != '0'" label="操作" align="center" width="190">
            <template slot-scope="{row}">
              <el-button v-show="edit" type="primary" icon="el-icon-edit" size="mini" @click="handleEdit(row.DEPARTMENT_ID)">编辑</el-button>
              <el-button v-show="del" type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(row.DEPARTMENT_ID, row.NAME)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="page-btn-group">
          <div>
            <el-button v-show="DEPARTMENT_ID != '0' && add" type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
            <el-button v-show="DEPARTMENT_ID != '0'" icon="el-icon-arrow-left" @click="getList(form.PARENT_ID)">返回</el-button>
          </div>
          <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList()" />
        </div>
      </el-main>
    </el-container>

    <el-dialog v-if="dialogFormAdd" :visible.sync="dialogFormAdd" :title="dialogType==='edit'?'修改':'新增'" width="600px">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px" style="width: 500px;margin: auto">
        <el-tag class="mark_up" size="medium">上级部门：{{ DEPARTMENT_ID == '0' ?'(无) 此项为顶级部门':pds.NAME }}</el-tag>
        <el-form-item label="部门名称" prop="NAME">
          <el-input v-model="form.NAME" placeholder="这里输入部门名称..." />
        </el-form-item>
        <el-form-item label="部门级别" prop="DEPT_LEVEL">
          <el-select v-model="form.DEPT_LEVEL" placeholder="请选择" style="width: 100%;">
            <el-option v-for="item in levelList" :key="item.BIANMA" :label="item.NAME" :value="item.BIANMA" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门排序" prop="DEPT_SORT">
          <el-input v-model.number="form.DEPT_SORT" placeholder="这里输入部门排序..." />
        </el-form-item>
        <el-form-item label="负责人" prop="HEADMAN">
          <el-input v-model="form.HEADMAN" placeholder="这里输入负责人..." />
        </el-form-item>
        <el-form-item label="电话" prop="TEL">
          <el-input v-model="form.TEL" placeholder="这里输入部门电话..." />
        </el-form-item>
        <el-form-item label="部门职能">
          <el-input :rows="3" v-model="form.FUNCTIONS" type="textarea" placeholder="这里输入部门职能..." />
        </el-form-item>
        <el-form-item label="备注">
          <el-input :rows="3" v-model="form.BZ" type="textarea" placeholder="这里输入备注..." />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormAdd = false">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog v-if="dialogGraph" :visible.sync="dialogGraph" title="组织机构结构图" width="80%" top="0">
      <div v-if="dialogGraph" style="height:calc(100vh - 100px);">
        <SeeksRelationGraph
          ref="seeksRelationGraph"
          :options="graphOptions"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>

import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import { requestFN } from '@/utils/request'
import SelectTree from '@/components/SelectTree'
import SeeksRelationGraph from 'relation-graph'

export default {
  name: 'Icons',
  components: { Pagination, SelectTree, SeeksRelationGraph },
  data() {
    var isChecked = (rule, value, callback) => {
      if (this.form.IS_REGULATORY == '1') {
        if (!this.form.MAIN_DEPARTMENT || this.form.MAIN_DEPARTMENT == '') {
          callback(new Error('请选择要监管的部门'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      loading: false,
      defaultProps: {
        children: 'nodes',
        label: 'name',
        value: 'id'
      },
      graphOptions: {
        disableDragNode: 'false',
        layouts: [
          {
            label: '中心',
            layoutName: 'tree',
            layoutClassName: 'seeks-layout-center',
            defaultJunctionPoint: 'border',
            defaultNodeShape: 0,
            defaultLineShape: 1,
            min_per_width: 40,
            max_per_width: 70,
            min_per_height: 200
          }
        ],
        defaultLineMarker: {
          markerWidth: 12,
          markerHeight: 12,
          refX: 6,
          refY: 6,
          data: 'M2,2 L10,6 L2,10 L6,6 L2,2'
        },
        defaultNodeShape: 1,
        defaultLineShape: 2,
        defaultJunctionPoint: 'tb',
        defaultNodeBorderWidth: 0,
        defaultLineColor: 'rgba(0, 186, 189, 1)',
        defaultNodeColor: 'rgba(0, 206, 209, 1)',
        defaultNodeHeight: 150,
        defaultNodeWidth: 60
      },
      listLoading: false,			// 加载状态
      treeLoading: false,
      radio: 1,
      dialogFormAdd: false,
      dialogEditIcon: false,
      dialogGraph: false,
      dialogType: 'add',
      // 树形部门
      filterText: '',
      treeData: [],
      // 列表
      varList: [],	// list
      DEPARTMENT_ID: '0',	// 主键ID
      PARENT_ID: '0',				// 上级ID
      CORPINFO_ID: '',
      listQuery: {
        page: 1,
        limit: 10
      },
      total: 0,
      pd: [],
      form: {
        DEPARTMENT_ID: '',	 // 主键ID
        CORPINFO_ID: '',	 // 主键ID
        PARENT_ID: '',
        NAME: '',
        DEPT_LEVEL: '',
        DEPT_SORT: '',	 //
        HEADMAN: '',	 //
        TEL: '',	 //
        FUNCTIONS: '', //
        BZ: '', //
        IS_REGULATORY: '0',
        checkedIds: '',
        MAIN_DEPARTMENT: ''
      },
      pds: [],
      levelList: [],
      add: false,
      del: false,
      edit: false,
      rules: {
        NAME: [
          { required: true, message: '部门名称不能为空', trigger: 'change' }
        ],
        DEPT_LEVEL: [
          { required: true, message: '部门级别不能为空', trigger: 'change' }
        ],
        DEPT_SORT: [
          { required: true, message: '部门序号不能为空', trigger: 'change' },
          { type: 'number', message: '部门序号必须为数字' }
        ],
        HEADMAN: [
          { required: true, message: '负责人不能为空', trigger: 'change' }
        ],
        TEL: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入11位手机号码', trigger: 'blur' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '请输入正确的手机号码'
          }
        ],
        FUNCTIONS: [
          { required: true, message: '部门职能不能为空', trigger: 'change' }
        ],

        IS_REGULATORY: [{ required: true, message: '是否监管部门不能为空', trigger: 'blur' }],
        MAIN_DEPARTMENT: [
          { validator: isChecked, trigger: 'change' }
        ]
      },

      decheckedIds: []
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.CORPINFO_ID = JSON.parse(sessionStorage.getItem('user')).CORPINFO_ID
    this.getTreeList()
    this.getList(this.DEPARTMENT_ID)
    this.getDict()
  },
  methods: {
    // 转换企业状态
    formatStateLabel(row) {
      const level = row.DEPT_LEVEL
      if (level) {
        if (level === 'departmentLevel0001') {
          return '厂级'
        } else if (level === 'departmentLevel0002') {
          return '车间级'
        } else if (level === 'departmentLevel0003') {
          return '班组级'
        }
      }
      return level
    },
    recursion(data) {
      var arr = []
      for (let i = 0; i < data.length; i++) {
        if (data[i].nodes && data[i].nodes.length > 0) {
          arr.push(data[i])
          arr = arr.concat(this.recursion(data[i].nodes))
        } else {
          arr.push(data[i])
        }
      }
      return arr
    },
    showGraph() {
      this.dialogGraph = true
      this.$nextTick(() => {
        this.showSeeksGraph()
      })
    },
    showSeeksGraph() {
      var treeData = this.recursion(this.treeData)
      var __graph_json_data = {
        rootId: this.treeData[0].name,
        nodes: [],
        links: []
      }
      for (let i = 0; i < treeData.length; i++) {
        if (i === 0) {
          __graph_json_data.nodes.push(
            { 'id': treeData[i].name,
              'text': treeData[i].name,
              width: 150,
              height: 60
            }
          )
        } else {
          __graph_json_data.nodes.push({ 'id': treeData[i].name, 'text': treeData[i].name })
        }
        for (let j = 0; j < treeData.length; j++) {
          if (treeData[i].id === treeData[j].pId) {
            __graph_json_data.links.push({ 'from': treeData[i].name, 'to': treeData[j].name })
          }
        }
      }
      this.$refs.seeksRelationGraph.setJsonData(__graph_json_data, (seeksRGGraph) => {
        // 这些写上当图谱初始化完成后需要执行的代码
      })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    handleNodeClick(node, data, value) {
      this.form.PARENT_ID = node.id
      this.DEPARTMENT_ID = node.id
      this.getList(node.id)
    },

    changeIssup(e) {
      // 第一次选择监管部门。初始化选择本部门
      if (e == '1' && (this.form.checkedIds == undefined || this.form.checkedIds == null || this.form.checkedIds.length == 0)) {
        var ids = []
        if (this.dialogType == 'add') {
          ids.push(JSON.parse(sessionStorage.getItem('user')).DEPARTMENT_ID)
          this.$nextTick(() => {
            this.$refs.treeSelect.loadCheckedKeys(ids)
          })
        } else {
          ids = [this.form.DEPARTMENT_ID]
          this.$nextTick(() => {
            this.$refs.treeSelect.loadCheckedKeys(ids)
          })
        }
      }
    },
    handleAdd() {
      this.dialogType = 'add'
      this.resetForm()
      requestFN(
        '/department/goAdd',
        {
          DEPARTMENT_ID: this.DEPARTMENT_ID
        }
      ).then((data) => {
        this.form.PARENT_ID = this.DEPARTMENT_ID
        this.pds = data.pds	|| []					// 父级部门信息
      }).catch((e) => {

      })
      this.dialogFormAdd = true

      this.treeData[0].disabled = true
    },
    handleEdit(DEPARTMENT_ID) {
      this.resetForm()
      this.dialogType = 'edit'
      requestFN(
        '/department/goEdit',
        {
          DEPARTMENT_ID: DEPARTMENT_ID
        }
      ).then((data) => {
        this.form = Object.assign({}, data.pd) // copy obj
        this.form.DEPT_SORT = Number(this.form.DEPT_SORT)
        this.pds = data.pds || []						// 父级部门信息

        this.dialogFormAdd = true
        this.decheckedIds = data.varlist.map(item => {
          // var node = this.$refs.tree.getNode(item)
          return item.SUB_DEPARTMENT_ID
        })
        this.$nextTick(() => {
          this.$refs.treeSelect.loadCheckedKeys(this.decheckedIds)
        })
        this.treeData[0].disabled = true
      }).catch((e) => {
        this.listLoading = false
      })
    },
    confirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.listLoading = true
          this.loading = true
          this.form.CORPINFO_ID = JSON.parse(sessionStorage.getItem('user')).CORPINFO_ID
          // console.log(this.form)
          requestFN(
            '/department/' + this.dialogType,
            this.form
          ).then((data) => {
            this.listLoading = false
            this.loading = false
            this.dialogFormAdd = false
            this.getTreeList()
            this.getList(this.DEPARTMENT_ID)
          }).catch((e) => {
            this.listLoading = false
            this.loading = false
          })
        } else {
          return false
        }
      })
    },
    handleDelete(id, name) {
      this.$confirm('确定要删除[' + name + ']吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/department/delete',
          {
            DEPARTMENT_ID: id
          }
        ).then((data) => {
          if (data.result === 'fail') {
            this.$message.error('包含下级部门，删除失败')
          } else {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getTreeList()
            this.getList(this.DEPARTMENT_ID)
          }
          this.listLoading = false
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },

    handleTreeSelected(checkedIds, checkedData) {
      this.form.checkedIds = checkedIds.join(',')
    },
    getTreeList() {
      this.treeLoading = true
      requestFN(
        '/department/listzTree',
        {}
      ).then((data) => {
        this.treeLoading = false
        this.treeData = JSON.parse(data.zTreeNodes)
      }).catch((e) => {
        this.treeLoading = false
      })
    },
    getList(DEPARTMENT_ID) {
      this.listLoading = true
      this.varList = []
      if (DEPARTMENT_ID) {
        this.DEPARTMENT_ID = DEPARTMENT_ID
      }
      requestFN(
        '/department/list?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          DEPARTMENT_ID: this.DEPARTMENT_ID,
          CORPINFO_ID: this.CORPINFO_ID,
          KEYWORDS: this.KEYWORDS
        }
      ).then((data) => {
        this.listLoading = false
        this.varList = data.varList
        this.form.PARENT_ID = data.PARENT_ID
        this.total = data.page.totalResult
        this.hasButton()
      }).catch((e) => {
        this.listLoading = false
      })
    },
    resetForm() {
      this.form = {
        DEPARTMENT_ID: '',	 // 主键ID
        PARENT_ID: '',
        NAME: '',
        DEPT_LEVEL: '',
        DEPT_SORT: '',	 //
        HEADMAN: '',	 //
        TEL: '',	 //
        FUNCTIONS: '', //
        BZ: '', //
        IS_REGULATORY: '0',
        checkedIds: ''
      }
    },
    // 获取数据字典数据
    getDict() {
      requestFN(
        'dictionaries/getLevels',
        { DICTIONARIES_ID: '4a661fa8aedc4d158c9cddaa9d2ec47e' }
      ).then((data) => {
        this.levelList = data.list
      }).catch((e) => {
        this.listLoading = false
      })
    },
    hasButton: function() {
      var keys = 'department:add,department:del,department:edit'
      requestFN(
        '/head/hasButton',
        {
          keys: keys
        }
      ).then((data) => {
        this.add = data.departmentfhadminadd
        this.del = data.departmentfhadmindel
        this.edit = data.departmentfhadminedit
      }).catch((e) => {
        this.listLoading = false
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.el-dialog__body{
  padding: 0;
  background: red;
}
.mark_up{
  margin-bottom:20px;
  margin-left: 110px;
}
.icons-container {
  margin: 0;
  overflow: hidden;

  .grid {
    position: relative;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  }

  .icon-item {
    margin-bottom: 10px;
    height: 70px;
    text-align: center;
    width: 100px;
    float: left;
    font-size: 24px;
    color: #24292e;
    cursor: pointer;
    span {
      display: block;
      font-size: 14px;
      margin-top: 10px;
    }

  }

  .disabled {
    pointer-events: none;
  }
}
</style>
