<template>
  <div class="examination" style="height:100vh; overflow: hidden;">
    <div style="display: flex">
      <div class="common-title-div-left"
        style="border-right: 1px solid rgb(233, 231, 231); border-bottom: 1px solid rgb(233, 231, 231); height: 100%; min-width: 300px">
        <div class="common-title-name" style="height: 40px; flex-shrink: 0;">
          <img style="width: 25px; height: 25px" src='../../../../assets/img/imgScreen/logo.png' />
          导航树
        </div>
        <el-tree v-loading='dataLoading' ref="baseDataTree" :props="props" :data="baseDataTree" highlight-current
          node-key="id" @node-click="nodeClick" style="height: calc(100% - 40px); overflow: auto;">
        </el-tree>
      </div>
      <div>
        <div class="common-right"
          style="flex: 1; display: flex; flex-direction: column; height: 100%; overflow: hidden;">
          <div class="common-title-div">
            <div class="zy-title-div">
              <img style="width: 25px; height: 25px" src='../../../../assets/img/imgScreen/logo.png' />
              公共代码
            </div>
            <div>
              <el-button icon="el-icon-circle-plus-outline" type="goon" size="mini" @click="addData">新增</el-button>
              <el-button icon="el-icon-edit" type="goon" size="mini" @click="modifyData">修改</el-button>
              <el-button icon="el-icon-circle-close" type="danger" size="mini" @click="deleteData">停用</el-button>
              <el-button icon="el-icon-check" type="goon" size="mini" @click="recoverData">启用</el-button>
            </div>
          </div>
          <!-- <div class="common-table-div" style="margin-bottom:0;margin-top:0">
            <el-table
                v-loading="dataLoading"
                ref="dataTable"
                border
                highlight-current-row
                @selection-change="handleSelectionChange"
                :data="table.list"
                :height="height_top"
                :icore-filter-flag="icoreFilterFlag"
                :header-cell-style="tableHeaderCellStyle"
                @row-click="getAllListByEmpNo"
                :cell-class-name="tableRowClassName"
                :summary-method="getSummaries"
                show-summary
                :exchangeFilterMap="{'validFlag':{'0':'已停用','1':'已启用'}}"
            > -->
          <div class="common-table-div-right" style="height: 100%;">
            <el-table v-loading="dataLoading" ref="dataTable" border :height="tableHeight" class="el-table" style="height:100%"
              highlight-current-row @selection-change="handleSelectionChange" :data="table.list"
              :icore-filter-flag="icoreFilterFlag" :header-cell-style="tableHeaderCellStyle"
              :cell-class-name="tableRowClassName" :summary-method="getSummaries" show-summary>
              <el-table-column type="index" label="NO" fixed="left" align="center">
              </el-table-column>
              <el-table-column type="selection" width="55" align="center"></el-table-column>
              <el-table-column sortable :show-overflow-tooltip="true" min-width="100px" prop="baseCode" label="代码编码"
                align="center"></el-table-column>
              <el-table-column sortable :show-overflow-tooltip="true" min-width="110px" prop="baseName" label="代码名称"
                align="center"></el-table-column>
              <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="isEdit1" label="是否可编辑"
                align="center">
                <!-- <template slot-scope="scope">
              <span v-if="scope.row.isEdit == 1">是</span>
              <span v-else-if="scope.row.isEdit == 0">否</span>
            </template> -->
              </el-table-column>
              <el-table-column sortable :show-overflow-tooltip="true" min-width="120px" prop="isSub1" label="是否允许添加子类"
                align="center">
                <!-- <template slot-scope="scope">
              <span v-if="scope.row.isSub == 1">是</span>
              <span v-else-if="scope.row.isSub == 0">否</span>
           </template> -->
              </el-table-column>
              <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="validFlag1" label="数据状态"
                align="center">
                <!-- <template slot-scope="scope">
              <span v-if="scope.row.validFlag == 1">有效</span>
              <span v-else-if="scope.row.validFlag == 0">无效</span>
          </template> -->
              </el-table-column>
              <el-table-column sortable :show-overflow-tooltip="true" min-width="100px" prop="memo" label="备注"
                align="center"></el-table-column>
              <el-table-column sortable :show-overflow-tooltip="true" min-width="165px" prop="createTime" label="创建时间"
                align="center"></el-table-column>
              <el-table-column sortable :show-overflow-tooltip="true" min-width="80px" prop="createMan" label="创建人"
                align="center"></el-table-column>
              <!-- <el-table-column width="165px" prop="updateTime" label="修改时间" align="center"></el-table-column>
        <el-table-column width="95px" prop="updateMan" label="修改人" align="center"></el-table-column> -->
            </el-table>
          </div>
          <div class="zy-foot-page" style="flex-shrink: 0; height: 50px;">
            <el-pagination v-loading="dataLoading" @size-change="pageSizeChange" @current-change="pageCurrentChange"
              :current-page="page.pageNum" :page-sizes="[10, 10, 50, 100, 100]" :page-size="page.pageSize"
              layout="total, sizes, prev, pager, next, jumper" :total="page.totalPage" background>
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
    <div is="alertComponets" :showFlag="showFlag" :Params="Params" :Params2="Params2" @refresh='refresh'></div>
  </div>
</template>
<script>
import {
  getCookie
} from '@/utils/util.js';
import {
  cookieUserId,
  cookieUserName
} from '@/config/config.js';
import alertComponets from './alertComponents';
let userName = getCookie(cookieUserName);
let userId = getCookie(cookieUserId);
export default {
  components: { alertComponets },
  data() {
    return {
      height_tree: 0,
      headerHeight: 0, // 搜索栏高度
      titleHeight: 0, // 标题栏高度
      footerHeight: 0, // 分页栏高度
      minTableHeight: 250, // 表格最小高度阈值
      resizeObserver: null, // 窗口监听对象
      baseDataTree: [],
      selectBaseCodeNo: '',
      selectBaseItem: {},
      table: {
        list: []
      },
      props: {
        label: (data, node) => {
          return data.baseName
          // if (node.level === 1) {
          //   // 第一层lable为src_name字段
          //   return data.src_name
          // } else if (node.level === 2 || node.level === 3) {
          //   // 第二三层lable为name字段
          //   return data.name
          // }
        },
        // isLeaf: (data, node) => {
        //   if (node.level === 3) {
        //     // 第三层没有下一级节点
        //     return true
        //   }
        // }
      },
      dataLoading: false,
      icoreFilterFlag: true,
      page: {
        pageSize: 50,
        pageNum: 1,
        totalPage: 0
      },
      showFlag: false,
      Params: {},
      Params2: {},
      tableHeight: 0,
      tableWidth: '',
      multipleSelection: [],
      search: {
        strTypeName: '',
        strName: ''
      },
      height_top: 0,
    }
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.calcTableHeight);
  },
  mounted() {
    this.getDataList();
    this.addScreen();
    this.getBaseDataList2()
    window.addEventListener('resize', this.calcTableHeight);
    this.resizeObserver = new ResizeObserver(() => {
      this.calcTableHeight();
    });
    // const headerEl = document.querySelector('.zy-head-search');
    const titleEl = document.querySelector('.common-title-div');
    const footerEl = document.querySelector('.zy-foot-page');
    // if (headerEl) this.resizeObserver.observe(headerEl);
    if (titleEl) this.resizeObserver.observe(titleEl);
    if (footerEl) this.resizeObserver.observe(footerEl);
  },
  created() {
    // this.tableHeight = window.innerHeight - 120
    // this.tableWidth = window.innerWidth - 500
  },
  methods: {
    calcTableHeight() {
      this.$nextTick(() => {
        // const headerEl = document.querySelector('.zy-head-search');
        const titleEl = document.querySelector('.common-title-div');
        const footerEl = document.querySelector('.zy-foot-page');

        // this.headerHeight = headerEl ? headerEl.offsetHeight : 0;
        this.titleHeight = titleEl ? titleEl.offsetHeight : 0;
        this.footerHeight = footerEl ? footerEl.offsetHeight : 0;

        // const totalReserveHeight = this.headerHeight + this.titleHeight + this.footerHeight + 20; // 20为额外边距（可调整）

        // const totalReserveHeight = this.titleHeight + this.footerHeight + 20;
        const calcHeight = window.innerHeight - this.titleHeight - this.footerHeight;
        this.tableHeight = calcHeight < this.minTableHeight ? this.minTableHeight : calcHeight;
        console.log('tableHeight:', this.tableHeight)
        console.log('========== 高度调试 ==========');
        console.log('窗口高度:', window.innerHeight);
        console.log('表格容器高度:', this.titleHeight);
        console.log('分页高度:', this.footerHeight);
        // console.log('保留高度:', totalReserveHeight);
        console.log('计算高度:', calcHeight);
        console.log('最终tableHeight:', this.tableHeight);
        console.log('页面总高度:', document.body.scrollHeight);
        console.log('左侧树高度:', document.querySelector('.common-title-div-left').offsetHeight);
        console.log('右侧容器高度:', document.querySelector('.common-table-div-right').parentElement.offsetHeight);
        this.$refs.dataTable.doLayout();
      });
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
        }
        if (index === 1) {
          sums[index] = data.length;
        }
      });
      return sums;
    },
    refresh() {
      // this.getDataList();
      this.getBaseDataList2();
      this.getBaseDataList();
      this.selectBaseItem = {}
    },
    addData() {
      let _this = this;
      if (_this.selectBaseItem.isSub === '0') {
        this.$message.warning('该父类不允许添加子类！')
      } else {
        _this.Params2 = []
        _this.showFlag = !_this.showFlag;
        _this.Params = null;
        _this.Params2 = _this.selectBaseItem
      }
    },
    modifyData() {
      let _this = this;
      if (_this.multipleSelection.length !== 1) {
        this.$message.warning('请勾选您要修改的一条数据！')
      } else if (_this.multipleSelection[0].isEdit === '0') {
        this.$message.warning('该数据不允许修改！')
      } else {
        _this.showFlag = !_this.showFlag;
        _this.Params = _this.multipleSelection
      }
    },
    recoverData() {
      let _this = this;
      if (_this.multipleSelection.length < 1) {
        this.$message.warning('请勾选您要启用的数据！')
      } else {
        for (var i = 0; i < _this.multipleSelection.length; i++) {
          _this.multipleSelection[i].updateMan = userName;
          _this.multipleSelection[i].updateNo = userId
        }
        _this.axios.post('pass/baseManagement/v1/limsbaseinfos/recover', _this.multipleSelection, { individualType: 'json' }).then(res => {
          if (res.succeed) {
            _this.dialogTableVisible = false;
            this.$message.success('启用成功');
            _this.refresh()
          } else {
            this.$message.error(res.message)
          }
        }).catch(e => {
          this.$message.error(e.message)
        })
      }
    },
    deleteData() {
      let _this = this;
      if (_this.multipleSelection.length < 1) {
        this.$message.warning('请勾选您要停用的数据！')
      } else {
        for (var i = 0; i < _this.multipleSelection.length; i++) {
          _this.multipleSelection[i].updateMan = userName;
          _this.multipleSelection[i].updateNo = userId
        }
        _this.axios.post('pass/baseManagement/v1/limsbaseinfos/abolish', _this.multipleSelection, { individualType: 'json' }).then(res => {
          if (res.succeed) {
            _this.dialogTableVisible = false;
            this.$message.success('停用成功');
            _this.refresh()
          } else {
            this.$message.error(res.message)
          }
        }).catch(e => {
          this.$message.error(e.message)
        })
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    pageSizeChange(size) {
      this.page.pageSize = size;
      this.getDataList();
    },
    pageCurrentChange(index) {
      this.page.pageNum = index;
      this.getDataList();
    },
    addScreen() {
      this.$nextTick(() => {
        let ss = document.createElement('div');
        ss.innerHTML = '筛选';
        ss.style = 'text-align: center;'
        this.$refs.dataTable.$el.getElementsByClassName('el-table__fixed')[0].getElementsByTagName('td')[0].appendChild(ss);
      });
    },
    getDataList() {
      this.dataLoading = true;
      this.axios.get('pass/baseManagement/v1/limsbaseinfos/' + '?pageNum=' + this.page.pageNum + '&pageSize=' + this.page.pageSize + '&levelNum=0')
        .then(res => {
          this.dataLoading = false;
          this.table.list = res.data.list;
          for (let i = 0; i < this.table.list.length; i++) {
            if (this.table.list[i].validFlag === '0') {
              this.table.list[i].validFlag1 = '无效'
            } else if (this.table.list[i].validFlag === '1') {
              this.table.list[i].validFlag1 = '有效'
            }
          }
          for (let i = 0; i < this.table.list.length; i++) {
            if (this.table.list[i].isEdit === '0') {
              this.table.list[i].isEdit1 = '否'
            } else if (this.table.list[i].isEdit === '1') {
              this.table.list[i].isEdit1 = '是'
            }
          }
          for (let i = 0; i < this.table.list.length; i++) {
            if (this.table.list[i].isSub === '0') {
              this.table.list[i].isSub1 = '否'
            } else if (this.table.list[i].isSub === '1') {
              this.table.list[i].isSub1 = '是'
            }
          }
          this.page.totalPage = res.data.total;
        }).catch(e => {
          this.dataLoading = false;
        });
    },
    nodeClick(item) {
      this.selectBaseCodeNo = item.baseCode;
      this.selectBaseItem = item;
      this.getBaseDataList();
    },
    getBaseDataList() {
      this.dataLoading = true;
      this.axios.get('pass/baseManagement/v1/limsbaseinfos/' + 'like/?pageNum=' + this.page.pageNum + '&pageSize=' + this.page.pageSize +
        '&baseCode=' + this.selectBaseCodeNo)
        .then(res => {
          this.dataLoading = false;
          this.table.list = res.data.list;
          for (let i = 0; i < this.table.list.length; i++) {
            if (this.table.list[i].validFlag === '0') {
              this.table.list[i].validFlag1 = '无效'
            } else if (this.table.list[i].validFlag === '1') {
              this.table.list[i].validFlag1 = '有效'
            }
          }
          for (let i = 0; i < this.table.list.length; i++) {
            if (this.table.list[i].isEdit === '0') {
              this.table.list[i].isEdit1 = '否'
            } else if (this.table.list[i].isEdit === '1') {
              this.table.list[i].isEdit1 = '是'
            }
          }
          for (let i = 0; i < this.table.list.length; i++) {
            if (this.table.list[i].isSub === '0') {
              this.table.list[i].isSub1 = '否'
            } else if (this.table.list[i].isSub === '1') {
              this.table.list[i].isSub1 = '是'
            }
          }
          this.page.totalPage = res.data.total;
        }).catch(e => {
          this.dataLoading = false;
        });
    },
    getBaseDataList2() {
      this.axios.post("pass/baseManagement/v1/limsbaseinfos/findBaseInfoAllTree").then(response => {
        this.baseDataTree = response.data
        // this.initTree(response.data)
      });
      // this.axios.get('pass/baseManagement/v1/limsbaseinfos/' + '?pageNum=1' + '&pageSize=1000')
      //   .then(res => {
      //     this.initTree(res.data.list);
      //   });
    },
    initTree(data) {
      //  for (let i = 0; i < data.length; i++) {
      //   if (data[i].validFlag === '0') {
      //      data[i].validFlag1 = '无效'
      //   } else if (data[i].validFlag === '1') {
      //      data[i].validFlag1 = '有效'
      //   }
      //   }
      //   for (let i = 0; i < data.length; i++) {
      //   if (data[i].isEdit === '0') {
      //     data[i].isEdit1 = '否'
      //   } else if (data[i].isEdit === '1') {
      //     data[i].isEdit1 = '是'
      //   }
      //   }
      //   for (let i = 0; i < data.length; i++) {
      //   if (data[i].isSub === '0') {
      //     data[i].isSub1 = '否'
      //   } else if (data[i].isSub === '1') {
      //     data[i].isSub1 = '是'
      //   }
      //   }
      var list = [];
      var parentList = [];
      for (var i = 0; i < data.length; i++) {
        data[i].children = [];
        data[i].label = data[i].baseName;
        if (data[i].baseCode === data[i].sortCode) {
          parentList.push(data[i]);
        } else {
          list.push(data[i]);
        }
      }
      this.getChildren(parentList, list);
      this.baseDataTree = parentList;
    },
    getChildren(parentList, list) {
      for (var i = 0; i < parentList.length; i++) {
        var childrenList = [];
        for (var j = 0; j < list.length; j++) {
          if (parentList[i].baseCode === list[j].sortCode) {
            parentList[i].children.push(list[j]);
            childrenList.push(list[j]);
          }
        }
        if (childrenList.length > 0) {
          this.getChildren(childrenList, list);
        }
      }
    },
    tableRowClassName({
      row, column, rowIndex, columnIndex
    }) {
      if (columnIndex === 6) {
        if (row.validFlag !== '1') {
          return 'error-row';
        }
        return '';
      }
    },
    tableHeaderCellStyle() {
      return 'color: rgb(255,255,255);'
      // border-bottom: 1px solid #DCDFE7;'
    }
  }
}
</script>
<style lang="less">
.el-tree {
  overflow-x: hidden !important;
}

.el-tree-node {
  .el-tree-node__label {
    border-bottom: 0;
  }
}
</style>
