<template>
  <div class="app-container">
    <div class="rightCont">
      <el-form label-width="50px">
        <el-row>
          <el-col :span="4">
            <el-form-item label="区域名称/编码" label-width="110px">
              <el-input v-model="keywords" placeholder="请输入关键字"/>
            </el-form-item>
          </el-col>
          <el-col :span="4"/>
          <el-col :span="4">
            <el-form-item label-width="10px">
              <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="getQuery">
                搜索
              </el-button>
              <el-button v-waves class="filter-item" type="success" icon="el-icon-refresh" @click="goKeyReset">
                重置
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div>
        <el-table
          v-loading="listLoading"
          ref="multipleTable"
          :data="varList"
          :row-key="getRowKey"
          border
          tooltip-effect="dark"
          style="width: 100%">
          <el-table-column :selectable="selectable" type="selection" reserve-selection width="55" align="center"/>
          <el-table-column type="index" label="序号" width="55" align="center"/>
          <el-table-column prop="fireRegionName" label="区域名称"/>
          <el-table-column prop="departmentName" label="负责部门"/>
          <el-table-column prop="fireRegionCode" label="编码"/>
          <el-table-column prop="pointCount" label="区域下点位数"/>
          <el-table-column prop="state" label="状态">
            <template slot-scope="{row}">
              <span v-if="row.state === 1" class="color-red">禁用</span>
              <span v-if="row.state === 0" class="color-green">启用</span>
            </template>
          </el-table-column>
          <el-table-column prop="remake" label="备注"/>
          <el-table-column label="操作" width="300">
            <template slot-scope="{row}">
              <el-button
                v-show="edit"
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="handleEdit(row.fireRegionId, row.state)">编辑
              </el-button>
              <el-button
                v-show="edit && row.pointCount === 0"
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="handelDelete(row)">删除
              </el-button>
              <el-button
                v-show="row.state === 0"
                type="warning"
                icon="el-icon-circle-close"
                size="mini"
                @click="handleClose(row.fireRegionId, row.fireRegionName, 1)">禁用
              </el-button>
              <el-button
                v-show="row.state === 1"
                type="success"
                icon="el-icon-circle-check"
                size="mini"
                @click="handleClose(row.fireRegionId, row.fireRegionName, 0)">启用
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="page-btn-group">
          <div>
            <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
            <el-button type="danger" icon="el-icon-plus" @click="handelDelete">批量删除</el-button>
            <el-button type="info" icon="el-icon-plus" @click="handelEditDept">批量修改负责部门</el-button>
          </div>
          <pagination
            :total="total"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.limit"
            @pagination="getList(HIDDENREGION_ID)"/>
        </div>
      </div>
    </div>
    <el-dialog v-loading ="listLoading" :visible.sync="dialogEditDept" title="批量修改负责部门" width="800px">
      <el-form ref="firefightingBatchEditDept" :model="form" :rules="rule" label-width="150px">
        <el-row>
          <el-form-item label="负责部门" prop="departmentId">
            <SelectTree
              v-if="deptTreeData.length !== 0"
              ref="deptTree_Select"
              :key="form.departmentId"
              :clearable="false"
              :options="deptTreeData"
              :props="defaultProps"
              v-model="form.departmentId"
              style="width: 80%;"
              placeholder="请选择部门"
            />
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEditDept = false">取 消</el-button>
        <el-button type="primary" @click="dialogEditDeptConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { requestFN } from '@/utils/request'
import waves from '@/directive/waves'
import SelectTree from '@/components/SelectTree'

export default {
  components: { Pagination, SelectTree },
  directives: { waves },
  data() {
    return {
      listLoading: true,
      add: false,
      del: false,
      edit: false,
      listQuery: {
        page: 1,
        limit: 20
      },
      total: 0,
      keywords: '',
      // 树形菜单
      filterText: '',
      varList: [],
      defaultProps: {
        value: 'id',
        children: 'nodes',
        label: 'name'
      },
      dialogEditDept: false,
      form: {
        departmentId: ''
      },
      rule: {
        departmentId: [{ required: true, message: '负责部门不能为空', trigger: 'blur' }]
      },
      deptTreeData: [],
      editDataIds: []
    }
  },
  watch: {
    filterText(val) {
      console.log(val)
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
    this.hasButton()
    this.getTreeList()
    this.getTreeData()
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    handleEdit(fireRegionId, state) {
      if (state === 1) {
        this.$message({
          message: '该区域已禁用',
          type: 'warning'
        })
        return
      }
      this.$parent.fireRegionId = fireRegionId
      this.$parent.activeName = 'Edit'
    },
    // 部门列表树
    getTreeData() {
      requestFN(
        '/department/listTreeV2',
        {}
      ).then((data) => {
        this.deptTreeData = JSON.parse(data.zTreeNodes)
      }).catch((e) => {
      })
    },
    handleClose(fireRegionId, name, state) {
      const stateName = state === 0 ? '启用' : '禁用'
      this.$confirm('确定要' + stateName + '[' + name + ']吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/fire/region/v2/update/state',
          {
            fireRegionId: fireRegionId,
            state: state
          }
        ).then((r) => {
          if (r.msg === 'success') {
            this.$message({
              message: stateName + '成功',
              type: 'success'
            })
            this.listLoading = false
            this.getTreeList()
            this.varList = []
            this.listQuery.page = 1
            this.getList(this.FIRE_REGION_ID)
          } else {
            this.listLoading = false
            this.$message.warning(r.msg)
          }
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },
    getRowKey(row) {
      return row.FIRE_REGION_ID
    },
    selectable(row, index) {
      // return row.ITEMCOUNT == 0
      return true
    },
    // 批量修改负责部门
    handelEditDept(row) {
      this.editDataIds = []
      if (row.fireRegionId) {
        this.editDataIds.push(row.fireRegionId)
      } else {
        const selection = this.$refs.multipleTable.selection
        if (!selection.length > 0) {
          this.$message({
            type: 'warning',
            message: '请选择要修改负责部门的数据'
          })
          return
        }
        selection.forEach(item => {
          this.editDataIds.push(item.fireRegionId)
        })
      }
      this.dialogEditDept = true
      this.form = {
        departmentId: ''
      }
    },
    dialogEditDeptConfirm() {
      this.$refs.firefightingBatchEditDept.validate((valid) => {
        if (!valid) {
          return
        }
        this.listLoading = true
        requestFN(
          '/fire/region/v2/update/dept',
          {
            ids: this.editDataIds.join(','),
            departmentId: this.form.departmentId
          }
        ).then((data) => {
          this.$message.success(data.msg)
          this.$refs.multipleTable.clearSelection()
          this.listLoading = false
          this.dialogEditDept = false
          this.varList = []
          this.listQuery.page = 1
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      })
    },
    // 批量删除
    handelDelete(row) {
      const DATA_IDS = []
      if (row.fireRegionId) {
        DATA_IDS.push(row.fireRegionId)
      } else {
        const selection = this.$refs.multipleTable.selection
        if (!selection.length > 0) {
          this.$message({
            type: 'warning',
            message: '请选择要删除的数据'
          })
          return
        }
        var isFlag = true
        selection.forEach(item => {
          if (item.ITEMCOUNT > 0) {
            isFlag = false
          }
        })
        if (!isFlag) {
          this.$message({
            type: 'warning',
            message: '选择区域中存在下级数据，不能删除'
          })
          return
        }
        selection.forEach(item => {
          DATA_IDS.push(item.fireRegionId)
        })
      }
      this.$confirm('确定要删除吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/fire/region/v2/remove',
          {
            ids: DATA_IDS.join(',')
          }
        ).then(() => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.$refs.multipleTable.clearSelection()
          this.listLoading = false
          this.varList = []
          this.listQuery.page = 1
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },
    // 添加
    handleAdd() {
      this.$parent.fireRegionId = ''
      this.$parent.activeName = 'Edit'
      this.$parent.FIRE_REGION_ID = ''
      this.$parent.FIRE_REGION_CODE = ''
      this.$parent.FIRE_REGION_NAME = ''
    },
    // 搜索
    getQuery() {
      // this.$refs.multipleTable.clearSelection()
      this.getList()
    },
    // 获取列表
    getList(pid) {
      this.listLoading = true
      this.varList = []
      this.HIDDENREGION_ID = pid
      requestFN(
        '/fire/region/v2/page?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          keywords: this.keywords
        }
      ).then((data) => {
        this.listLoading = false
        this.varList = data.varList
        this.total = data.page.totalResult
        this.hasButton()
      }).catch((e) => {
        this.listLoading = false
      })
    },
    goKeyReset() {
      this.keywords = ''
      this.getList()
    },
    getDict() {
      requestFN(
        'dictionaries/getLevels',
        {
          DICTIONARIES_ID: '4a3d0d99b0ea4e268c11dd0b18866917'
        }
      ).then((data) => {
        this.typeList = data.list
      })
        .catch((e) => {
          this.listLoading = false
        })

      requestFN(
        'dictionaries/getLevels',
        {
          DICTIONARIES_ID: 'f60cf0e8315b4993b6d6049dd29f2ba5'
        }
      ).then((data) => {
        this.periodList = data.list
      })
        .catch((e) => {
          this.listLoading = false
        })

      requestFN(
        'dictionaries/getLevels',
        {
          DICTIONARIES_ID: '4a661fa8aedc4d158c9cddaa9d2ec47e'
        }
      ).then((data) => {
        this.listingLevelList = this.listingLevelList.concat(data.list)
      })
        .catch((e) => {
          this.listLoading = false
        })
    },
    hasButton: function() {
      var keys = 'listmanager:add,listmanager:del,listmanager:edit,toExcel'
      requestFN(
        '/head/hasButton',
        {
          keys: keys
        }
      ).then((data) => {
        this.add = data.listmanagerfhadminadd		// 新增权限
        this.del = data.listmanagerfhadmindel		// 删除权限
        this.edit = data.listmanagerfhadminedit	// 修改权限
        this.toExcel = data.toExcel // 导出到excel权限
      }).catch((e) => {
        this.listLoading = false
      })
    },
    handleNodeClick(node, data, value) {
      /*
      this.handleEdit(node.id)
*/
      // this.getListSubset(node.id)
      this.getPaging(node.id)
    },
    getTreeList() {
      this.treeLoading = true
      requestFN(
        '/hiddenRegion/listAll',
        {}
      ).then((data) => {
        this.treeLoading = false
        this.treeData = JSON.parse(data.zTreeNodes)
      }).catch((e) => {
        this.treeLoading = false
      })
    }
  }
}
</script>

<style scoped>
.app-container {
  display: flex;
  align-items: baseline;
}

.rightCont {
  width: 100%
}
</style>
