<template>
  <div class="bbsl-common-page">
    <div class="bbsl-table-search">
      <el-form v-model="queryParam" :inline="true">
        <el-form-item label="姓名：">
          <el-input
            v-model="querys[0].value"
            clearable
            maxlength="128"
            placeholder="请输入姓名"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="年份" prop="year">
          <el-date-picker
            v-model="querys[4].value"
            placeholder="请选择年份"
            clearable
            type="year"
            value-format="yyyy"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" type="primary" @click="handleSearch"
            >搜索
          </el-button>
          <!-- <el-button icon="el-icon-refresh" @click="clearQuerys">重置</el-button>/ -->
        </el-form-item>
      </el-form>
    </div>

    <el-row :gutter="10" class="fullheight">
      <el-col :span="6" class="fullheight">
        <div class="common-tree-container">
          <div class="container-head">
            <el-input
              v-model="filterText"
              clearable
              placeholder="输入关键字进行过滤"
            >
            </el-input>
            <img
              v-if="expandAll"
              src="@/assets/img/quanjusuoxiao2.png"
              @click="expandHandle"
            />
            <img v-else src="@/assets/img/quanping.png" @click="expandHandle" />
            <i class="el-icon-refresh" @click="getEqu"></i>
            <!-- <i class="bbsl-iconfont  icon-shouqi" @click="expandHandle" v-if="expandAll" ></i>
						<i class="el-icon-s-unfold" @click="expandHandle" v-else ></i> -->
          </div>
          <el-tree
            v-if="treeData.length"
            ref="tree"
            :current-node-key="currentKey"
            :data="treeData"
            :expand-on-click-node="true"
            :filter-node-method="filterNode"
            :props="defaultProps"
            highlight-current
            node-key="id"
            @node-click="handleNodeClick"
          >
          </el-tree>
        </div>
      </el-col>

      <el-col :span="18" class="fullheight">
        <div ref="contentPanel" class="bbsl-table-content">
          <div ref="btnPanel" class="bbsl-btn-content">
            <el-button
              v-charge
              :disabled="type !== '3'"
              icon="el-icon-plus"
              type="success"
              @click="handleAdd"
              >新增
            </el-button>
            <el-popconfirm title="确定删除选中数据吗？" @confirm="handleDelete">
              <el-button
                slot="reference"
                v-charge
                :disabled="!multipleSelection.length"
                icon="el-icon-delete"
                style="margin-left: 10px"
                type="danger"
                >删除
              </el-button>
            </el-popconfirm>
            <el-button
              v-charge
              icon="el-icon-sort"
              plain
              style="margin-left: 10px"
              type="primary"
              @click="savePropertyf"
              :disabled="type !== '3'"
            >
              保存排序号
            </el-button>
            <el-upload
              ref="upload"
              v-charge
              :auto-upload="false"
              :file-list="fileList"
              :http-request="upLoadFile"
              :on-change="e => handleChange(e, fileList)"
              :show-file-list="false"
              accept="."
              action="no"
              class="avatar-uploader"
            >
              <el-button
                icon="el-icon-download"
                style="margin-right: 10px;"
                type="primary"
                :disabled="type !== '3'"
                >导入
              </el-button>
            </el-upload>
            <el-button icon="el-icon-upload2" type="warning" @click="exportFile"
              >导出
            </el-button>
            <el-button
              v-charge
              icon="el-icon-document"
              type="info"
              @click="templateDownload"
            >
              模版下載
            </el-button>
          </div>
          <el-table
            ref="multipleSelection"
            v-loading="loading"
            :cell-style="{'text-align': 'center'}"
            :data="tableData"
            :header-cell-style="{'text-align': 'center'}"
            :max-height="tableMaxHeight"
            :style="{width: '100%'}"
            size="mini"
            @row-dblclick="handleDbClick"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column
              fixed
              label="序号"
              type="index"
              width="55"
            ></el-table-column>
            <el-table-column label="年份" prop="year" show-overflow-tooltip>
            </el-table-column>
            <el-table-column label="姓名" prop="userName" show-overflow-tooltip>
            </el-table-column>
            <!-- <el-table-column min-width="200" sortable prop="majorNames" label="专业装备" show-overflow-tooltip>
						</el-table-column> -->
            <el-table-column label="岗位" prop="post" show-overflow-tooltip>
            </el-table-column>
            <el-table-column
              label="所属单位"
              min-width="70"
              prop="companyName"
              show-overflow-tooltip
            >
            </el-table-column>

            <el-table-column
              label="考核科目"
              prop="subjectName"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              label="考核成绩"
              prop="score"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              label="评定等级成绩"
              min-width="120"
              prop="rateLevel"
              show-overflow-tooltip
            >
              <template slot-scope="{row}">
                {{ getDictName('dagl-pjdj', row.rateLevel) }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="排序"
              min-width="70"
              prop="sn"
              show-overflow-tooltip
              sortable
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.sn"
                  min="1"
                  size="small"
                  style="width:70px"
                  type="number"
                  @input="insort(scope.row)"
                >
                </el-input>
                <!-- <el-input-number  controls-position="right" size="small" @input="insort(scope.row)" v-model="scope.row.sn"
									style="width:70px"></el-input-number> -->
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            ref="paginationPanel"
            :current-page="queryParam.pageBean.page"
            :page-size="queryParam.pageBean.pageSize"
            :page-sizes="[20, 30, 40, 50]"
            :total="total"
            align="right"
            background
            class="bbsl-pagination"
            layout="prev, pager, next,total, sizes, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
      </el-col>
    </el-row>

    <subMenuDialog ref="formModals" @reload="reload"></subMenuDialog>
  </div>
</template>

<script>
import {TableMixin} from '@/mixins/tableMixin'
import subMenuDialog from './components/subMenuDialog.vue'
import subMenu from '@/api/examDataMenu/examActivityData/subMenu'
import dictUtils from '@/components/dict/DictSelectUtils.js'
import equSysMenu from '@/api/examination/questionListMenu.js'

export default {
  name: 'subMenu',
  components: {
    subMenuDialog
  },
  mixins: [TableMixin],
  data() {
    return {
      url: {
        delete: '/exam/subject/info/'
      },
      search: '',
      tableData: [],
      filterText: '',
      treeData: [],
      treeNode: {
        code: '',
        id: '0',
        name: '课目分类管理',
        type: 0,
        children: []
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      querys: [
        {
          group: 'main',
          operation: 'LIKE',
          parentGroup: '',
          property: 'userName',
          relation: 'AND',
          value: ''
        },
        {
          group: 'main',
          operation: 'EQUAL',
          parentGroup: '',
          property: 'trainType',
          relation: 'AND',
          value: ''
        },
        {
          group: 'main',
          operation: 'EQUAL',
          parentGroup: '',
          property: 'typeId',
          relation: 'AND',
          value: ''
        },
        {
          group: 'main',
          operation: 'EQUAL',
          parentGroup: '',
          property: 'biz_sub_exam_data.subject_id_',
          relation: 'AND',
          value: ''
        },
        {
          group: 'main',
          operation: 'EQUAL',
          parentGroup: '',
          property: 'biz_sub_exam_data.year_',
          relation: 'AND',
          value: ''
        }
      ],
      TrainTypeList: [],
      TrainLevelList: [],
      positionList: [],
      sortList: {},
      fileList: [],
      equSys: [],
      type: '1',
      currentKey: '',
      // parentId: ''
      addInformation: {},
      positionId: '',
      expandAll: false
    }
  },
  created() {
    this.TrainTypeList = dictUtils.getDictItemsFromCache('xllb')
    this.TrainLevelList = dictUtils.getDictItemsFromCache('xljb')
    this.getEqu()
  },
  mounted() {},
  methods: {
    // 删除数据

    async handleDelete(row) {
      let ids = row ? row.id : this.multipleSelection.join()
      const {state} = await subMenu.deleteEqeSys(ids)
      console.log(11111222, state)
      if (state) {
        this.$message.success(`删除成功`)
        const {page, pageSize, total} = this.queryParam.pageBean
        const totalPages = Math.ceil(total / pageSize) // 计算总页数
        if (totalPages > 1 && page === totalPages) {
          if (this.tableData.length === 1) {
            // 当前页只有一条数据
            this.queryParam.pageBean.page -= 1 // 返回前一页
          }
        }
        await this.loadData()
      }
    },
    expandHandle() {
      console.log(this.$refs.tree.store)
      this.expandAll = !this.expandAll
      this.expandNodes(this.$refs.tree.store.root)
    },
    // 遍历树形数据，设置每一项的expanded属性，实现展开收起
    expandNodes(node) {
      node.expanded = this.expandAll
      for (let i = 0; i < node.childNodes.length; i++) {
        node.childNodes[i].expanded = this.expandAll
        if (node.childNodes[i].childNodes.length > 0) {
          this.expandNodes(node.childNodes[i])
        }
      }
    },

    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    // 保存排序
    savePropertyf() {
      subMenu.saveSort(this.sortList, res => {
        if (res.state) {
          this.$notify({
            type: 'success',
            message: res.message,
            duration: 2000
          })
          this.loadData()
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    getEqu() {
      this.currentKey = null
      equSysMenu.getSubjects({}, res => {
        console.log(111111111, res)
        this.treeData = res.value
        this.currentKey = res.value[0].id
        this.addInformation.orgId = res.value[0].id
        this.querys[3].value = this.currentKey
        this.$set(this.querys)
        this.$set(this.treeData)
        this.loadData(1)
      })
    },
    insort(val) {
      let id = val.id
      let value = val.sn
      this.sortList[id] = value
    },
    reload() {
      this.loadData()
    },
    handleAdd() {
      this.$refs.formModals.add(this.addInformation)
    },
    handleDbClick(val) {
      this.$refs.formModals.edit(val)
    },
    // 重置
    clearQuerys() {
      this.querys[0].value = ''
      this.querys[1].value = ''
      this.querys[2].value = ''
      this.querys[4].value = ''
      this.loadData(1)
    },
    handleNodeClick(data, {parent}) {
      this.type = data.type
      if (data.type != '3') return

      this.addInformation = {
        postId: parent.data.id,
        post: parent.data.name,
        companyId: parent.parent.data.id,
        companyName: parent.parent.data.name,
        subjectId: data.id,
        subjectName: data.name
      }

      // this.parentId = data.parentId
      this.querys[3].value = data.id
      this.loadData(1)
    },

    // 获取list
    loadData(page) {
      if (page) {
        this.queryParam.pageBean.page = page
      }
      this.loading = true
      this.tableData = []
      this.queryParam.querys = []
      this.queryParam.sorter = [
        {
          direction: 'DESC',
          property: 'createTime'
        }
      ]
      if (this.querys[0].value) {
        this.queryParam.querys.push(this.querys[0])
      }
      if (this.querys[1].value) {
        this.queryParam.querys.push(this.querys[1])
      }
      if (this.querys[2].value) {
        this.queryParam.querys.push(this.querys[2])
      }
      if (this.querys[3].value) {
        this.queryParam.querys.push(this.querys[3])
      }
      if (this.querys[4].value) {
        this.queryParam.querys.push(this.querys[4])
      }
      subMenu.getSubjects(this.queryParam, res => {
        this.total = res.total
        this.tableData = res.rows
        this.tableData.forEach(item => {
          this.TrainLevelList.forEach(ee => {
            if (item.trainLevel == ee.value) {
              item['trainLevelName'] = ee.name
            }
          })
          this.TrainTypeList.forEach(ee => {
            if (item.trainType == ee.value) {
              item['trainTypeName'] = ee.name
            }
          })
          this.positionList.forEach(ee => {
            if (item.positionId == ee.id) {
              item['positionName'] = ee.name
            }
          })
        })
        this.$set(this.tableData)
        this.loading = false
      })
    },

    // 获取树
    getTreen() {
      subMenu.getSubTree(
        {
          id: '0'
        },
        res => {
          this.treeData[0].children = res.value
          this.$set(this.treeData)
        }
      )
    },

    // 新增
    append(data, type) {
      if (type != 'father') {
        this.$refs.SubClassModal.add(data)
      } else {
        this.$refs.SubClassModal.add(data)
      }
    },
    // 修改
    upDateinfo(data, type) {
      this.$refs.SubClassModal.edit(data)
    },
    // 删除单个
    remove(item) {
      this.$confirm('确定删除选中数据？', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确 定',
        cancelButtonText: '取 消',
        type: 'warning'
      })
        .then(() => {
          subMenu.deleteSubjectClass(item.id).then(res => {
            if (res.data.state) {
              this.$notify({
                type: 'success',
                message: '删除成功',
                duration: 2000
              })
              this.loadData(1)
            }
          })
        })
        .catch(action => {
          this.$notify({
            type: 'info',
            message: action === 'cancel' ? '已取消删除' : '停留在当前页面'
          })
        })
    },
    searchName() {
      let querys = {
        name: ''
      }
      querys.name = this.search
      subMenu.getSubTree(querys, res => {
        this.treeData[0].children = res.value
        this.$set(this.treeData)
      })
    },
    //导入
    handleChange(file, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }
      if (
        file.raw.name.split('.')[1] == 'xlsx' ||
        file.raw.name.split('.')[1] == 'xls' ||
        file.raw.name.split('.')[1] == 'xlsm'
      ) {
        this.upLoadFile(file.raw)
      } else {
        this.$message.warning('请上传xls,xlsx,xlsm格式文件！')
        fileList.splice(0)
      }
    },
    //自定义上传方法（覆盖默认上传行为）
    upLoadFile(file) {
      let formData = new FormData()
      formData.append('file', file)
      subMenu.importExcel(formData, res => {
        if (res.state) {
          this.$notify({
            type: 'success',
            message: '导入成功',
            duration: 2000
          })
          this.loadData(1)()
        } else {
          this.$notify({
            type: 'error',
            message: res.message,
            duration: 2000,
            offset: 80
          })
          this.loadData(1)
        }
      })
    },
    exportFile() {
      subMenu.export(
        {
          querys: this.queryParam.querys,
          pageBean: {
            pageSize: -1
          }
        },
        res => {
          if (res) {
          }
        }
      )
    },

    // 模板下载
    async templateDownload() {
      window.open(this.portal + '/biz/subExam/data/downModel', '_blank')
    }
  }
}
</script>
<style lang="scss" scoped>
a {
  text-decoration: none;
  color: #ffffff;
}

.type-tag {
  margin: 0 2px;
}

.common-tree-container {
  height: calc(100% - 70px);
  margin-top: 0.52083vw;
  padding: 1.04167vw 1.04167vw;
  background-color: #fff;
  position: relative;
  box-sizing: border-box;
  border-radius: 20px;
  overflow-y: auto;
  box-shadow: 0px 0px 0.625vw 0 rgba(92, 102, 83, 0.2);
}

.avatar-uploader {
  display: inline-block;
  margin-left: 10px;
}

.title {
  width: 100%;
  margin-bottom: 10px;

  i {
    color: #1289fe;
    font-size: 25px;
  }

  span {
    font-size: 25px;
  }
}

::v-deep .el-tree {
  height: 90%;
  overflow-y: auto;
  border: none;
}

::v-deep .el-tree-node__content {
  padding: 5px 0;
}

.container-head {
  display: flex;
  align-items: center;

  img {
    width: 28px;
    height: 28px;
    margin: auto 5px;
    cursor: pointer;
  }

  i {
    font-size: 28px;
    font-weight: 600;
    cursor: pointer;
  }
}
</style>
