<template>
  <div class="app-container">
    <!-- 顶部搜索能力 -->
    <el-form :model="searchParmas" label-width="130px">
      <el-row>
        <el-col :span="6">
          <el-form-item label="企业名称">
            <el-input v-model="searchParmas.enterpriseName" placeholder="请输入企业名称" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="集团单位">
            <el-input v-model="searchParmas.groupUnit" placeholder="请输入集团单位" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="股份主管部门" style="margin-right: 20px">
            <el-input v-model="searchParmas.shareSuperdepart" placeholder="请输入股份主管部门" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <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>

    <!-- 多级表格 -->
    <el-table
      v-loading="loading"
      ref="multipleTable"
      :data="varList"
      :header-cell-style="{ 'font-weight': 'bold', color: '#000' }"
      :max-height="tableMaxHeight"
      tooltip-effect="dark"
      border
      fit
      stripe
      highlight-current-row
      @selection-change="selectionChange"
      @select-all="selectAll">
      <!-- 固定列 -->
      <el-table-column :selectable="handleSelectWithDifferentStatus" type="selection" width="55" fixed align="center" />

      <!-- 序号列及弹出框 -->
      <el-table-column type="index" fixed="left" label="序号" align="center" width="90">
        <template slot="header">
          <el-popover ref="tablePopover" v-model="popoverVisible" width="240" trigger="manual">
            <span slot="reference" style="cursor: pointer" @click="openPopover">
              序号
              <i class="el-icon-finished" style="font-weight: bold" />
            </span>
            <div class="popoverCheckBoxArea">
              <el-checkbox
                v-model="checked"
                :indeterminate="indeterminate"
                @change="handleCheckAllChange">全选</el-checkbox>
              <div style="margin: 10px 0" />
              <el-tree
                ref="treeRef"
                :data="dataSourceForTree"
                :props="defaultProps"
                :default-expand-all="true"
                show-checkbox
                node-key="id"
                class="treeColumnStyle"
                @check-change="changeCheck" />
            </div>
            <div class="popoverCheckBoxButton">
              <el-button size="mini" @click="canclePopover">取消</el-button>
              <el-button type="primary" size="mini" @click="confirmPopover">确定</el-button>
            </div>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column v-if="showColumn('RELEVANT_UNIT_NAME')" prop="RELEVANT_UNIT_NAME" label="企业名称" align="center" show-overflow-tooltip width="120"/>
      <el-table-column v-if="showColumn('CORP_TYPE_NAME')" prop="CORP_TYPE_NAME" label="集团单位" show-overflow-tooltip align="center" width="120"/>
      <el-table-column v-if="showColumn('MAIN_DEPARTMENT_NAME')" prop="MAIN_DEPARTMENT_NAME" label="股份主管部门" align="center" width="120"/>
      <el-table-column v-if="showColumn('CORP_SIZE_NAME')" prop="CORP_SIZE_NAME" label="企业规模" align="center" width="120"/>
      <el-table-column v-if="showColumn('CONTACT_PERSON')" prop="CONTACT_PERSON" label="主要负责人" align="center" width="120"/>
      <el-table-column v-if="showColumn('CONTACT_TEL')" prop="CONTACT_TEL" label="主要负责人联系电话" align="center" width="120"/>
      <el-table-column v-if="showColumn('REGISTER_COUNT')" prop="REGISTER_COUNT" label="注册人数" align="center" width="120"/>
      <el-table-column v-if="showColumn('PASS_COUNT')" prop="PASS_COUNT" label="培训合格人数" align="center" width="120"/>

      <el-table-column v-if="showColumn('personAgeStruc')" prop="personAgeStruc" label="人员年龄结构" align="center">
        <el-table-column v-if="showColumn('AVG_AGE')" prop="AVG_AGE" label="平均年龄" align="center" width="120"/>
        <el-table-column v-if="showColumn('MORE_THAN_60_COUNT')" prop="MORE_THAN_60_COUNT" label="大于60岁人数" align="center" width="120"/>
        <el-table-column v-if="showColumn('BETWEEN_55_AND_60_COUNT')" prop="BETWEEN_55_AND_60_COUNT" label="55-60岁人数" align="center" width="120"/>
        <el-table-column v-if="showColumn('LESS_THAN_55_COUNT')" prop="LESS_THAN_55_COUNT" label="55岁以下人数" align="center" width="120"/>
      </el-table-column>

      <el-table-column v-if="false" prop="workExprien" label="在港工作经历（年）" align="center" width="120"/>

      <el-table-column v-if="showColumn('personEducation')" prop="personEducation" label="人员学历" align="center">
        <el-table-column v-if="showColumn('BELOW_HIGH_SCHOOL')" prop="BELOW_HIGH_SCHOOL" label="高中以下" align="center" width="120"/>
        <el-table-column v-if="showColumn('HIGH_SCHOOL')" prop="HIGH_SCHOOL" label="高中" align="center" width="120"/>
        <el-table-column v-if="showColumn('TECHNICAL_SCHOOL')" prop="TECHNICAL_SCHOOL" label="技工" align="center" width="120"/>
        <el-table-column v-if="showColumn('TECHNICAL_SECONDARY_SCHOOL')" prop="TECHNICAL_SECONDARY_SCHOOL" label="中专或中等技术学校" align="center" width="130"/>
        <el-table-column v-if="showColumn('JUNIOR_COLLEGE')" prop="JUNIOR_COLLEGE" label="大学专科或专科院校" align="center" width="130"/>
        <el-table-column v-if="showColumn('UNDERGRADUATE')" prop="UNDERGRADUATE" label="大学本科" align="center" width="120"/>
        <el-table-column v-if="showColumn('ABOVE_UNDERGRADUATE')" prop="ABOVE_UNDERGRADUATE" label="大学本科以上" align="center" width="120"/>
      </el-table-column>

      <el-table-column v-if="showColumn('man')" prop="man" label="男职工" align="center">
        <el-table-column v-if="showColumn('MAN_COUNT')" prop="MAN_COUNT" label="人数" align="center" width="120"/>
        <el-table-column v-if="showColumn('MAN_PERCENT')" prop="MAN_PERCENT" label="占比" align="center" width="120"/>
      </el-table-column>

      <el-table-column v-if="showColumn('woman')" prop="woman" label="女职工" align="center">
        <el-table-column v-if="showColumn('WOMAN_COUNT')" prop="WOMAN_COUNT" label="人数" align="center" width="120"/>
        <el-table-column v-if="showColumn('WOMAN_PERCENT')" prop="WOMAN_PERCENT" label="占比" align="center" width="120"/>
      </el-table-column>

      <el-table-column v-if="showColumn('insurance')" prop="insurance" label="保险相关" align="center">
        <el-table-column v-if="showColumn('SOCIAL')" prop="SOCIAL" label="有社保人数" align="center" width="120"/>
        <el-table-column v-if="showColumn('OCCUPATIONAL_INJURY')" prop="OCCUPATIONAL_INJURY" label="有工伤保险人数" align="center" width="120"/>
        <el-table-column v-if="showColumn('COMMERCIAL_INSURANCE')" prop="COMMERCIAL_INSURANCE" label="有商业保险人数" align="center" width="120"/>
        <el-table-column v-if="showColumn('OTHER_INSURANCE')" prop="OTHER_INSURANCE" label="其他保险人数" align="center" width="120"/>
        <el-table-column v-if="showColumn('NO_INSURANCE')" prop="NO_INSURANCE" label="无保险人数" align="center" width="120"/>
      </el-table-column>

      <el-table-column v-if="showColumn('numOfSpecialOperation')" prop="numOfSpecialOperation" label="取得特种作业证书人数" align="center">
        <el-table-column v-if="showColumn('SPECIAL_TOTAL')" prop="SPECIAL_TOTAL" label="总人数" align="center" width="120"/>
        <el-table-column v-if="showColumn('ELECTRICIAN')" prop="ELECTRICIAN" label="电工作业" align="center" width="120"/>
        <el-table-column v-if="showColumn('WELDING')" prop="WELDING" label="焊接与热切割作业" align="center" width="120"/>
        <el-table-column v-if="showColumn('HIGH_WORK')" prop="HIGH_WORK" label="高处作业" align="center" width="120"/>
        <el-table-column v-if="showColumn('CRANE_OPERATION')" prop="CRANE_OPERATION" label="起重机械作业" align="center" width="120"/>
        <el-table-column v-if="showColumn('MOTOR_VEHICLE')" prop="MOTOR_VEHICLE" label="企业内机动车辆作业" align="center" width="130"/>
        <el-table-column v-if="showColumn('OTHER_SPECIAL')" prop="OTHER_SPECIAL" label="其他特种作业" align="center" width="120"/>
      </el-table-column>

    </el-table>

    <div class="page-btn-group">
      <div>
        <el-button type="primary" icon="el-icon-upload2" @click="handleExportBtn">批量导出</el-button>
      </div>
      <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>
  </div>
</template>

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

export default {
  components: { Pagination },
  directives: { waves },

  data() {
    return {
      config: config,
      searchParmas: {
        enterpriseName: '',
        groupUnit: '',
        shareSuperdepart: ''
      },
      varList: [],
      // el-table表格的动态高度值
      tableMaxHeight: 0,
      // 列表加载态
      loading: false,
      // 列表表格分页参数
      listQuery: {
        page: 1,
        limit: 10
      },
      total: 0,
      // 选择展示的字段数组
      dataSourceForTree: [
        {
          id: '1',
          label: '企业名称',
          value: 'RELEVANT_UNIT_NAME',
          disabled: false,
          show: true,
          children: []
        },
        {
          id: '2',
          label: '集团单位',
          value: 'CORP_TYPE_NAME',
          disabled: false,
          show: true,
          children: []
        },
        {
          id: '3',
          label: '股份主管部门',
          value: 'MAIN_DEPARTMENT_NAME',
          disabled: false,
          show: true,
          children: []
        },
        {
          id: '4',
          label: '企业规模',
          value: 'CORP_SIZE_NAME',
          disabled: false,
          show: true,
          children: []
        },
        {
          id: '5',
          label: '主要负责人',
          value: 'CONTACT_PERSON',
          disabled: false,
          show: true,
          children: []
        },
        {
          id: '6',
          label: '主要负责人联系电话',
          value: 'CONTACT_TEL',
          disabled: false,
          show: true,
          children: []
        },
        {
          id: '7',
          label: '注册人数',
          value: 'REGISTER_COUNT',
          disabled: false,
          show: true,
          children: []
        },
        {
          id: '8',
          label: '培训合格人数',
          value: 'PASS_COUNT',
          disabled: false,
          show: true,
          children: []
        },
        {
          id: '9',
          label: '人员年龄结构',
          disabled: false,
          value: 'personAgeStruc',
          show: true,
          children: [
            {
              id: '9-1',
              label: '平均年龄',
              value: 'AVG_AGE',
              disabled: false,
              show: true,
              children: []
            },
            {
              id: '9-2',
              label: '大于60岁人数',
              value: 'MORE_THAN_60_COUNT',
              disabled: false,
              show: true,
              children: []
            },
            {
              id: '9-3',
              label: '55-60岁人数:',
              value: 'BETWEEN_55_AND_60_COUNT',
              disabled: false,
              show: true,
              children: []
            },
            {
              id: '9-4',
              label: '55岁以下人数',
              value: 'LESS_THAN_55_COUNT',
              disabled: false,
              show: true,
              children: []
            }
          ]
        },
        {
          id: '11',
          label: '人员学历',
          disabled: false,
          value: 'personEducation',
          show: true,
          children: [
            {
              id: '11-1',
              label: '高中以下',
              value: 'BELOW_HIGH_SCHOOL',
              disabled: false,
              show: true,
              children: []
            },
            {
              id: '11-2',
              label: '高中',
              value: 'HIGH_SCHOOL',
              disabled: false,
              show: true,
              children: []
            },
            {
              id: '11-3',
              label: '技工',
              value: 'TECHNICAL_SCHOOL',
              disabled: false,
              show: true,
              children: []
            },
            {
              id: '11-4',
              label: '中专或中等技术学校',
              value: 'TECHNICAL_SECONDARY_SCHOOL',
              disabled: false,
              show: true,
              children: []
            },
            {
              id: '11-5',
              label: '大学专科或专科院校',
              value: 'JUNIOR_COLLEGE',
              disabled: false,
              show: true,
              children: []
            },
            {
              id: '11-6',
              label: '大学本科',
              value: 'UNDERGRADUATE',
              disabled: false,
              show: true,
              children: []
            },
            {
              id: '11-7',
              label: '大学本科以上',
              value: 'ABOVE_UNDERGRADUATE',
              disabled: false,
              show: true,
              children: []
            }
          ]
        },
        {
          id: '12',
          label: '男职工',
          value: 'man',
          show: true,
          disabled: false,
          children: [
            {
              id: '12-1',
              label: '人数',
              value: 'MAN_COUNT',
              disabled: false,
              show: true,
              children: []
            },
            {
              id: '12-2',
              label: '占比',
              value: 'MAN_PERCENT',
              disabled: false,
              show: true,
              children: []
            }
          ]
        },
        {
          id: '13',
          label: '女职工',
          show: true,
          value: 'woman',
          disabled: false,
          children: [
            {
              id: '13-1',
              label: '人数',
              value: 'WOMAN_COUNT',
              disabled: false,
              show: true,
              children: []
            },
            {
              id: '13-2',
              label: '占比',
              value: 'WOMAN_PERCENT',
              disabled: false,
              show: true,
              children: []
            }
          ]
        },
        {
          id: '14',
          label: '保险相关',
          value: 'insurance',
          disabled: false,
          show: true,
          children: [
            {
              id: '14-1',
              label: '有社保人数',
              value: 'SOCIAL',
              disabled: false,
              show: true,
              children: []
            },
            {
              id: '14-2',
              label: '有工伤保险人数',
              value: 'OCCUPATIONAL_INJURY',
              disabled: false,
              show: true,
              children: []
            },
            {
              id: '14-3',
              label: '有商业保险人数',
              value: 'COMMERCIAL_INSURANCE',
              disabled: false,
              show: true,
              children: []
            },
            {
              id: '14-4',
              label: '其他保险人数',
              value: 'OTHER_INSURANCE',
              disabled: false,
              show: true,
              children: []
            },
            {
              id: '14-5',
              label: '无保险人数',
              value: 'NO_INSURANCE',
              disabled: false,
              show: true,
              children: []
            }
          ]
        },
        {
          id: '15',
          label: '取得特种作业证书人数',
          value: 'numOfSpecialOperation',
          disabled: false,
          show: true,
          children: [
            {
              id: '15-1',
              label: '总人数',
              value: 'SPECIAL_TOTAL',
              disabled: false,
              show: true,
              children: []
            },
            {
              id: '15-2',
              label: '电工作业',
              value: 'ELECTRICIAN',
              disabled: false,
              show: true,
              children: []
            },
            {
              id: '15-3',
              label: '焊接与热切割作业',
              value: 'WELDING',
              disabled: false,
              show: true,
              children: []
            },
            {
              id: '15-4',
              label: '高处作业',
              value: 'HIGH_WORK',
              disabled: false,
              show: true,
              children: []
            },
            {
              id: '15-5',
              label: '起重机械作业',
              value: 'CRANE_OPERATION',
              disabled: false,
              show: true,
              children: []
            },
            {
              id: '15-6',
              label: '企业内机动车辆作业',
              value: 'MOTOR_VEHICLE',
              disabled: false,
              show: true,
              children: []
            },
            {
              id: '15-7',
              label: '其他特种作业',
              value: 'OTHER_SPECIAL',
              disabled: false,
              show: true,
              children: []
            }
          ]
        }
      ],
      treeCheckedIds: [], // 保存被选中的树节点 id
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      checked: true, // 全选状态
      popoverVisible: false,
      indeterminate: false, // 半选状态
      selectionSelected: [],
      head: []
    }
  },
  created() {
    // 当页面初始化后立刻计算 el-table 表格的动态高度值
    this.tableMaxHeight = window.innerHeight - 230
    // 页面初始化渲染后,立刻调用的处理函数等方法
    this.getList() // 调用获取列表数据的方法
  },
  mounted() {
    // 当前页面挂载之后立刻计算 el-table 表格的动态高度值
    this.$nextTick(() => {
      window.onresize = () => {
        this.tableMaxHeight = window.innerHeight - 230
      }
      this.$refs.treeRef.setCheckedNodes(
        this.dataSourceForTree.filter(node => !node.disabled)
      )
    })
  },
  methods: {
    handleSelectWithDifferentStatus(row, rowIndex) {
      return true
    },
    getQuery() {
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection()
      }
      this.listQuery = {
        page: 1,
        limit: 10
      }
      this.getList()
    },
    goKeyReset() {
      this.searchParmas = {
        enterpriseName: '',
        groupUnit: '',
        shareSuperdepart: ''
      }
      this.getQuery()
    },
    /** 获取列表数据 */
    getList() {
      this.loading = true
      requestFN(
        '/xgf/user/statistics?showCount=' +
        this.listQuery.limit +
        '&currentPage=' +
        this.listQuery.page,
        { KEYWORDS: this.KEYWORDS, ISSMALL: '2' }
      )
        .then(data => {
          this.loading = false
          this.varList = data.list
          this.total = data.page.totalResult
        })
        .catch(e => {
          console.log(e)
          this.loading = false
        })
    },
    selectionChange(row) {
      this.selectionSelected = row
    },
    selectAll(selection) {
      this.selectionSelected = selection
    },
    handleExportBtn() {
      const ids = this.selectionSelected
        .map(item => {
          return item.CORPINFO_ID
        })
        .toString(',')
      const result = this.collectValues(this.dataSourceForTree)
      this.head = result.toString(',')

      if (
        this.selectionSelected.map(item => {
          return item.CORPINFO_ID
        }).length === 0
      ) {
        // 不用选啦~不选就是全部导出 modified by xuyifeng
        // this.$message.error('请选择数据项后导出!')
      }
      this.exportExcelHandler(ids, this.head)
    },
    collectValues(data, resultArray = []) {
      data.forEach(item => {
        if (item.show) {
          resultArray.push(item.value) // 将满足条件的 value 存入结果数组中
        }
        if (item.children && item.children.length > 0) {
          this.collectValues(item.children, resultArray) // 递归处理子节点
        }
      })
      return resultArray
    },
    // 导出指定数据项至 excel 表格
    exportExcelHandler(ids, head) {
      window.open(`${this.config.httpurl}/xgf/user/exportExcel?ids=${ids}&head=${head}`)
    },
    // 点击操作打开菜单选择框
    openPopover() {
      this.popoverVisible = true
    },
    // 点击取消关闭菜单选择框
    canclePopover() {
      this.popoverVisible = false
    },
    // 处理多选框全部选中
    handleCheckAllChange() {
      if (this.checked) {
        this.$refs.treeRef.setCheckedNodes(
          this.dataSourceForTree.filter(node => !node.disabled)
        )
        this.treeCheckedIds = this.$refs.treeRef
          .getCheckedNodes(false, true)
          .map(i => i.id)
        this.head = this.$refs.treeRef.getCheckedNodes(false, true).map(i => i.value)
      } else {
        this.$refs.treeRef.setCheckedNodes([])
        this.treeCheckedIds = []
        this.head = []
      }
    },
    // 多选框发生改变的事件处理
    changeCheck(checkedNode, isChecked, selfNode) {
      const res = this.updateShowProperty(
        this.dataSourceForTree,
        checkedNode,
        isChecked
      )
      this.dataSourceForTree = res
    },
    updateShowProperty(dataSource, curNode, isChecked) {
      // 定义递归函数
      function recursiveUpdate(node) {
        // 记录所有子节点是否都未选中
        let allChildrenUnchecked = true

        // 递归处理子节点
        if (node.children && node.children.length > 0) {
          node.children.forEach(child => {
            const childChecked = recursiveUpdate(child)
            if (childChecked) {
              allChildrenUnchecked = false
            }
          })
        }

        // 更新当前节点的 show 属性
        if (node.id === curNode.id) {
          node.show = isChecked
        }

        // 更新父节点的 show 属性
        if (node.children && node.children.length > 0) {
          if (allChildrenUnchecked) {
            node.show = false
          } else {
            node.show = true
          }
        }

        return node.show // 返回当前节点的 show 属性值
      }
      // 遍历整个数据源进行更新
      dataSource.forEach(node => recursiveUpdate(node))
      return dataSource
    },
    // 弹出框确认的事件处理
    confirmPopover() {
      this.popoverVisible = false
    },
    // 控制表格列的显示与隐藏
    showColumn(columnValue) {
    // 在数据源中查找与传入列值匹配的项
      const findItem = (data, value) => {
        for (let i = 0; i < data.length; i++) {
          const item = data[i]
          if (item.value === value) {
            return item
          }
          if (item.children && item.children.length > 0) {
            const foundInChildren = findItem(item.children, value)
            if (foundInChildren) {
              return foundInChildren
            }
          }
        }
        return null
      }

      // 查找数据源中对应的列项
      const foundItem = findItem(this.dataSourceForTree, columnValue)

      // 返回该列项的 show 属性，如果不存在则返回 false
      return foundItem ? foundItem.show : false
    }
  }
}
</script>

<style lang="scss" scoped>
.treeColumnStyle {
  height: 400px;
  overflow-y: auto;
  overflow-x: auto;

  &::-webkit-scrollbar {
    display: none;
  }
}
</style>
