<template>
  <div class="app-container">
    <el-container>
      <el-aside width="300px" style="background-color:#fff">
        <el-tree
          v-loading="treeLoading"
          ref="tree"
          :data="treeData"
          :props="defaultProps"
          :load="getVillageList"
          accordion
          class="filter-tree"
          lazy
          @node-expand="nodeExpand"
          @node-click="handleNodeClick"/>
      </el-aside>
      <el-main>
        <div class="filter-container">
          <div class="filter-row mb-10">
            <div class="filter-group ">
              <div class="filter-lable">
                搜索：
              </div>
              <div class="filter-width">
                <el-input v-model="KEYWORDS" placeholder="请输入关键字" class="filter-item" />
              </div>
            </div>
            <div class="filter-group">
              <div class="filter-lable">
                属地：
              </div>
              <div class="filter-width">
                <el-cascader id="POSSESSION" ref="POSSESSION" v-model="POSSESSION" :options="areaList" :props="areaProps" placeholder="请选择省市县" style="width: 100%"/>
              </div>
            </div>
            <div class="filter-group">
              <div class="filter-lable">
                部门级别：
              </div>
              <div class="filter-width">
                <el-select v-model="LEVEL" placeholder="请选择" label="属地">
                  <el-option v-for="item in DepartmentLevelList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </div>
            </div>
            <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getQuery">
              搜索
            </el-button>
            <el-button class="filter-item" type="success" icon="el-icon-refresh" @click="goKeyReset">
              重置
            </el-button>
          </div>

        </div>
        <el-tabs v-model="activeTab" type="border-card" @tab-click="handleClick">
          <el-tab-pane v-for="tab in tabList" :name="tab.id" :key="tab.id" :label="tab.name">
            <el-table
              v-loading="listLoading"
              :data="varList"
              :header-cell-style="{
                'font-weight': 'bold',
                'color': '#000'
              }"
              border
              fit
              highlight-current-row>
              <el-table-column type="index" label="序号" width="50" align="center" />
              <el-table-column label="名称" width="180">
                <template slot-scope="{row}">
                  <div class="link-type" @click="getQuery(row.DEPARTMENT_ID)">
                    {{ row.NAME }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="HEADMAN" label="部门负责人" />
              <el-table-column label="部门级别" >
                <template slot-scope="{row}">
                  <template v-if="row.LEVEL==1">省级</template>
                  <template v-if="row.LEVEL==2">市级</template>
                  <template v-if="row.LEVEL==3">区/县级</template>
                  <template v-if="row.LEVEL==4">乡/镇级</template>
                  <template v-if="row.LEVEL==5">村/社区级</template>
                </template>
              </el-table-column>
              <el-table-column label="属地" >
                <template slot-scope="{row}">
                  {{ row.CITY_NAME }} {{ row.COUNTRY_NAME?('-- '+ row.COUNTRY_NAME ):'' }}
                  {{ row.VILLAGE_NAME?(' -- '+row.VILLAGE_NAME):'' }} {{ row.STREET_NAME?(' -- '+row.STREET_NAME):'' }}
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="290">
                <template slot-scope="scope">
                  <el-button v-show="edit" type="primary" icon="el-icon-edit" size="mini" @click="handleEdit(scope.row.DEPARTMENT_ID)">编辑</el-button>
                  <el-button v-show="del" type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(scope.row.DEPARTMENT_ID, scope.row.NAME)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
        <div class="page-btn-group">
          <div>
            <el-button v-show="add" type="primary" icon="el-icon-plus" @click="handleCreate(DEPARTMENT_ID)">新增</el-button>
            <el-button v-show="DEPARTMENT_ID != '0'" icon="el-icon-arrow-left" @click="getQuery(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 :visible.sync="dialogFormEdit" :title="dialogType=='edit'?'修改':'新增'" width="600px">
      <el-tag class="mark_up" size="medium">上级部门：{{ DEPARTMENT_NAME }}</el-tag>
      <el-form ref="roleForm" :model="form" :rules="formRules" label-width="120px" style="width: 500px;">
        <el-form-item label="部门名称" prop="NAME">
          <el-input v-model="form.NAME" autocomplete="off" placeholder="这里输入名称..." />
        </el-form-item>
        <el-form-item label="部门级别" prop="LEVEL">
          <el-select v-model="form.LEVEL" placeholder="请选择" class="filter-item" disabled>
            <el-option v-for="item in levelList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属区域">
          {{ AREA_NAME }}
        </el-form-item>
        <el-form-item v-if="activeTab==2" label="部门类别" prop="CATEGORY">
          <el-select v-model="form.CATEGORY" placeholder="请选择" clearable class="filter-item">
            <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item v-show="dialogType=='edit'" label="主管负责人" prop="HEADMAN">
          <el-select v-model="form.HEADMAN" placeholder="请选择" clearable class="filter-item">
            <el-option v-for="item in userList" :key="item.USER_ID" :label="item.USERNAME" :value="item.USER_ID" />
          </el-select>
        </el-form-item>
        <el-form-item v-show="dialogType=='edit'" label="分管领导" prop="LRMAN">
          <el-select v-model="form.LRMAN" placeholder="请选择" clearable class="filter-item">
            <el-option v-for="item in lrUserList" :key="item.USER_ID" :label="item.USERNAME" :value="item.USER_ID" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="DEP_ORDER">
          <el-input v-model.number="form.DEP_ORDER" placeholder="这里输入排序..." />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormEdit = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import { requestFN } from '@/utils/request'
export default {
  components: { Pagination },
  data() {
    return {
      treeLoading: false,
      treeData: [],
      CITY_CODE: '',
      PROVINCE: '150000', // 省
      CITY: '', // 市
      COUNTRY: '', // 区
      VILLAGE: '', // 镇
      STREET: '', // 街
      AREA: [],
      AREA_NAME: '',
      defaultProps: {
        children: 'nodes',
        label: 'NAME'
      },
      activeTab: '1',
      tabList: [
        { id: '1', name: '安委会' },
        { id: '2', name: '行业' },
        { id: '3', name: '属地' },
        { id: '4', name: '其他' }
      ],
      levelList: [
        { id: '2', name: '市级' },
        { id: '3', name: '区/县级' },
        { id: '4', name: '乡/镇级' },
        { id: '5', name: '村/社区级' }
      ],
      categoryList: [
        { id: '1', name: '行业监管' },
        { id: '2', name: '综合监管' }
      ],
      areaList: [], // 省市县列表
      props: { value: 'value', label: 'label', children: 'children' },
      userList: [], // 本部门人
      lrUserList: [], // 上级部门人
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10
      },
      DEPARTMENT_ID: '0',
      PARENT_ID: '',	 // 上级ID
      total: 0,
      pd: [], // 上级部门
      varList: [],
      ROLE_ID: '1',	// 角色ID
      dialogFormEdit: false,
      dialogType: 'add',
      form: {
        DEPARTMENT_ID: '', // ID
        PARENT_ID: '', // 父ID
        NAME: '', // 名称
        TYPE: this.activeTab, // 类型
        LEVEL: '', // 级别
        CATEGORY: '', // 类别
        HEADMAN: '', // 主管负责人
        LRMAN: '', // 分管领导
        AREA: '',
        PROVINCE: '150000', // 省
        CITY: '', // 市
        COUNTRY: '', // 区
        VILLAGE: '', // 镇
        STREET: '', // 街
        DEP_ORDER: ''// 排序
      },
      add: false,
      del: false,
      edit: false,
      formRules: {
        NAME: [
          { required: true, message: '名称不能为空', trigger: 'blur' },
          { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
        ],
        LEVEL: [
          { required: true, message: '请选择行政区域级别', trigger: 'change' }
        ],
        AREA: [
          { required: true, message: '请选择所属区域', trigger: 'change' }
        ],
        CATEGORY: [
          { required: true, message: '请选择部门类别', trigger: 'change' }
        ],
        DEP_ORDER: [
          { required: true, message: '菜单序号不能为空', trigger: 'change' },
          { type: 'number', message: '菜单序号必须为数字' }
        ]
      },

      KEYWORDS: null,

      LEVEL: null,
      DepartmentLevelList: [
        { label: '省级', value: '4' },
        { label: '市级', value: '1' },
        { label: '区县级', value: '2' },
        { label: '乡镇级', value: '3' }
      ],
      areaProps: {
        lazy: true,
        lazyLoad: this.lazyLoad,
        value: 'numValue',
        id: 'id',
        label: 'label',
        children: 'children',
        checkStrictly: true
      },
      POSSESSION: null,
      DEPARTMENT_NAME: null
    }
  },
  created() {
    this.getAreaDict('e725d2a91b8248f4b8f49889038df7de', '0').then(data => {
      this.areaList = data
    })
  },
  methods: {
    getCityCode() {
      return new Promise((resolve) => {
        requestFN(
          '/department/getCityCode',
          {
          }
        ).then((data) => {
          this.CITY_CODE = data.CITY_CODE
          resolve()
        }).catch((e) => {
        })
      })
    },
    async getVillageList(node, resolve) {
      if (node.level === 0) {
        await this.getCityCode()
        requestFN(
          '/dictionaries/goEdit',
          {
            DICTIONARIES_ID: this.CITY_CODE
          }
        ).then((data) => {
          this.CITY = data.pd.BIANMA
          this.AREA[0] = data.pd.NAME
          this.AREA_NAME = this.AREA.join('/')
          this.getQuery(this.DEPARTMENT_ID)
          const tempArr = []
          tempArr.push(data.pd)
          return resolve(tempArr)
        }).catch((e) => {
        })
      } else {
        requestFN(
          '/dictionaries/getLevels',
          {
            DICTIONARIES_ID: node.data.DICTIONARIES_ID
          }
        ).then((data) => {
          resolve(data.list)
        }).catch((e) => {
        })
      }
    },
    nodeExpand(data, node, tree) {
      node.childNodes.map(item => {
        item.expanded = false
      })
    },
    handleNodeClick(node, data, value) {
      if (data.level === 1) {
        this.CITY = node.BIANMA
        this.COUNTRY = ''
        this.VILLAGE = ''
        this.STREET = ''
        this.AREA[0] = node.NAME
        this.AREA[1] = ''
        this.AREA[2] = ''
        this.AREA[3] = ''
      } else if (data.level === 2) {
        this.COUNTRY = node.BIANMA
        this.VILLAGE = ''
        this.STREET = ''
        this.AREA[1] = node.NAME
        this.AREA[2] = ''
        this.AREA[3] = ''
      } else if (data.level === 3) {
        this.VILLAGE = node.BIANMA
        this.STREET = ''
        this.AREA[2] = node.NAME
        this.AREA[3] = ''
      } else {
        this.STREET = node.BIANMA
        this.AREA[3] = node.NAME
      }
      this.AREA_NAME = this.AREA.join('/')
      this.getList()
    },
    handleClick(tab) {
      this.activeTab = tab.name
      this.varList = []
      this.listQuery.page = 1
      this.getQuery(this.DEPARTMENT_ID)
    },
    getQuery(DEPARTMENT_ID) {
      this.DEPARTMENT_ID = DEPARTMENT_ID
      this.getList()
    },
    getList() {
      this.listLoading = true
      this.varList = []
      requestFN(
        '/department/list?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          KEYWORDS: this.KEYWORDS,
          LEVEL: this.LEVEL,
          POSSESSION: this.POSSESSION ? this.POSSESSION.join(',') : '',
          DEPARTMENT_ID: this.DEPARTMENT_ID,
          TYPE: this.activeTab,
          CITY: this.CITY,
          COUNTRY: this.COUNTRY,
          VILLAGE: this.VILLAGE,
          STREET: this.STREET
        }
      ).then((data) => {
        this.listLoading = false
        this.varList = data.varList
        this.pd = data.pd
        this.total = data.page.totalResult
        this.PARENT_ID = data.PARENT_ID
        this.hasButton()
        this.DEPARTMENT_NAME = this.DEPARTMENT_ID == '0' ? '(无) 此项为顶级部门' : data.pd.NAME
      }).catch((e) => {
        this.listLoading = false
      })
    },
    handleCreate(parentId) {
      this.areaList = []
      this.dialogType = 'add'
      this.resetForm()
      if (this.STREET) {
        this.form.LEVEL = '5'
      } else if (this.VILLAGE) {
        this.form.LEVEL = '4'
      } else if (this.COUNTRY) {
        this.form.LEVEL = '3'
      } else if (this.CITY) {
        this.form.LEVEL = '2'
      // } else if (this.PROVINCE) {
      //   this.form.LEVEL = '1'
      } else {
        this.$message({
          message: '请先在左侧树选择属地',
          type: 'error'
        })
      }
      this.form.PARENT_ID = parentId
      this.dialogFormEdit = true
    },
    async handleEdit(id) {
      this.dialogType = 'edit'
      await this.getData(id)
      this.userList = await this.getUserList(this.form.DEPARTMENT_ID)
      this.lrUserList = await this.getUserList(this.DEPARTMENT_ID)
      this.dialogFormEdit = true
    },
    getData(id) {
      return new Promise((resolve) => {
        requestFN(
          '/department/goEdit',
          {
            DEPARTMENT_ID: id
          }
        ).then((data) => {
          this.form = Object.assign({}, data.pd) // copy obj
          resolve()
        }).catch((e) => {
          this.listLoading = false
        })
      })
    },
    handleDelete(id, name) {
      this.$confirm('确定要删除[' + name + ']吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/department/delete',
          {
            DEPARTMENT_ID: id
          }
        ).then(() => {
          this.listLoading = false
          this.getQuery(this.DEPARTMENT_ID)
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },
    confirm() {
      this.$refs.roleForm.validate(valid => {
        if (valid) {
          this.listLoading = true
          this.form.PROVINCE = this.PROVINCE
          this.form.CITY = this.CITY
          this.form.COUNTRY = this.COUNTRY || ''
          this.form.VILLAGE = this.VILLAGE || ''
          this.form.STREET = this.STREET || ''
          requestFN(
            '/department/' + this.dialogType,
            this.form
          ).then((data) => {
            this.listLoading = false
            this.dialogFormEdit = false
            this.varList = []
            this.listQuery.page = 1
            this.getQuery(this.DEPARTMENT_ID)
          }).catch((e) => {
            this.listLoading = false
          })
        } else {
          return false
        }
      })
    },
    getUserList(id) {
      return new Promise((resolve) => {
        requestFN(
          '/user/listAll',
          {
            DEPARTMENT_ID: id
          }
        ).then((data) => {
          resolve(data.userList)
        })
          .catch((e) => {
          })
      })
    },
    resetForm() {
      this.form = {
        DEPARTMENT_ID: '', // ID
        PARENT_ID: '', // 父ID
        NAME: '', // 名称
        TYPE: this.activeTab, // 类型
        LEVEL: '', // 级别
        CATEGORY: '', // 类别
        HEADMAN: '', // 主管负责人
        LRMAN: '', // 分管领导
        AREA: [],
        PROVINCE: '', // 省
        CITY: '', // 市
        COUNTRY: '', // 区
        VILLAGE: '', // 镇
        DEP_ORDER: ''// 排序
      }
    },
    hasButton: function() {
      var keys = 'department:add,department:del,department:edit,toExcel'
      requestFN(
        '/head/hasButton',
        {
          keys: keys
        }
      ).then((data) => {
        this.add = data.departmentfhadminadd
        this.del = data.departmentfhadmindel
        this.edit = data.departmentfhadminedit
      }).catch((e) => {
      })
    },
    lazyLoad(nodeValue, resolve) {
      if (nodeValue.data && (!nodeValue.children || nodeValue.children.length == 0)) {
        this.getDictByDicId(nodeValue.data.id).then(data => {
          resolve(data)
        })
      } else {
        resolve(null)
      }
    },
    // 获取数据字典数据
    getDictByDicId(dicId) {
      var dicListVal = []
      return new Promise((resolve) => {
        let id = ''
        if (!dicId) {
          id = '0'
        } else {
          id = dicId
        }
        requestFN(
          '/dictionaries/getLevelsAndSCount',
          {
            DICTIONARIES_ID: id
          }
        ).then((data) => {
          if (data.list.length > 0) {
            dicListVal = data.list.map((e) => {
              if (e.zcount == '0') {
                return { value: e.DICTIONARIES_ID.toString(), numValue: e.BIANMA.toString(), label: e.NAME, id: e.DICTIONARIES_ID, leaf: true }
              } else {
                return { value: e.DICTIONARIES_ID.toString(), numValue: e.BIANMA.toString(), label: e.NAME, id: e.DICTIONARIES_ID, children: [], leaf: false }
              }
            })
          } else {
            dicListVal = undefined
          }
          return resolve(dicListVal)
        }).catch((e) => {
        })
      })
    },
    // 获取数据字典数据
    getAreaDict(dicId, level, disabled) {
      var dicListVal = []
      return new Promise((resolve) => {
        let id = ''
        if (!dicId) {
          id = '0'
        } else {
          id = dicId
        }
        requestFN(
          '/dictionaries/getAreaDict',
          {
            DICTIONARIES_ID: id,
            LEVEL: level,
            DISABLED: disabled

          }
        ).then((data) => {
          if (data.list.length > 0) {
            dicListVal = data.list.map((e) => {
              if (e.zcount == '0') {
                return { value: e.DICTIONARIES_ID.toString(), numValue: e.BIANMA.toString(), label: e.NAME, id: e.DICTIONARIES_ID, leaf: true, disabled: e.DISABLED, level: e.LEVEL }
              } else {
                return { value: e.DICTIONARIES_ID.toString(), numValue: e.BIANMA.toString(), label: e.NAME, id: e.DICTIONARIES_ID, children: [], leaf: false, disabled: e.DISABLED, level: e.LEVEL }
              }
            })
          } else {
            dicListVal = undefined
          }
          return resolve(dicListVal)
        }).catch((e) => {
        })
      })
    },
    goKeyReset() {

    }
  }
}
</script>
<style lang="scss" scoped>
  .mark_up{
    margin-bottom:20px;
    margin-left: 110px;
  }
</style>
