<template>
  <div>
    <el-row class="handle-box" style="margin-bottom: 10px">
      <el-col :span="24">
        <el-radio-group v-model="deptGroup" size="small" @change="initData">
          <el-radio-button v-for="item in GroupDataAll" :key="item.value" :label="item.value" size="small">{{ item.label }}</el-radio-button>
        </el-radio-group> &nbsp;&nbsp;
        <el-select v-model="deptAttr" clearable filterable placeholder="组织架构类型" size="small" @change="initData">
          <el-option v-for="item in DeptAttrDataAll" :key="item.value" :label="item.label" :value="item.value" />
        </el-select> &nbsp;&nbsp;
        <el-input v-model="deptName" class="ch-input ch-input-size" placeholder="部门名称" size="small" @keyup.enter.native="handleSearch()" /> &nbsp;&nbsp;
        <el-button class="ch-button" size="small" style="float: right; margin-top: 4px;margin-left: 10px;" @click="handleAdd()"><i class="el-icon-menu" />&nbsp;新增</el-button>
        <el-button class="ch-button-export" size="small" style="float: right; margin-top: 4px;margin-right: 10px;" @click="confirmOutput()"><i class="el-icon-download" />&nbsp;导出</el-button>
        <el-button class="ch-button" size="small" style="float: right; margin-top: 4px;margin-right: 10px;" @click="handleSearch()"><i class="el-icon-search" />&nbsp;搜索</el-button>
        <el-button class="ch-button-warning" size="small" style="float: right; margin-top: 4px;margin-right: 10px;" @click="handleReset()"><i class="el-icon-refresh" />&nbsp;重置</el-button>
      </el-col>
    </el-row>
    <div class="custom-tree-container">
      <div class="block-l">
        <el-card shadow="hover">
          <el-tag class="full space-vertical">当前所选：{{ selectDeptNode.name || '暂无' }}</el-tag>
          <el-tree
            ref="selectTree"
            :data="DeptTree"
            :default-expanded-keys="expandedDeptKey"
            :expand-on-click-node="expandDeptClick"
            :indent="deptTreeIndent"
            accordion
            node-key="id"
            @node-click="handleDeptNodeClick"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span>
                <i v-if="data.level == 0" class="el-icon-s-home" />
                <i v-else-if="data.level == 1" class="el-icon-menu" />
                <i v-else class="el-icon-link" />
                {{ node.label }}
              </span>
              <span v-if="data.level == 0">
                <el-link class="space" type="primary" @click="() => unFoldAll()">展开</el-link>
                <el-link class="space" type="primary" @click="() => collapseAll()">折叠</el-link>
              </span>
            </span>
          </el-tree>
        </el-card>
      </div>
      <div class="block-r">
        <el-row class="handle-box">
          <el-col :span="24">
            <el-table v-loading="loading" :data="AllData" :max-height="tableMax" row-class-name="g_table_row" stripe>
              <el-table-column type="index" width="60" />
              <el-table-column label="部门名称" prop="deptName" />
              <el-table-column v-if="!currGroup" align="center" header-align="center" label="所属组织" prop="groupStr" />
              <el-table-column align="center" header-align="center" label="组织架构类型" prop="deptAttrStr" />
              <el-table-column align="center" header-align="center" label="顺序号" prop="deptOrder" />
              <el-table-column align="center" header-align="center" label="操作" width="160">
                <template scope="scope">
                  <el-link v-if="scope.row.deptLevel!==0" :underline="false" type="primary" @click="handleEdit(scope.row)">编辑&nbsp;</el-link>
                  <el-link v-if="scope.row.deptLevel!==0" :underline="false" type="danger" @click="handleDelete(scope.row)">删除&nbsp;</el-link>
                </template>
              </el-table-column>
            </el-table>
            <div class="table-page">
              <el-pagination
                :current-page.sync="currentPage"
                :page-size="pageSize"
                :total="allpage"
                background
                layout="total, prev, pager, next"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <el-dialog v-dialogDrag :title="dialogTitle" :visible.sync="dialogVisible" append-to-body top="50px" width="75%" @open="dlgOpen">
      <el-form ref="form" :model="form" :rules="rules" style="width: 100%;padding: 5px">
        <el-row>
          <el-col style="padding-bottom: 10px">
            <el-card shadow="always" style="padding: 15px 5px 5px 15px">
              <el-row>
                <el-col :span="4" class="col-txt"><span>上级部门</span></el-col>
                <el-col :span="20" class="col-input">
                  <el-form-item>
                    <el-cascader
                      v-model="form.parentId"
                      :options="DeptTree"
                      :props="{ checkStrictly: true }"
                      class="full"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="4" class="col-txt"><span>顺序号</span></el-col>
                <el-col :span="20" class="col-input">
                  <el-form-item>
                    <el-input v-model="form.deptOrder" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="4" class="col-txt"><span>部门名称</span></el-col>
                <el-col :span="20" class="col-input">
                  <el-form-item>
                    <el-input v-model="form.deptName" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="4" class="col-txt"><span>部门编码</span></el-col>
                <el-col :span="20" class="col-input">
                  <el-form-item>
                    <el-input v-model="form.deptCode" :disabled="form.deptCode==='TOP'" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="!currGroup">
                <el-col :span="4" class="col-txt"><span>所属组织</span></el-col>
                <el-col :span="20" class="col-input">
                  <el-form-item>
                    <el-select v-model="form.groupId" clearable filterable placeholder="所属组织">
                      <el-option
                        v-for="item in GroupData"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="4" class="col-txt"><span>部门负责人</span></el-col>
                <el-col :span="20" class="col-input">
                  <el-form-item>
                    <el-select v-model="form.chargedBy" clearable filterable multiple placeholder="部门负责人">
                      <el-option
                        v-for="item in StaffData"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="!isAdd || (isAdd && !selectDeptNode.id)">
                <el-col :span="4" class="col-txt"><span>组织架构类型</span></el-col>
                <el-col :span="20" class="col-input">
                  <el-form-item>
                    <el-select v-model="form.deptAttr" clearable filterable placeholder="组织架构类型">
                      <el-option
                        v-for="item in DeptAttrData"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSubmit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Base from '../base/base'
import BaseData from '../base/baseData'
import BaseDept from '../base/baseDept'
import '../../assets/drag'

export default {
    name: 'Department',
    mixins: [Base, BaseData, BaseDept],
    data() {
        return {
            // 列表相关
            deptGroup: '',
            deptAttr: '',
            deptName: '',
            AllData: [],
            loading: false,
            topId: '0',
            // 弹框相关
            dialogVisible: false,
            dialogTitle: '新增',
            isAdd: true,
            // selectParent: [],
            form: this.initForm(),
            rules: {},

            // 判定组织
            currGroup: ''
        }
    },
    mounted() {
        this.initDeptAttr({}, true)
        this.currGroup = this.$common.currUser().groupId
        this.initStaff()
        this.initGroup({}, !this.currGroup).then(() => {
            this.deptGroup = this.GroupDataAll.length > 0 ? this.GroupDataAll[0].value : ''
            this.selectDeptNode = {}
            this.initData()
        })
    },
    methods: {
        initData: function() {
            this.initDepartment({
                groupId: this.deptGroup,
                deptName: this.deptName,
                deptAttr: this.deptAttr
            }).then(() => {
                if (this.selectDeptNode.id) {
                    this.expandedDeptKey = []
                    this.expandedDeptKey.push(this.selectDeptNode.id)
                }
                //console.log('初始化', this.selectDeptNode)
                this.getData()
            })
        },
        handleDelete: function(row){
          // //console.log("row_：", row);
          this.pubRequest("getSubset", {id: row.id}).then((res) => {
            if(res.data.data > 0){
              this.$message({
                message: '已绑定下级，无法删除！',
                type: 'warning'
              });
            }else{
              this.handleDel(row)
            }
          }).catch(() => {
          })
        },
        getData: function() {
            const _this = this
            _this.loading = true
            _this.AllData = []

            const postData = this.getPostData()
            this.baseRequest('list', postData).then((res) => {
                if (res.data.rows) {
                    res.data.rows.forEach(function(item) {
                        const json = _this.getItemJson(item)
                        _this.AllData.push(json)
                    })
                    _this.allpage = res.data.total
                }
                _this.loading = false
            }).catch(() => {
            })

            this.initOutData()
        },
        handleSearch: function() {
            this.initData()
        },
        handleReset: function() {
            this.deptName = ''
            this.deptAttr = ''

            // this.initDeptTopNodeSelect(this.topId)
            this.selectDeptNode = {}
            this.handleSearch()
        },
        initOutData: function() {
            const _this = this
            this.OutData = []
            const title = []
            title.push('部门名称')
            title.push('所属组织')
            title.push('部门编码')
            title.push('顺序号')
            title.push('架构类型')
            this.OutData.push(title)

            const postData = this.getPostData()
            this.baseRequest('listAll', postData).then((res) => {
                if (res.data) {
                    res.data.forEach(function(item) {
                        const jsonMap = _this.getItemJson(item)
                        const jsonArray = []
                        jsonArray.push(jsonMap.deptName)

                        jsonArray.push(jsonMap.groupStr)

                        jsonArray.push(jsonMap.deptCode)
                        jsonArray.push(jsonMap.deptOrder)
                        jsonArray.push(jsonMap.deptAttrStr)

                        _this.OutData.push(jsonArray)
                    })
                }
            }).catch(() => {
            })
        },
        getPostData: function() {
            return {
                parentId: this.selectDeptNode.id === '0' ? '' : this.selectDeptNode.id,
                groupId: this.deptGroup,
                deptName: this.deptName,
                deptAttr: this.deptAttr,
                pageNum: this.currentPage,
                pageSize: this.pageSize
            }
        },
        getItemJson: function(item) {
            const attrs = item.deptAttr ? item.deptAttr.split(',') : []
            if (attrs.length > 0) {
                const attrStr = []
                attrs.forEach(attr => {
                    attrStr.push(this.DeptAttrMap[attr])
                })
                item.deptAttrStr = attrStr.join(',')
            }
            const groupIds = item.groupId ? item.groupId.split(',') : []
            if (groupIds.length > 0) {
                const groupStr = []
                groupIds.forEach(groupId => {
                    groupStr.push(this.GroupMap[groupId])
                })
                item.groupStr = groupStr.join(',')
            }
            return item
        },
        initForm: function(_selectNode) {
            // this.selectParent = _selectNode ? [_selectNode.id] : []
            //console.log('_selectNode', _selectNode)
            return {
                id: '',
                deptName: '',
                deptCode: '',
                deptOrder: 0,
                parentId: _selectNode ? (_selectNode.id ? _selectNode.id : '0') : '0',
                parentName: _selectNode ? _selectNode.name : '',
                deptLevel: _selectNode ? (_selectNode.level ? _selectNode.level + 1 : 1) : 1,
                deptAttr: _selectNode ? _selectNode.deptAttr : '',
                groupId: _selectNode ? (_selectNode.groupId ? _selectNode.groupId : this.currGroup) : this.currGroup,
                chargedBy: []
            }
        },
        // initDeptTopNodeSelect: function(_deptId) {
        //     return this.getDeptTopNode(_deptId).then(topNode => {
        //         if (topNode) {
        //             this.selectDeptNode = topNode
        //         } else {
        //             this.selectDeptNode = this.getDeptDefaultTopNode()
        //         }
        //     })
        // },
        confirmOutput: function() {
            const OutSize = [{ wch: 30 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }]
            const fileName = 'department导出' + new Date().Format('yyyyMMddhhmm')
            this.$outputXlsxFile(this.OutData, OutSize, fileName)
        },
        dlgOpen: function() {
            const _this = this

            if (_this.form.id) {
                const postData = {
                    id: _this.form.id
                }
                this.baseRequest('getById', postData).then((res) => {
                    if (res.data) {
                        _this.form.deptName = res.data.deptName
                        _this.form.deptCode = res.data.deptCode
                        _this.form.deptOrder = res.data.deptOrder
                        _this.form.deptLevel = res.data.deptLevel
                        // _this.form.deptAttr = res.data.deptAttr ? res.data.deptAttr.split(',') : []
                        _this.form.deptAttr = res.data.deptAttr
                        // _this.form.groupIds = res.data.groupId ? res.data.groupId.split(',') : []
                        _this.form.groupId = res.data.groupId
                        _this.form.parentId = res.data.parentId
                        _this.form.parentName = _this.DeptTreeMap[res.data.parentId].label
                        _this.form.chargedBy = res.data.chargedBy ? res.data.chargedBy.split(',') : []
                        _this.form.id = res.data.id

                        // _this.selectParent = []
                        // if (res.data.parentId) {
                        //     _this.selectParent.push(res.data.parentId)
                        // }
                    }
                }).catch(() => {
                })
            }
        },
        /* 编辑*/
        handleEdit: function(val) {
            this.isAdd = false
            this.form.id = val.id
            this.dialogVisible = true
            this.dialogTitle = '编辑'
        },
        /* 新增*/
        handleAdd: function() {
            this.form = this.initForm(this.selectDeptNode)
            this.isAdd = true
            this.dialogVisible = true
            this.dialogTitle = '新增'
        },
        confirmSubmit: function() {
            const _this = this

            this.$refs.form.validate(valid => {
                if (valid) {
                    let soaUrl = 'edit'
                    const postData = {
                        deptName: _this.form.deptName,
                        deptAttr: _this.form.deptAttr,
                        // deptLevel: _this.form.deptLevel,
                        groupId: _this.form.groupId,
                        chargedBy: _this.form.chargedBy.join(','),
                        id: _this.form.id
                    }

                    if (postData.deptCode !== 'TOP') {
                        // postData.groupId = _this.form.groupIds.join(',')
                        postData.deptOrder = _this.form.deptOrder ? _this.form.deptOrder : 0
                        postData.deptCode = _this.form.deptCode

                        const parents = this.form.parentId
                        if (parents) {
                            if (this.$common.isArrayFn(parents)) {
                                if (parents.length > 0) {
                                    postData.parentId = parents[parents.length - 1]
                                }
                            } else {
                                postData.parentId = parents
                            }
                        }
                    }

                    if (this.isAdd) {
                        soaUrl = 'add'
                    }
                    this.opRecord(postData, soaUrl)
                } else {
                    //console.log('error submit!!')
                    return false
                }
            })
        },
        opRefresh: function() {
            this.initData()
            this.dialogVisible = false
            // this.$notify({
            //     title: '处理成功',
            //     type: 'info'
            // })
        },
        // // 全部展开
        // unFoldAll: function() {
        //     const _this = this
        //     // 将没有转换成树的原数据
        //     const keyList = this.DeptTreeMap
        //     for (const _id in keyList) {
        //         // 将没有转换成树的原数据设置key为... 的展开
        //         _this.$refs.selectTree.store.nodesMap[_id].expanded = true
        //     }
        // },
        // // 全部折叠
        // collapseAll: function() {
        //     const _this = this
        //     const keyList = this.DeptTreeMap
        //     for (const _id in keyList) {
        //         // 将没有转换成树的原数据设置key为... 的展开
        //         _this.$refs.selectTree.store.nodesMap[_id].expanded = false
        //     }
        // },
        // 字典项
        baseRequest: function(opUrl, postData) {
            return this.$channel.globeRequest('SysDeptController', opUrl, postData, 'project')
        },
        pubRequest: function(opUrl, postData) {
            return this.$channel.globeRequest('pub', opUrl, postData, 'project')
        }
    }
}
</script>

<style scoped>
    .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 16px;
        padding-right: 8px;
    }
    .custom-tree-container .block-l {
        /*flex-grow: 2 ;*/
        float: left;
        width: 20%;
        padding: 0 8px 0 0;
    }
    .custom-tree-container .block-r {
        /*flex-grow: 10;*/
        float: left;
        width: 80%;
        /*padding: 0 0 0 8px;*/
    }
</style>

<style scoped>
    .ch-input .el-input__inner {
        border-radius: 0px;
        border-color: #32323A;
    }
    .ch-input-size {
        width: 150px;
    }
    .ch-button {
        border-radius: 0px;
        border-color: #32323A;
        background-color: #32323A;
        color: #fff;
    }
    .ch-button-warning {
        margin-left: 10px;
        border-radius: 0px;
        border-color: #E6A23C;
        background-color: #E6A23C;
        color: #fff;
    }
    .ch-button-export {
        margin-left: 10px;
        border-radius: 0px;
        border-color: #98CC1F;
        background-color: #98CC1F;
        color: #fff;
    }
</style>
