vxetable的使用-中位数,最大最小计算结果展示在表头上

head是表头,这个是构造出来的数据,渲染表头

   head:[{
                    label:'全',
                    prop:'1000',
                  },
                    {
                      label:'市',
                      prop:'10001',
                    },
                  ]
                  这个是下面返回的数据,需要展示在下面的数据,这个个数据也是构造的
                  data:[
                      {
                    1000:'2',
                    10001:'1',
                    year:'2001'
                  },
                    {
                      1000:'2',
                      10001:'1',
                      year:'2002'
                    },
                    {
                      1000:'2',
                      10001:'1',
                      year:'2003'
                    },
                  ]
               需要在表头上展示计算结果,根据prop属性将head和data关联起来
                  head:[
                      {
                    label:'全',
                    prop:'1000',
                    add:4,
                    average:2
                  },
                    {
                      label:'市',
                      prop:'10001',
                      add:2,
                      average:1
                    },
                  ]
              处理的方法如下
  //开始计算每一行的数据放到每一个属性中
                this.normalHeader.forEach(item => {
                  this.tableHeaderData2.push({
                    label: item.cname,
                    prop: item.code,
                    showFlag: item.showFlag,
                    desc: '',
                    //求和
                    sum: 0,
                    //求平均
                    average: 0,
                    //求最大值
                    max: Number.NEGATIVE_INFINITY,
                    //求最小值
                    min: Number.POSITIVE_INFINITY,
                    //求方差
                    variance: 0,
                    //求标准差
                    standardDeviation: 0,
                    //求中位数
                    median: 0
                  })
                });
                let total = 0;
                let sqrSum = 0;
                let validCount = 0;
                let values = [];
// 遍历数据计算每个属性的总和、平均值、最大值、最小值、方差、标准差和中位数
                tableData.forEach(rowData => {
                  this.tableHeaderData2.forEach(headerData => {
                    let prop = headerData.prop;
                    let value = rowData[prop] * 1;
                    if (!isNaN(value)) { // 判断是否为数字
                      headerData.sum += value;
                      headerData.max = Math.max(headerData.max, value);
                      headerData.min = Math.min(headerData.min, value);
                      total += value;
                      sqrSum += value * value;
                      values.push(value);
                      validCount++;
                    }
                  });
                });
// 计算平均值、方差、标准差和中位数
                this.tableHeaderData2.forEach(headerData => {
                  let prop = headerData.prop;
                  let count = validCount;
                  let sqrSum = values.reduce((prev, curr) => {
                    if (!isNaN(curr)) {
                      return prev + (curr - headerData.average) ** 2;
                    } else {
                      return prev;
                    }
                  }, 0);
                  let sortedValues = values.filter(value => !isNaN(value)).sort((a, b) => a - b);
                  let medianIndex = Math.floor(sortedValues.length / 2);
                  let median = sortedValues.length % 2 === 0 ? (sortedValues[medianIndex] + sortedValues[medianIndex - 1]) / 2 : sortedValues[medianIndex];
                  if (count > 1) {
                    headerData.average = (headerData.sum / validCount).toFixed(2);
                    headerData.variance = (sqrSum / (count - 1)).toFixed(2);
                    headerData.standardDeviation = Math.sqrt(headerData.variance).toFixed(2);
                  }
                  headerData.median = median.toFixed(2);
                });
                this.tableHeaderData2.forEach(headerData => {
                  let prop = headerData.prop;
                  let desc = `${headerData.label}:
sum= ${headerData.sum}\n
average= ${headerData.average}\n
max= ${headerData.max}\n
min= ${headerData.min}\n
variance= ${headerData.variance}\n
standardDeviation= ${headerData.standardDeviation}\n
median= ${headerData.median}`;


                  headerData.desc = desc;
                });
  <vxe-table border
                 v-if="zhuanIndex == 2"
                 highlight-hover-row     
                 ref="multipleTable2"
                 height="100%"
                 :selection-config="{ checkField: 'checked', trigger: 'cell', highlight: true }"
                 :checkbox-config="{ range: true }"
                 @checkbox-all="selectAllChangeEvent"
                 @checkbox-change="selectChangeEvent"
                 :sort-config="{multiple: true, trigger: 'cell',chronological:true,
      sortMethod: customSortMethod}" :show-overflow='true' :menu-config="tableMenu"
                 :show-header-overflow="true" :scroll-y="{enabled: false}"
                 style="width: 101%; height: 648px" :loading="loading" :resizable="true" :data="tableData"
                 @menu-click="menuClick" trigger="cell"
      >
        <!-- <vxe-table-column title="序号" type="seq" width="60"></vxe-table-column> -->
        <vxe-column type="checkbox" title=""  :width="60"></vxe-column>
        <vxe-table-column
            v-for="(table, $index) in tableHeaderData2"
            :key="Math.random()"
            :field="table.prop"
            :title="table.desc ? table.desc : table.label"
            :column-key="table.prop"
            :width="table.label == '指标' ? '328' : '110'"
            :sortable="true"
            :ellipsis="true"
            :header-render="renderHeader"
            :cell-render="renderCell"
        >

        </vxe-table-column>
      </vxe-table>

<vxe-table border
v-if=“zhuanIndex == 2”
highlight-hover-row //选中行高亮
ref=“multipleTable2” //绑定的domId,如果需要对表格进行更新,更加精准
height=“100%” //设置高度
:selection-config=“{ checkField: ‘checked’, trigger: ‘cell’, highlight: true }” //多选的收添加的
:checkbox-config=“{ range: true }” //多选的收添加的
@checkbox-all=“selectAllChangeEvent” //多选的方法全选
@checkbox-change=“selectChangeEvent”//多选的方法,选中一个的时候或者取消一个的时候
:sort-config=“{multiple: true, trigger: ‘cell’,chronological:true,
sortMethod: customSortMethod}” //排序的方法
:show-overflow=‘true’ //展示超过的,如果不添加,超出的表格就不展示
:menu-config=“tableMenu” //右键菜单(点击右键展示数据勘误)
:show-header-overflow=“true” //表头超出部分是否展示,有这个属性超过的内容就会悬浮展示,否则就会撑大表格展示
:scroll-y=“{enabled: false}” //自动换行
style=“width: 101%; height: 648px”
:loading=“loading” //加载动画
:resizable=“true”
:data=“tableData”//数据
@menu-click=“menuClick” //点击菜单的时候(点击数据勘误的时候执行的操作)
trigger=“cell”
>


<vxe-table-column
v-for=“(table, $index) in tableHeaderData2”
:key=“Math.random()”//更新的时候唯一,在引入之后可以更新
:field=“table.prop”
:title=“table.desc ? table.desc : table.label”//展示的内容
:column-key=“table.prop”
:width=“table.label == ‘指标’ ? ‘328’ : ‘110’”
:sortable=“true”
:ellipsis=“true”
:header-render=“renderHeader”
:cell-render=“renderCell”
>

    </vxe-table-column>
  </vxe-table>
控制表格的样式
 renderHeader({column}) {
      return (
          '<div style="width: 100px; word-wrap: break-word">' + column.getTitle() + '</div>'
      )
    },
    renderCell({row, column}) {
      return (
          '<div style="width: 100px; white-space: normal; word-wrap: break-word;">' +
          '<span v-if="row[column.property] && row[column.property].split(\'|\')[0] != \'null\'">' +
          '{{ row[column.property].split("|")[0] }}' +
          '</span>' +
          '<span v-else>-</span>' +
          '</div>'
      )
    },

//下面附上完整的代码希望可以帮助你

<template>
  <div>
    <div v-show="zhuanZhi">
      <!-- 社会系统的页面展示的表格数据 -->
      <vxe-table border highlight-hover-row ref="multipleTablezb" height="100%" style="width: 101%; height: 648px"
                 :sort-config="{multiple: true, trigger: 'cell',chronological:true,
      sortMethod: customSortMethod}"       :selection-config="{ checkField: 'checked', trigger: 'cell', highlight: true }"
                 :checkbox-config="{ range: true }"
                 @checkbox-all="selectAllChangeEvent"
                 @checkbox-change="selectChangeEvent"
                 :show-overflow='true' :menu-config="tableMenu"
                 :show-header-overflow="true"
                 :loading="loading" :resizable="true" :data="tableData"
                 @menu-click="menuClick"
      >
        <vxe-column type="checkbox" title=""  :width="60"></vxe-column>
        <vxe-table-column title="序号" type="seq" width="60"></vxe-table-column>
        <vxe-table-column :edit-render="{ autofocus: '.vxe-input--inner' }" v-for="(table, $index) in tableHeaderData"
                          :key="Math.random()" :field="table.prop" :column-key="table.prop"
                          :width="tableHeaderData.length < 8 ? '150' : '150'"
                          sortable :title="table.label" :render-header="table">
          <template slot="header">
            <span>{{ table.label }}
              <i class="el-icon-info" @click="vxeClicksh(table)"> </i>
            </span>
          </template>
          <template #edit="{ row }">
            <vxe-input v-model="
              row[table.prop]
            " type="text"></vxe-input>
          </template>
        </vxe-table-column>
      </vxe-table>
      <el-col :span="24" class="pageposition">
        <el-pagination background prev-text="上一页" next-text="下一页" @current-change="handleCurrentChange"
                       :current-page="pageNo" layout=" prev, pager, next,sizes" :page-sizes="[50, 100, 150, 200]"
                       @size-change="handleSizeChange" :total="total" v-if="zhuanZhi">
        </el-pagination>
      </el-col>
    </div>
    <div v-if="!zhuanZhi">
      <!-- 第一种表格刚进去的时候设置的数据 -->
      <vxe-table border v-if="zhuanIndex == 1" highlight-hover-row ref="multipleTable" height="100%" :sort-config="{multiple: true, trigger: 'cell',chronological:true,
      sortMethod: customSortMethod}" :show-overflow='true'       :selection-config="{ checkField: 'checked', trigger: 'cell', highlight: true }"
                 :checkbox-config="{ range: true }"
                 @checkbox-all="selectAllChangeEvent"
                 @checkbox-change="selectChangeEvent"
                 :show-header-overflow="true" :menu-config="tableMenu"
                 style="width: 101%; height: 648px" :loading="loading" :resizable="true" :data="tableData"
                 @menu-click="menuClick"
      >
        <vxe-column type="checkbox" title=""  :width="60"></vxe-column>
        <vxe-table-column v-for="(table, $index) in tableHeaderData" :key="Math.random()" :field="table.prop"
                          :title="table.label" :column-key="table.prop" :width="table.label == '指标' ? '328' : '110'"
                          sortable
                          :edit-render="{ autofocus: '.vxe-input--inner' }">
          <template v-if="$index == 0" #default="{ row }">
            <span style="margin-right: 10px">{{
                row.firstColumn.split("|")[0]
              }}</span>
            <i v-if="row.firstCaliber || row.firstExp" class="el-icon-info" @click="vxeClick(row)"></i>
          </template>
          <template #edit="{ row }" v-else-if="$index !== 0">
            <vxe-input v-model="
              row[table.prop]
          " type="text"></vxe-input>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-table border
                 v-if="zhuanIndex == 2"
                 highlight-hover-row ref="multipleTable2"
                 height="100%"
                 :selection-config="{ checkField: 'checked', trigger: 'cell', highlight: true }"
                 :checkbox-config="{ range: true }"
                 @checkbox-all="selectAllChangeEvent"
                 @checkbox-change="selectChangeEvent"
                 :sort-config="{multiple: true, trigger: 'cell',chronological:true,
      sortMethod: customSortMethod}" :show-overflow='true' :menu-config="tableMenu"
                 :show-header-overflow="true" :scroll-y="{enabled: false}"
                 style="width: 101%; height: 648px" :loading="loading" :resizable="true" :data="tableData"
                 @menu-click="menuClick" trigger="cell"
      >
        <!-- <vxe-table-column title="序号" type="seq" width="60"></vxe-table-column> -->
        <vxe-column type="checkbox" title=""  :width="60"></vxe-column>
        <vxe-table-column
            v-for="(table, $index) in tableHeaderData2"
            :key="Math.random()"
            :field="table.prop"
            :title="table.desc ? table.desc : table.label"
            :column-key="table.prop"
            :width="table.label == '指标' ? '328' : '110'"
            :sortable="true"
            :ellipsis="true"
            :header-render="renderHeader"
            :cell-render="renderCell"
        >

        </vxe-table-column>
      </vxe-table>
      <vxe-table border v-if="zhuanIndex == 3" highlight-hover-row ref="multipleTable3" height="100%"
                 :sort-config="{multiple: true, trigger: 'cell',chronological:true,
      sortMethod: customSortMethod}" :show-overflow='true'        :selection-config="{ checkField: 'checked', trigger: 'cell', highlight: true }"
                 :checkbox-config="{ range: true }"
                 @checkbox-all="selectAllChangeEvent"
                 @checkbox-change="selectChangeEvent"
                 :show-header-overflow="true" :menu-config="tableMenu"
                 style="width: 100%; height: 600px" :loading="loading" :resizable="true" :data="tableData"
                 @menu-click="menuClick">
        <!--  -->
        <!-- <vxe-table-column title="序号" type="seq" width="60"></vxe-table-column> -->
        <vxe-column type="checkbox" title=""  :width="60"></vxe-column>
        <vxe-table-column v-for="(table, $index) in tableHeaderData3" :key="Math.random()" :field="table.prop"
                          :title="table.label" :column-key="table.prop" :width="table.label == '指标' ? '328' : '110'"
                          sortable>
          <template v-if="$index == 0" #default="{ row }">
            <span style="margin-right: 10px">{{ row.firstColumn }}</span><i v-if="row.firstCaliber || row.firstExp"
                                                                            class="el-icon-info"
                                                                            @click="vxeClick(row)"></i>
          </template>
          <template v-else-if="$index !== 0" #default="{ row, column }">
            <span v-if="
                row[column.property] &&
                row[column.property].split('|')[0] != 'null'
              " style="margin-right: 10px">{{ row[column.property].split("|")[0] }}</span>
            <span v-else>-</span>
          </template>
        </vxe-table-column>
      </vxe-table>
    </div>
    <el-dialog :visible.sync="dialogVisible" :modal="true" width="40%" element-loading-background="rgba(0, 0, 0, 0.3)"
               :modal-append-to-body="true" :append-to-body="true" :close-on-click-modal="false">
      <div>
        <div v-if="zbExp" style="font-weight: bold; font-size: 16px; margin-bottom: 12px">
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;指标解释
        </div>
        <div v-if="zbExp" style="line-height: 26px; margin-bottom: 18px">
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ zbExp }}
        </div>
        <div v-if="zbCaliber" style="font-weight: bold; font-size: 16px; margin-bottom: 12px">
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;统计口径
        </div>
        <div v-if="zbCaliber" style="line-height: 26px">
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ zbCaliber }}
        </div>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisiblesh" :modal="true" title="列名解释" width="40%"
               element-loading-background="rgba(0, 0, 0, 0.3)" :modal-append-to-body="true" :append-to-body="true"
               :close-on-click-modal="false">
      <div>
        <el-input type="textarea" v-model="mtdaDesc"></el-input>
        <div style="margin-top: 10px">
          <span slot="footer">
            <el-button @click="saveDesc">保存修改</el-button>
            <el-button type="primary" @click="dialogVisiblesh = false">还原数据</el-button>
          </span>
        </div>
      </div>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="editdialogVisible" width="30%">
      <el-button type="primary" size="mini" @click="screenshot">一键截图</el-button>
      <!-- 调整截图弹出框 -->
      <!--      <div v-if="screenshot">-->
      <!--      <DialogPageSnapshot  />-->
      <!--      </div>-->
      <!--      修改类型:-->
      <!--      <el-select v-model="editType" placeholder="修改类型">-->
      <!--        <el-option label="OCR电子化产生的错误" value="1"></el-option>-->
      <!--        <el-option label="数据本身错误" value="2"></el-option>-->
      <!--      </el-select>-->
      <!--      <span slot="footer" class="dialog-footer">-->
      <!--        <el-button @click="editNoSave">取 消</el-button>-->
      <!--        <el-button type="primary" @click="editclick">确 定</el-button>-->
      <!--      </span>-->
    </el-dialog>
  </div>
</template>
<script>
import {Message} from 'element-ui'
import pinyin from "js-pinyin";


export default {
  computed: {
    flag() {
      return {
        importquerytotable: this.importquerytotable,
        showFlag: this.showFlag
      }
    }
  },
  components: {

  },
  watch: {
    flag: {
      //监听变量的时候记录打点是有的时候更换了表格之后所以会变化
      handler: function (val, oldval) {
        // this.tableHeaderDataChange=true;
        this.initTable(val.importquerytotable);

        if (oldval.importquerytotable) {
          this.oldvalImportquerytotable = oldval.importquerytotable;
        } else {
          this.oldvalImportquerytotable = val.importquerytotable;
        }
        //记录时间

        this.browseTimefirst = this.browseTime * 1000
        if (this.browseTimesecond !== this.browseTimefirst) {
          this.controlrequestmethods(this.oldvalImportquerytotable, '1');
        }

      },
      deep: true
    },
  },
  props: {
    importquerytotable: {
      default: {},
    },
    showFlag: {
      default: true,
    },
    //传递参数
    selectLine: {
      default: [],
    },
    selectColumn: {
      default: [],
    },
  },
  destroyed() {
    if (!this.oldvalImportquerytotable.message) {
      this.oldvalImportquerytotable = this.importquerytotable
    }
    this.browseTimesecond = this.browseTime * 1000
    if (this.browseTimesecond !== this.browseTimefirst) {
      this.controlrequestmethods(this.oldvalImportquerytotable, '2');
    }
  },

  data() {
    return {

      showScreenshot: false,
      title: '',
      browseTimesecond: 0,
      browseTimefirst: 0,
      oldvalImportquerytotable: {},
      //定时器使用到的数据
      browseTime: 0,  // 浏览时长初始值为 0
      // tableHeaderDataChange:false,
      //修改单元格数据的时候调用的变量
      editCellparam: '',
      editCellI: '',
      editCellColumnField: '',
      editCellinitData: '',
      //选择修改的类型debugger
      editType: '',
      //添加弹框当用户修改了数据之后直接就打开
      editdialogVisible: false,
      //列的注释
      mtdaDesc: '',
      dialogVisiblesh: false,
      tableHeaderData2: [],
      tableHeaderData3: [],
      tableHeaderData: [],
      tableMenu: {
        body: {
          options: [
            [
              {code: 'sjkw', name: '数据勘误', visible: true},
              //问题描述
            ],
          ],
          disabled: false,
        },
      },
      tableData: [],
      //因为修改节点的时候,判断数据是否更新的方法不起作用,所以数据不会刷新,初始的数据带着PKcode
      tableDatacopyinit: [],
      ///展示的表格的数据
      tableDatacopy: [],
      zhuanIndex: '2',
      zhuanZhi: false, //是否转置*-
      loading: true,
      zbExp: '',
      zbCaliber: '',
      dialogVisible: false,
      zbSelect: '',
      normalHeader: [],
      pageNo: 1,
      pageSize: 50,
      total: 0,
    }
  },
  created() {
    this.initTable(this.importquerytotable);
  },
  mounted() {
    this.browseTime = 0;
    // 页面激活时开启定时器
    this.timer = setInterval(() => {
      // console.log('setInterval');
      this.browseTime++;
    }, 1000)
  },
  methods: {

    selectAllChangeEvent({ checked }) {
      let $table=null;
      if (this.zhuanIndex == 1) {
        $table= this.$refs.multipleTable
      } else if (this.zhuanIndex == 2) {
        $table= this.$refs.multipleTable2
      } else {
        $table= this.$refs.multipleTable3
      }
      if ($table) {
        const records = $table.getCheckboxRecords()
        //获取到的是当前勾选的数据,将他传递给父级

        console.log(checked ? '所有勾选事件' : '所有取消事件', records)
      }
    },
    selectChangeEvent({ checked }) {
      let $table=null;
      if (this.zhuanIndex == 1) {
        $table= this.$refs.multipleTable
      } else if (this.zhuanIndex == 2) {
        $table= this.$refs.multipleTable2
      } else {
        $table= this.$refs.multipleTable3
      }
      if ($table) {
        const records = $table.getCheckboxRecords()
        console.log(checked ? '勾选事件' : '取消事件', records)
      }
    },

    renderHeader({column}) {
      return (
          '<div style="width: 100px; word-wrap: break-word">' + column.getTitle() + '</div>'
      )
    },
    renderCell({row, column}) {
      return (
          '<div style="width: 100px; white-space: normal; word-wrap: break-word;">' +
          '<span v-if="row[column.property] && row[column.property].split(\'|\')[0] != \'null\'">' +
          '{{ row[column.property].split("|")[0] }}' +
          '</span>' +
          '<span v-else>-</span>' +
          '</div>'
      )
    },
    //触发一下父亲的截图工具
    screenshot() {
      this.$emit('screenshot');
      this.editdialogVisible = false;
    },

    //点击了指标之后发送的埋点数据
    dadianVisit(
        pkTreeCode,
        treeName,
        download,
        opttype,
        requestparam,
        pkZbCode,
        zbRenderName, useTime
    ) {
      this.$axios({
        url: this.logRecordUrl + '/log/dadianVisit',
        method: 'post',
        data: {
          useTime: useTime,
          pkTreeCode: pkTreeCode,
          treeName: treeName,
          username: sessionStorage.getItem('username'),
          officeName: sessionStorage.getItem('officeName'),
          download: download,
          userId: sessionStorage.getItem('userId'),
          officeId: sessionStorage.getItem('officeId'),
          opttype: opttype,
          requestparam: requestparam,
          pkZbCode: pkZbCode,
          zbRenderName: zbRenderName,
          requestTime: Date.now(),
          //1.指标分析,2.数据上图,3.数据下载,4.点击综合搜索的时候5收藏,6.sql查询,7.接口调用,8.图标的echarts
        },
      }).then((res) => {
      })
    },
//控制发送请求
    controlrequestmethods(importquerytotable) {
      // 页面关闭(路由跳转)时清除定时器
      clearInterval(this.timer)
      this.timer = null;
      //发送球球的时候传递的参数要跟之前的参数是一致的。
      // 为true就是表格
      if (importquerytotable.tableDataShow) {
        let leftMenuMessage = JSON.parse(importquerytotable.message)
        this.dadianVisit(
            leftMenuMessage.pkTreeCode,
            leftMenuMessage.treeName,
            false,
            9,
            JSON.stringify([
              {
                pkZbCode: leftMenuMessage.pkTreeCode,
                zbRenderName: leftMenuMessage.treeName,
              },
            ]),
            leftMenuMessage.pkTreeCode,
            leftMenuMessage.treeName,
            this.browseTime * 1000
        )
      } else {
        //为指标的时候
        this.dadianVisit(
            leftMenuMessage.pkTreeCode,
            leftMenuMessage.treeName,
            false,
            9,
            JSON.stringify([
              {
                pkZbCode: importquerytotable.zbselsct,
                zbRenderName: importquerytotable.zhibiaoName,
              },
            ]),
            importquerytotable.zbselsct,
            importquerytotable.zhibiaoName,
            this.browseTime * 1000
        )
      }
    },


    /**
     * 根据拼音将对象数组中的 name 属性按照升序或降序排列
     * @param {Array<object>} objList 待排序的对象数组
     * @param {boolean} isAsc 是否为升序排列,默认为 true
     * @returns {Array<object>} 排序后的对象数组
     */
    sortObjectsByPinyin(objList, isAsc = true, property) {
      // 将所有对象转换为拼音并组成元组
      const pinyinList = objList.map((obj) => ({
        obj,
        pinyin: pinyin(obj.property, {style: 'strip', heteronym: false}).join(' ')
      }));
      // 按照拼音排序
      const sortedList = pinyinList.sort((a, b) => (isAsc ? a.pinyin.localeCompare(b.pinyin) : b.pinyin.localeCompare(a.pinyin)));
      // 输出排序后的对象数组
      return sortedList.map((tuple) => tuple.obj);
    }
    ,
    containsChinese(str) {
      const chineseReg = /[\u4e00-\u9fa5]/g; // 中文正则表达式
      return chineseReg.test(str);
    },
    customSortMethod({data, sortList}) {
      let _self = this;
      const sortItem = sortList[sortList.length - 1]
      // 取出第一个排序的列
      //如果是因为数据发生改变之后触发的这个方法直接return [];
      const {property, order} = sortItem
      let list = []
      if (order === 'asc') {
        list = data.sort(function (a, b) {
          let at = JSON.parse(JSON.stringify(a));
          let bt = JSON.parse(JSON.stringify(b));
          if (_self.containsChinese(at[property])) {
            return at[property].localeCompare(bt[property], 'zh-Hans-CN', {sensitivity: 'accent'});
          } else {
            at[property] = (at[property] == null || at[property] == '-') ? '-9999' : at[property];
            bt[property] = (bt[property] == null || bt[property] == '-') ? '-9999' : bt[property];
            return at[property] - bt[property]; // 升序排列
          }
          // return b - a; // 降序排列
        });
      }
      if (order === 'desc') {
        list = data.sort(function (a, b) {
          let at = JSON.parse(JSON.stringify(a));
          let bt = JSON.parse(JSON.stringify(b));
          if (_self.containsChinese(at[property])) {
            return -at[property].localeCompare(bt[property], 'zh-Hans-CN', {sensitivity: 'accent'});
          } else {
            at[property] = (at[property] == null || at[property] == '-') ? '-9999' : at[property];
            bt[property] = (bt[property] == null || bt[property] == '-') ? '-9999' : bt[property];
            return bt[property] - at[property]; // 升序排列
          }

          // return b - a; // 降序排列
        });
      }
      return list
    },
    //当用户点击了取消之后
    editNoSave() {
      //说明当前的修改不起作用所以就取消
      //还原数据//关闭按钮
      // this.tableData[this.editCellI][this.editCellColumnField] = this.editCellinitData;
      this.editdialogVisible = false;
    },
    editclick() {
      //当用户点击了确定之后,关闭,将参数传递给方法
      this.editdialogVisible = false;
      // 如果不选择类型就不让确定关闭

      if (!this.editType) {
        Message.error('请选择修改类型');
      } else {
        if (this.tableDatacopyinit.length > 0) {
          //普通的参数存储
          // this.editCellparam
          this.$axios({
            url: this.dataQueryUrl + "/zb/updateDataIndicaterTableById",
            // service/search/score/detail/{fkComputeId}
            //2.15修改后可以修改中间变量的页面
            method: 'post',
            data: {
              pkDataCode: this.editCellparam,
              //类型
              optType: this.editType,
              showData: this.tableData[this.editCellI][this.editCellColumnField],
              //修改用户的id
              // usrId:s
              userId: sessionStorage.getItem('userId'),
            },
          }).then((res) => {
            Message.success('修改成功')
          })
        } else {
          //社会的
        }
      }
    },
    //编辑表格保存数据的方法为了让他实时更新需要确定他具体的位置
    editClosedEvent({row, column}) {
      //得拿出判断条件来
      // 判断不同的类型展示的树是不一样的 
      let tableDatacopy = []
      let $table
      let tableData = []
      tableData = this.tableData;
      tableDatacopy = JSON.parse(JSON.stringify(this.tableDatacopy))
      if (this.zhuanZhi) {
        //社会的
        $table = this.$refs.multipleTablezb
      } else if (!this.zhuanZhi) {
        switch (this.zhuanIndex) {
          case '1':
            //转置的第一种情况展示表
            $table = this.$refs.multipleTable
            tableData = this.tableData
            break
          case '2':
            //转置的第二种情况
            $table = this.$refs.multipleTable2

            break
          case '3':
            //展示的第三种情况
            $table = this.$refs.multipleTable3

            break;
        }
      }
      let field = column.property
      let cellValue = row[field]
      // 判断单元格值是否被修改
      // 从column中获取到id和field
      // column
      for (let i = 0; i < tableData.length; i++) {
        //确定修改的是第几行的数据
        if (row._X_ROW_KEY == tableData[i]._X_ROW_KEY) {
          //获取到数据之后判断数据是否发生变化,如果数据发生变化就弹出框来,让用户自己选择
          console.log(
              tableData[i][column.field],
              tableDatacopy[i][column.field]
          )
          if (tableData[i][column.field] == tableDatacopy[i][column.field]) {
            // Message.error('修改失败')
          } else {
            console.log(tableData[i][column.field], i, column.field)
            Message.success('修改成功')
            this.editdialogVisible = true;
            //如果用户选择了下拉就可以直接的给用户传递添加一个判断
            //列表初始的时候获取到的初始的数据,
            //只要是成功的修改就需要添加上变量,在弹框中处理数据
            this.editCellI = i;
            this.editCellColumnField = column.field;
            //需要还原的数据的值
            this.editCellinitData = tableDatacopy[i][column.field];
            if (this.tableDatacopyinit.length > 0) {
              //获取到pkcode,这个是用户需要的数据
              //需要存储的数据
              //向后台发送请求的参数
              if (this.editCellparam = this.tableDatacopyinit[i][column.field]) {
                this.editCellparam = this.tableDatacopyinit[i][column.field].split('|')[1];
              }
              // console.log(
              //   this.tableDatacopyinit[i][column.field].split('|')[1]
              // )
            } else {

              //社会的需要存的值
              console.log("社会的")
            }
          }
        }
      }
      // _X_ROW_KEY: 'row_190'
      // this.tableData
      // this.tableDatacopy
      // if ($table.isUpdateByRow(row, field)) {
      //   VXETable.modal.message({
      //     content: `局部保存成功! ${field}=${cellValue}`,
      //     status: 'success',
      //   })
      //   // 局部更新单元格为已保存状态
      //   $table.reloadRow(row, null, field)
      // }
    },
    //选择分页个数
    //分页的数据的个数
    handleSizeChange(val) {
      this.pageNo = 1
      this.pageSize = val

      this.searchByCondition2(this.typeCode + '', 'change')
    },
    //分页
    handleCurrentChange(val) {
      this.pageNo = val

      this.searchByCondition2(this.typeCode + '', 'change')
    },
    //点击保存的时候
    saveDesc() {
      //发送请求
      this.$axios({
        url: this.dataQueryUrl + '/metadata/updateMetaData',
        method: 'post',
        data: {
          id: this.editid,
          mtdaDesc: this.mtdaDesc,
        },
      }).then((res) => {
        this.dialogVisiblesh = false
      })
    },

    vxeClicksh(row) {
      this.editid = row.id
      //向后台发送请求重新获取一下最新的
      this.$axios({
        url:
            this.dataQueryUrl + '/metadata/getMetaDataDetail?id=' + this.editid,
        method: 'post',
      }).then((res) => {
        if (res.data.result.mtdaDesc) {
          this.mtdaDesc = res.data.result.mtdaDesc
        }
      })

      this.dialogVisiblesh = true
    },

    //写方法把数据灌进去
    //图标点击
    vxeClick(row) {
      this.zbExp = row.firstExp
      this.zbCaliber = row.firstCaliber
      this.dialogVisible = true
    },
    //父亲点击执行孩子的方法
    handleDownload() {
      if (this.zhuanIndex == 1) {
        this.$refs.multipleTable.exportData({
          data: this.$refs.multipleTable.getCheckboxRecords()
        })
      } else if (this.zhuanIndex == 2) {
        this.$refs.multipleTable2.exportData({
          data: this.$refs.multipleTable2.getCheckboxRecords()
        })

      } else {
        this.$refs.multipleTable3.exportData({
          data: this.$refs.multipleTable3.getCheckboxRecords()
        })

      }
    },
    //加载表格数据
    initTable(nv) {

      this.zhuanIndex = this.importquerytotable.zhuanIndex
      this.leftMenuMessage = JSON.parse(nv.message)
      this.positionText = nv.positionText
      this.typeCode = nv.typeCode
      this.treeName = this.leftMenuMessage.treeName
      this.searchInner = nv.searchText
      let scId = sessionStorage.getItem('scId')
      this.scFlag1 = false
      this.scFlag2 = false
      if (scId) {
        if (scId === 'scIdundefind') {
          this.scFlag = false
          this.scId = ''
        } else {
          this.scFlag = true
          this.scId = scId
        }
      } else {
        if (nv.scId) {
          this.scFlag = true
          this.scId = nv.scId
        } else {
          this.scFlag = false
          this.scId = ''
        }
      }
      this.searchContent = {}
      if (this.searchContent && this.searchContent.colums) {
        this.sxArr = this.searchContent.colums
      } else {
        this.sxArr = []
      }
      if (
          this.searchContent &&
          this.searchContent.orderParam &&
          this.searchContent.orderType
      ) {
        this.orderParam = this.searchContent.orderParam
        this.orderType = this.searchContent.orderType
      } else {
        this.orderParam = ''
        this.orderType = ''
      }
      //业务系统调用的方法要单独写
      if (this.importquerytotable.tableDataShow == true) {

        this.searchByCondition2(this.typeCode + '', 'zhuanzhi')
      } else {

        this.searchByCondition2(this.typeCode + '', 'change')
      }
      //传递的是表格的code,获取到指标的下拉框的数据
      // 默认收起数据介绍
      this.leftTrue = true;
    },
    //业务系统的方法
    // 排序
    changeSort(column) {

      let param = column
      if (param.order == 'asc') {
        param.order = 'ascending'
      }
      if (param.order == 'desc') {
        param.order = 'descending'
      }
      this.orderParam = column.property
      this.orderType = column.order
    },
    //右键单元格
    cellContextMenuEvent($event) {
    },
    //点击菜单
    menuClick(e) {
      this.title = '数据勘误'
      this.editdialogVisible = true;
      // let str = e.row[e.column.property]
      // this.dataCode = str.split('|')[1]
    },
    //列表接口
    searchByCondition2(code, type) {
      //社会系统的数据直接不用处理就可以
      if (this.importquerytotable.shehuiparams == true) {
        this.zhuanZhi = true
        let params = {
          tbName: this.importquerytotable.originTableName
              ? this.importquerytotable.originTableName
              : 'apd_sty_ind_el_yr',
          list: [{paramName: '', paramValue: ''}],
          colums: [],
          current: this.pageNo,
          size: this.pageSize,
          orderParam: '',
          orderType: '',
        }
        this.loading = true
        this.$axios({
          url: this.dataQueryUrl + 'detail/searchByTbName',
          method: 'post',
          data: params,
        }).then((res) => {
          this.loading = false
          if (res.data.code == 200) {
            this.tableHeaderData = []
            this.normalHeader = res.data.metaData
            this.tableData = res.data.result
            this.tableDatacopy = JSON.parse(JSON.stringify(res.data.result))
            this.total = res.data.totalCount
            if (this.normalHeader != null) {
              this.normalHeader.map((item, index) => {
                this.tableHeaderData.unshift({
                  label: item.mtdaName,
                  prop: item.mtdaCode,
                  mtdaDesc: item.mtdaDesc,
                  id: item.id,
                  showFlag: item.showFlag,
                })
              })

            }
            this.$refs.multipleTablezb.reloadData(this.tableData)

          } else {
            this.$message.error(res.data.message)
          }
        })
      } else {
        this.zhuanZhi = false
        //不是社会的是普通的数据和指标的
        if (type == 'change') {
          // 不管是指标还是数据都给他传递一个
          this.zbSelect = this.importquerytotable.zbselsct
        } else {
          this.zbSelect = this.importquerytotable.zbselsct
        }
        //如果社会的就跳转到这个放,社会的????判断他是社会的
        this.loading = true
        var params = {
          code: code,
          tableData: '',
          tableHead: '',
          select: '',
          spaceParam: '',
          timeParam: '',
          zbParam: '',
          time_names: [],
          space_names: [],
          pk_zb_codes: [],
          cata_logues: this.importquerytotable.filterText.value2,
        }
        var type = type
        if (this.zhuanIndex == '1') {
          params.tableData = 'zb';
          (params.tableHead = 'time'),
              (params.select = 'zb')
          params.pk_zb_codes = this.selectLine;
          params.time_names = this.selectColumn;
          // params.spaceParam = this.zbSelect
        } else if (this.zhuanIndex == '2') {
          params.tableData = 'time'
          ;(params.tableHead = 'space'),
              (params.select = 'time')
          params.time_names = this.selectLine;
          params.space_names = this.selectColumn;
        } else if (this.zhuanIndex == '3') {
          params.tableData = 'space'
          ;(params.tableHead = 'zb'),
              (params.select = 'space')
          params.space_names = this.selectLine;
          params.pk_zb_codes = this.selectColumn;
        }
        //传递参数的时候
        console.log("调用一次就输出一次")
        this.$axios({
          url: this.dataQueryUrl + '/detail/searchByCondition2',
          data: params,
          method: 'post',
        }).then((res) => {
          if (res.data.code == 200) {
            this.loading = false
            this.normalHeader = []
            //将这个获取到的select传递给父亲
            for (let i = 0; i < res.data.result.select.length; i++) {
              if (res.data.result.select[i].code == '20210122') {
                res.data.result.select.splice(i, 1)
              }
            }
//获取到的是行,每一行的开头数据
            this.$emit('getnewKeyList', res.data.result.select, res.data.result.tableHead);
            //将获取到的列数据传递给父级
            for (let i = 0; i < res.data.result.tableHead.length; i++) {
              if (res.data.result.tableHead[i].code == '20210122') {
                res.data.result.tableHead.splice(i, 1)
              }
              // else  if(res.data.result.tableHead[i].code=="202105"){
              //   res.data.result.tableHead[i].code="2015"
              // }
            }
            let tableData = []
            //处理一下,如果是需要隐藏的直接就隐藏了
            if (this.showFlag == false) {
              let tableHead = res.data.result.tableHead
              for (let i = 0; i < tableHead.length; i++) {
                if (tableHead[i].showFlag == 1) {
                  this.normalHeader.push(tableHead[i])
                }
              }
              for (let i = 0; i < res.data.result.tableData.length; i++) {
                if (res.data.result.tableData[i].showflag == 1) {
                  tableData.push(res.data.result.tableData[i])
                }
              }
            } else {
              tableData = res.data.result.tableData
              this.normalHeader = res.data.result.tableHead
            }
            this.tableDatacopyinit = JSON.parse(JSON.stringify(tableData))
            //初始的每一行的数据需要存下
            let a
            for (let i = 0; i < tableData.length; i++) {
              //遍历所有的属性,如果属性的含有竖线就处理一下
              //属性名
              //  Object.keys(tableData[i])

              for (let j = 0; j < Object.keys(tableData[i]).length; j++) {
                a = tableData[i][Object.keys(tableData[i])[j]]
                if (typeof a == 'string') {
                  if (a.indexOf('|') > -1) {
                    // console.log(key)

                    tableData[i][Object.keys(tableData[i])[j]] = a.split('|')[0]
                  }
                }
              }
              this.tableData = tableData;
            }
            this.tableHeaderData = []
            this.tableHeaderData2 = []
            this.tableHeaderData3 = []
            if (this.normalHeader != null) {
              if (this.zhuanIndex == 1) {
                this.normalHeader.map((item, index) => {
                  this.tableHeaderData.push({
                    label: item.cname,
                    prop: item.code,
                    showFlag: item.showFlag,
                  })
                })
                if (params.select == 'space') {
                  this.tableHeaderData.unshift(
                      {
                        label: '指标',
                        prop: 'firstColumn',
                      },
                      {
                        label: '单位',
                        prop: 'unitColumn', showFlag: 0,
                      }
                  )
                } else if (params.select == 'zb') {
                  this.tableHeaderData.unshift({
                    label: '年份',
                    prop: 'firstColumn', showFlag: 0,
                  })
                } else {
                  this.tableHeaderData.unshift({
                    label: '省份',
                    prop: 'firstColumn', showFlag: 0,
                  })
                }
              } else if (this.zhuanIndex == 2) {
                //输出初始处理完成的
                console.log('this.tableHeaderData2>>>>>>>', this.tableHeaderData2)
                //将要处理的数据遍历的方法

//开始计算每一行的数据放到每一个属性中
                //开始计算每一行的数据放到每一个属性中
                this.normalHeader.forEach(item => {
                  this.tableHeaderData2.push({
                    label: item.cname,
                    prop: item.code,
                    showFlag: item.showFlag,
                    desc: '',
                    //求和
                    sum: 0,
                    //求平均
                    average: 0,
                    //求最大值
                    max: Number.NEGATIVE_INFINITY,
                    //求最小值
                    min: Number.POSITIVE_INFINITY,
                    //求方差
                    variance: 0,
                    //求标准差
                    standardDeviation: 0,
                    //求中位数
                    median: 0
                  })
                });
                let total = 0;
                let sqrSum = 0;
                let validCount = 0;
                let values = [];
// 遍历数据计算每个属性的总和、平均值、最大值、最小值、方差、标准差和中位数
                tableData.forEach(rowData => {
                  this.tableHeaderData2.forEach(headerData => {
                    let prop = headerData.prop;
                    let value = rowData[prop] * 1;
                    if (!isNaN(value)) { // 判断是否为数字
                      headerData.sum += value;
                      headerData.max = Math.max(headerData.max, value);
                      headerData.min = Math.min(headerData.min, value);
                      total += value;
                      sqrSum += value * value;
                      values.push(value);
                      validCount++;
                    }
                  });
                });
// 计算平均值、方差、标准差和中位数
                this.tableHeaderData2.forEach(headerData => {
                  let prop = headerData.prop;
                  let count = validCount;
                  let sqrSum = values.reduce((prev, curr) => {
                    if (!isNaN(curr)) {
                      return prev + (curr - headerData.average) ** 2;
                    } else {
                      return prev;
                    }
                  }, 0);
                  let sortedValues = values.filter(value => !isNaN(value)).sort((a, b) => a - b);
                  let medianIndex = Math.floor(sortedValues.length / 2);
                  let median = sortedValues.length % 2 === 0 ? (sortedValues[medianIndex] + sortedValues[medianIndex - 1]) / 2 : sortedValues[medianIndex];
                  if (count > 1) {
                    headerData.average = (headerData.sum / validCount).toFixed(2);
                    headerData.variance = (sqrSum / (count - 1)).toFixed(2);
                    headerData.standardDeviation = Math.sqrt(headerData.variance).toFixed(2);
                  }
                  headerData.median = median.toFixed(2);
                });
                this.tableHeaderData2.forEach(headerData => {
                  let prop = headerData.prop;
                  let desc = `${headerData.label}:
sum= ${headerData.sum}\n
average= ${headerData.average}\n
max= ${headerData.max}\n
min= ${headerData.min}\n
variance= ${headerData.variance}\n
standardDeviation= ${headerData.standardDeviation}\n
median= ${headerData.median}`;


                  headerData.desc = desc;
                });

                if (params.select == 'space') {
                  this.tableHeaderData2.unshift(
                      {
                        label: '指标',
                        prop: 'firstColumn', showFlag: 0,
                      },
                      {
                        label: '单位',
                        prop: 'unitColumn', showFlag: 0,
                      }
                  )
                } else if (params.select == 'zb') {
                  this.tableHeaderData2.unshift({
                    label: '年份',
                    prop: 'firstColumn', showFlag: 0,
                  })
                } else {
                  this.tableHeaderData2.unshift({
                    label: '省份',
                    prop: 'firstColumn', showFlag: 0,
                  })
                }
              } else if (this.zhuanIndex == 3) {
                this.normalHeader.map((item, index) => {
                  this.tableHeaderData3.push({
                    label: item.cname,
                    prop: item.code,
                    showFlag: item.showFlag,
                  })
                })
                if (params.select == 'space') {
                  this.tableHeaderData3.unshift(
                      {
                        label: '指标',
                        prop: 'firstColumn', showFlag: 0,
                      },
                      {
                        label: '单位',
                        prop: 'unitColumn', showFlag: 0,
                      }
                  )
                } else if (params.select == 'zb') {
                  this.tableHeaderData3.unshift({
                    label: '年份',
                    prop: 'firstColumn', showFlag: 0,
                  })
                } else {
                  this.tableHeaderData3.unshift({
                    label: '省份',
                    prop: 'firstColumn', showFlag: 0,
                  })
                }
              }
            }

            //处理完展示的数据
            this.tableDatacopy = JSON.parse(JSON.stringify(tableData))
            //江浙央行的数据传递给父级
            this.$emit('getTableDataNow', this.tableDatacopy);
// console.log('this.tableDatacopy>>>>>>>>',this.tableDatacopy)
            //现将原始的存储下来,然后再处理渲染的数据,数据渲染上去的时候在从原始的数据中获取数据,
            if (this.zhuanIndex == 1) {
              this.$refs.multipleTable.reloadData(tableData)
            } else if (this.zhuanIndex == 2) {
              this.$refs.multipleTable2.reloadData(tableData)
            } else {
              this.$refs.multipleTable3.reloadData(tableData)
            }
          }
        })
      }
    },
  },
}
</script>
<style scoped lang="scss">
@import url(./style.scss);

.vxe-table--body td .cell {
  white-space: normal !important;
  word-break: break-all !important;
}


.pageposition {
  display: flex;
  white-space: nowrap;
  padding: 2px 5px;
  color: #303133;
  font-weight: 700;
  justify-content: center;
  z-index: 99;
}

::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
  background-color: #ffa800;
  color: #fff;
}

::v-deep.el-pagination {
  .more + .number {
    display: none;
  }
}
</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值