<template>
  <div class="app-container">
    <el-row>
      <el-col :span="5">
        <div style="width:90%;">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>事部件管理</span>
            </div>
            <el-tree
              v-loading="treeLoading"
              ref="tree"
              :data="caseTypeTree"
              :props="defaultProps"
              :default-expand-all="expandAllNode"
              :expand-on-click-node="expandNodeClick"
              :accordion="accordion"
              :default-expanded-keys="[listQuery.typeId]"
              :default-checked-keys="[listQuery.typeId]"
              :highlight-current="highlightCurrent"
              class="filter-tree"
              node-key="id"
              @node-click="handleNodeClick"
            />
          </el-card>
        </div>
      </el-col>
      <el-col :span="19">
        <div>
          <el-row class="table-title">
            <el-col :span="6"><div class="title-header"><i class="el-icon-menu"/>数据列表</div></el-col>
            <el-col :span="12" :offset="6" class="edit_btns">
              <el-button v-if="hasPerm('/caseType/deleteTypeDetail')" class="edit_btn" size="small" @click="del">删除</el-button>
              <el-button v-if="hasPerm('/caseType/addTypeDetail')" class="edit_btn" size="small" @click="add">添加</el-button>
              <el-popover
                placement="right"
                trigger="click">
                <el-form :model="listQuery" :inline="false" class="form-container" size="mini">
                  <el-form-item class="filter-item" label="名称" prop="typeName">
                    <el-input v-model="listQuery.typeDetailName" placeholder="名称" clearable/>
                  </el-form-item>
                  <el-form-item class="filter-item" label="编码" prop="typeCode">
                    <el-input v-model="listQuery.typeDetailId" placeholder="编码" clearable/>
                  </el-form-item>
                  <el-form-item class="filter-button">
                    <div>
                      <el-button type="primary" icon="el-icon-search" @click="search">搜索</el-button>
                    </div>
                  </el-form-item>
                </el-form>
                <el-button slot="reference" class="edit_btn" size="small">条件过滤</el-button>
              </el-popover>
              <!-- <el-button v-if="hasPerm('/marker/delete')" class="edit_btn" size="small" @click="del">删除</el-button> -->
            </el-col>
          </el-row>
          <el-table v-loading="listLoading" :data="caseDetailTypeList" class="table" border @selection-change="handleSelectionChange" @row-click="showDetail">
            <el-table-column align="center" type="selection" width="50"/>
            <el-table-column :index="indexMethod" align="center" type="index" />
            <el-table-column align="center" prop="typeDetailName" label="名称"/>
            <el-table-column align="center" prop="typeDetailCode" label="编码"/>
            <el-table-column align="center" label="所属大类">
              <template slot-scope="scope">
                {{ caseTypeMap[scope.row.typeId] }}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="240">
              <template slot-scope="scope">
                <el-button class="table-button" type="text" @click="edit(scope.row)">编辑</el-button>
                <!-- <el-button class="table-button" type="text" @click="showStandard(scope.row)">立案标准</el-button> -->
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination-container">
          <el-pagination
            :current-page="listQuery.offset"
            :page-sizes="[5,10,20,30,50]"
            :page-size="listQuery.limit"
            :total="total"
            align="center"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"/>
        </div>
      </el-col>
    </el-row>
    <edit-caseType v-show="editShow" ref="editCaseType" @watchChild="fetchData"/>
    <detail-caseType v-show="detailShow" ref="detailCaseType"/>
  </div>
</template>

<script>
import { getCaseTypeList, getCaseDetailType, deleteCaseDetailType, getCaseTypeDict } from '@/api/busAdmin/caseType'
import editCaseType from '@/views/busAdmin/caseType/editCaseType'
import detailCaseType from '@/views/busAdmin/caseType/detailCaseType'

export default {
  name: 'ListCaseType',
  components: { editCaseType, detailCaseType, deleteCaseDetailType },
  data() {
    return {
      // caseTypeTree: [
      //   {
      //     id: -1,
      //     name: '事件',
      //     children: []
      //   },
      //   {
      //     id: -2,
      //     name: '部件',
      //     children: []
      //   }
      // ],
      caseTypeTree: [],
      treeLoading: false,
      expandAllNode: false,
      expandNodeClick: true,
      accordion: true,
      highlightCurrent: true,
      defaultProps: {
        children: 'children',
        label: 'name',
        id: 'id'
      },
      listQuery: {
        typeId: 0,
        eorc: 1,
        typeDetailId: '',
        typeDetailName: '',
        offset: 1,
        limit: 10,
        sort: 'id',
        order: 'asc'
      },
      total: 0, // 数据总数
      columns: [
        {
          text: '名称',
          value: 'typeDetailName',
          align: 'center'
        },
        {
          text: '编码',
          value: 'typeDetailCode',
          align: 'center',
          width: 100
        },
        {
          text: '所属大类',
          value: 'this.typeId',
          align: 'center'
        }
      ],
      listLoading: false,
      caseDetailTypeList: [],
      editShow: false,
      detailShow: false,
      multipleSelection: [], // 多选选中项
      caseTypeMap: {}
    }
  },
  watch: {
    'editShow': function(newVal, oldVal) {
      console.log('editShow', this.editShow)
    }
  },
  created() {
    this.initCaseTypeTree()
    // this.fetchCaseTypeTree()
  },
  methods: {
    indexMethod(index) {
      return this.listQuery.limit * (this.listQuery.offset - 1) + index + 1
    },
    initCaseTypeTree() {
      this.treeLoading = true
      getCaseTypeDict().then(response => {
        response.data.forEach(dictItem => {
          const treeRoot = {}
          treeRoot.id = 0 - parseInt(dictItem.value)
          treeRoot.name = dictItem.name
          treeRoot.eorc = dictItem.value
          treeRoot.children = []
          this.caseTypeTree.push(treeRoot)
        })
        this.fetchCaseTypeTree()
      })
    },
    fetchCaseTypeTree() {
      getCaseTypeList().then(response => {
        this.parseCaseTypeTree(response.data)
        this.parseCaseTypeMap(response.data)
        this.listQuery.typeId = parseInt(response.data[0].id)
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(this.listQuery.typeId) // treeBox 元素的ref   value 绑定的node-key
        })
        this.treeLoading = false
        this.fetchData()
      })
    },
    parseCaseTypeTree(caseTypeList) {
      caseTypeList.forEach(item => {
        const caseType = {}
        caseType.id = parseInt(item.id)
        caseType.name = item.typeName
        caseType.children = []
        caseType.eorc = item.eorc
        // console.log(this.caseTypeTree)
        this.caseTypeTree.forEach(treeItem => {
          if (caseType.eorc === treeItem.eorc) {
            treeItem.children.push(caseType)
          }
        })
        // console.log(this.caseTypeTree)
      })
    },
    parseCaseTypeMap(caseTypeList) {
      caseTypeList.forEach(item => {
        this.caseTypeMap[item.id] = item.typeName
        // this.caseTypeMap.set(item.id, item.value)
      })
      console.log('caseTypeMap', this.caseTypeMap)
    },
    handleNodeClick(data) {
      this.listQuery.typeId = data.id
      this.listQuery.eorc = data.eorc
      if (this.listQuery.typeId > 0) {
        this.fetchData(false)
      }
    },
    fetchData(isNowPage = true) {
      this.listLoading = true
      if (!isNowPage) { // 是否显示当前页，否则跳转第一页
        this.listQuery.offset = 1
      }
      getCaseDetailType(this.listQuery).then(response => {
        this.caseDetailTypeList = response.data.rows
        this.total = parseInt(response.data.total)
        this.listLoading = false
      })
    },
    search() {
      this.fetchData(false)
    },
    // 改变页容量
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.fetchData()
    },
    // 改变当前页
    handleCurrentChange(val) {
      this.listQuery.offset = val
      this.fetchData()
    },
    add() {
      this.dialogFormVisible = true
      this.editShow = true
      this.$refs.editCaseType.initDialog({
        dialogStatus: 'create',
        dialogFormVisible: this.dialogFormVisible,
        eorc: this.listQuery.eorc,
        typeId: this.listQuery.typeId
      })
    },
    edit(row) {
      if (this.hasPerm('/caseType/updateTypeDetail')) {
        event.stopPropagation()
        this.dialogFormVisible = true
        this.editShow = true
        this.$refs.editCaseType.initDialog({
          dialogStatus: 'update',
          dialogFormVisible: this.dialogFormVisible,
          eorc: this.listQuery.eorc,
          typeId: this.listQuery.typeId,
          row: row
        })
      } else {
        event.stopPropagation()
        this.$message.warning('没有权限')
      }
    },
    del() {
      if (this.checkSelection()) {
        const detailTypeIds = []
        this.multipleSelection.forEach(function(value, index) {
          detailTypeIds.push(value.id)
        })
        this.$confirm(
          '确定要删除所选类别吗？',
          '确认操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          deleteCaseDetailType(detailTypeIds.join(',')).then(response => {
            if (response.code === 200) {
              this.$message.success('删除成功')
              this.fetchData()
            }
          })
        })
      } else {
        this.$message.error('至少选中一项')
      }
    },
    // 多选触发方法
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 检查选择情况
    checkSelection() {
      if (this.multipleSelection.length === 0) {
        return false
      } else {
        return true
      }
    },
    showDetail(row) {
      this.detailShow = true
      this.$refs.detailCaseType.initDialog(true, row)
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  $tableTitleHeight:46px;
  .table{
    margin-bottom: 20px;
  }
  .pagination-container{
    margin-bottom: 50px;
  }
  .table-title{
    background-color:rgba(243, 243, 243, 1);
    height: $tableTitleHeight;
    .title-header{
      line-height:$tableTitleHeight;
      color: #606266;
      font-size: 15px;
      i{
        margin-left: 5px;
        margin-right: 5px;
      }
    }
  }
  .edit_btns{
    .edit_btn{
      float:right;
      margin:7px 3px;//为了需要居中显示margin-top和bottom要用$tableTitleHeight减去按钮原高度除以2
    }
  }
  .table-button{
    padding: 10px;
  }
  .form-container{
    padding: 20px;
    text-align: center;
  }
  .filter-item{
    display: flex;
  }
  .filter-button{
    margin: auto;
  }
</style>
