<template>
  <div class="page">
    <topBar
      v-if="topList.length > 0"
      :topList="topList"
      :moren="moren"
    ></topBar>
    <div class="thetopbox">
      <el-form label-width="100px">
        <el-row>
          <el-col :span="4">
            <el-form-item label="SKU编码">
              <el-input clearable v-model="select.skuCode"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item :label="'产品名称'">
              <el-input clearable v-model="select.productName"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item :label="'订单类型'">
              <el-select v-model="select.orderType">
                <el-option
                  v-for="item in orderList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="统计日期">
              <el-date-picker
                v-model="creationTime"
                @change="changeTime"
                value-format="yyyy-MM-dd"
                type="daterange"
                :range-separator="'至'"
                :start-placeholder="'开始日期'"
                :end-placeholder="'结束日期'"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <div class="searchbox">
              <el-button class="my_search" @click="getSearch">
                {{ '搜索' }}</el-button
              >
              <el-button class="my_reset" @click="reChongzhi">
                {{ '重置' }}</el-button
              >
            </div>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="main">
      <div class="maintop">
        <div class="mainbtn">
          <el-button
            size="small"
            class="thebtn1"
            v-hasButtons="['ProductSalesRankingExport']"
            @click="handleExport"
          >
            {{ '导出' }}</el-button
          >
        </div>
      </div>
      <div class="maintable">
        <el-table
          :data="tableData"
          v-loading="loading"
          height="700px"
          style="width: 100%"
          :header-cell-style="{ background: '#EEEEEE' }"
          @selection-change="handleSelectionChange"
          :span-method="objectSpanMethod"
        >
          <!-- <el-table-column prop="colsele" type="selection" width="55">
          </el-table-column> -->

          <el-table-column
            align="center"
            prop="skuCode"
            label="SKU编码"
            min-width="120px"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="productName"
            :label="'产品名称'"
          >
          </el-table-column>

          <el-table-column
            align="center"
            prop="unitStr"
            :label="'产品单位'"
            min-width="120px"
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="specsName"
            :label="'产品规格'"
          >
          </el-table-column>
          <el-table-column
            min-width="180px"
            :label="'商品编码'"
            align="center"
            prop="waresCode"
          >
          </el-table-column>
          <el-table-column
            min-width="180px"
            :label="'商品名称'"
            align="center"
            prop="waresName"
          >
          </el-table-column>
          <el-table-column
            min-width="180px"
            label="商品规格（产品规格*数量）"
            align="center"
            prop="waresSpecs"
          >
          </el-table-column>

          <el-table-column
            min-width="120px"
            :label="'产品数量'"
            align="center"
            prop="productQuantity"
          >
          </el-table-column>
          <el-table-column
            min-width="120px"
            :label="'商品数量'"
            align="center"
            prop="waresQuantity"
          >
          </el-table-column>
        </el-table>
      </div>
    </div>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getSearch"
    />
  </div>
</template>
    
        <script>
import topBar from "@/components/topBar";
import * as api from "@/api/statistics";
import { isLocals, isLocalSymbol } from "@/utils/numberToCurrency";
export default {
  name: "ProductSalesRanking",
  components: {
    topBar,
  },
  data() {
    return {
      moren: "productSalesRanking",
      topList: [
        {
          name: "产品销量排行",
          path: "productSalesRanking",
        },
      ],
      tableData: [],
      loading: false,
      queryParams: {
        pageNum: 1,
        pageSize: 50,
      },
      select: {},
      creationTime: [],
      total: 0,
      multipleSelection: [],
      tableData: [],
      orderList: [],
      // 需要合并项的列
      needMergeArr: [
        {
          colName: "skuCode",
          mergeCheckNames: ["groupByInfo", "skuCode"],
        },
        {
          colName: "productName",
          mergeCheckNames: ["groupByInfo", "productName"],
        },
        {
          colName: "unitStr",
          mergeCheckNames: ["groupByInfo", "unitStr"],
        },
        {
          colName: "specsName",
          mergeCheckNames: ["groupByInfo", "specsName"],
        },
      ],
      rowMergeArrs: {}, // 包含需要一个或多个合并项信息的对象
    };
  },
  created() {
    this.getSearch();
    this.getData();
  },
  methods: {
    getData() {
      api.getOrderType().then((res) => {
        this.orderList = res.data;
      });
    },
    isLocalSymbol,
    isLocals,
    changeTime(val) {
      this.select.startTime = val ? val[0] : "";
      this.select.endTime = val ? val[1] : "";
    },
    //导出
    handleExport() {
        this.$confirm('是否确认导出所有数据项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: "warning",
        }).then((_) => {
          this.download(
            "report/manager/product-sales/product-sales-stat-export",
            Object.assign({}, this.queryParams, this.select),
            `产品销量排行${new Date().getTime()}.xlsx`
          );
        });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    reChongzhi() {
      this.select = {};
      this.creationTime = [];
      this.getSearch();
    },
    getSearch() {
      this.loading = true;
      api
        .getProductSalesStat(Object.assign({}, this.queryParams, this.select))
        .then((res) => {
          this.tableData = res.rows;
          this.rowMergeArrs = this.rowMergeHandle(
            this.needMergeArr,
            this.tableData
          );
          this.total = res.total;
          this.loading = false;
        });
    },
    //解决多列行列合并，根据某一列 合并其他列
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      let needMerge = this.needMergeArr.some((item) => {
        return item.colName === column.property;
      });
      if (needMerge === true) {
        return this.mergeAction(column.property, rowIndex, column);
      }
    },
    mergeAction(val, rowIndex, colData) {
      let _row = this.rowMergeArrs[val].rowArr[rowIndex];
      let _col = _row > 0 ? 1 : 0;
      return [_row, _col];
    },
    rowMergeHandle(arr, data) {
      if (!Array.isArray(arr) && !arr.length) return false;
      if (!Array.isArray(data) && !data.length) return false;
      let needMerge = {};

      arr.forEach((mergeItem) => {
        // 创建合并管理对象
        needMerge[mergeItem.colName] = {
          rowArr: [],
          rowMergeNum: 0,
        };
        let currentMergeItemData = needMerge[mergeItem.colName];

        // 进行合并管理对象数据的遍历整理
        data.forEach((item, index) => {
          if (index === 0) {
            currentMergeItemData.rowArr.push(1);
            currentMergeItemData.rowMergeNum = 0;
          } else {
            let currentRowData = data[index];
            let preRowData = data[index - 1];

            if (
              this.colMergeCheck(
                currentRowData,
                preRowData,
                mergeItem.mergeCheckNames
              )
            ) {
              currentMergeItemData.rowArr[
                currentMergeItemData.rowMergeNum
              ] += 1;
              currentMergeItemData.rowArr.push(0);
            } else {
              currentMergeItemData.rowArr.push(1);
              currentMergeItemData.rowMergeNum = index;
            }
          }
        });
      });
      return needMerge;
    },
    colMergeCheck(currentRowData, preRowData, mergeCheckNames) {
      if (!Array.isArray(mergeCheckNames) && !mergeCheckNames.length)
        return false;
      let result = true;
      for (let index = 0; index < mergeCheckNames.length; index++) {
        const mergeCheckName = mergeCheckNames[index];
        if (currentRowData[mergeCheckName] !== preRowData[mergeCheckName]) {
          result = false;
          break;
        }
      }
      return result;
    },
  },
};
</script>
    
    <style lang="scss" scoped>
::v-deep .inlineTable thead {
  display: none !important;
}
::v-deep .el-image-viewer__close {
  right: 500px;
}
::v-deep .dizhi .el-cascader {
  width: 100%;
}
::v-deep .el-range-editor.el-input__inner {
  width: 100%;
}
::v-deep .el-table thead {
  color: #000000;
}
::v-deep .el-table .warning-row {
  background: #f9f9f9;
}
.page {
  padding: 10px 20px;
  background: #f9f9f9;
  font-size: 14px;
  .thetopbox {
    padding: 15px 20px 15px 0;
    background: #ffffff;
    border-radius: 8px;
    .searchbox {
      display: flex;
      align-items: center;
      margin-left: 40px;
    }
    .searchtitle {
      margin-right: 10px;
    }
    .searchbtn {
      background: #08143f;
      color: #ffffff;
    }
  }
  .main {
    //margin-top: 20px;
    background: #f9f9f9;
    //border-radius: 8px;
    //box-shadow: 0px 2px 20px 0px rgba(238, 238, 238, 0.5);

    .maintop {
      display: flex;
      // padding: 10px 0;
      justify-content: space-between;
      align-items: center;
      .mainbtn {
        .thebtn1 {
          color: #ffffff;
          background: #ffad41;
          width: 68px;
          height: 32px;
        }
        .thebtn2 {
          color: #ffffff;
          background: #009b58;
          width: 68px;
          height: 32px;
        }
        .thebtn3 {
          color: #ffffff;
          background: #c8161d;
          width: 68px;
          height: 32px;
        }
      }
    }
  }
}
</style>
    