<!-- 出库信息审核 -->
<template>
  <basic-container>
    <el-form class="whole_form" :inline="true">
      <el-form-item label="调用时间" style="width:350px">
        <el-date-picker
          type="daterange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          v-model="searchList.outboundTime"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="调用省份">
        <el-select v-model="searchList.provinceSiteIdList" multiple filterable style="width:250px" clearable>
          <el-option v-for="item in province_ch" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="调出仓库">
        <el-select v-model="searchList.warehouseDeptId" multiple filterable style="width: 250px" clearable>
          <el-option v-for="item in dcckOptions" :key="item.deptId" :label="item.abbreviationName" :value="item.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="物资名称">
        <el-input v-model="searchList.dmUpname2" style="width:200px" clearable />
      </el-form-item>
      <el-form-item>
        <el-button :icon="Search" type="primary" @click="getList">查询</el-button>
        <el-button :icon="RefreshRight" @click="clearSearch">清空</el-button>
      </el-form-item>
    </el-form>
    <el-button
    v-if="hasBtn('tj:fx:export')"
        type="primary"
        :icon="Download"
        style="margin-bottom: 10px"
        @click="exportToExcel"
        >导出</el-button
      >
    <div id="printTest">
    <el-table :data="tableData" :span-method="arraySpanMethod" style="width: 100%" stripe border>
      <el-table-column type="index" label="序号" align="center" width="60">
        <template #default="scope">
          <span v-if="scope.$index == 0">
            合计
          </span>
          <span v-else>
            {{ scope.$index }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="outboundTime" label="调用时间" header-align="center" align="center" />
      <el-table-column prop="provinceLabel" label="调用省份" header-align="center" align="center" />
      <el-table-column prop="warehouseName" label="调出仓库" header-align="center" align="center" />
      <el-table-column prop="materials3" label="物资名称" header-align="center" align="center" />
      <el-table-column prop="materials4" label="单位" header-align="center" align="center" />
      <el-table-column prop="quantity" label="数量" header-align="center" align="center" />
      <el-table-column prop="inboundTime" label="入库时间" header-align="center" align="center" />
      <el-table-column prop="unitPrice" label="单价（元）" header-align="center" align="center" />
      <el-table-column prop="totalPrice" label="价值（万元）" header-align="center" align="center" />
      <el-table-column prop="warehouseTotalPrice" label="合计价值（万元）" header-align="center" align="center" />
    </el-table>
    </div>
  </basic-container>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { selectDistributeListByOutboundTime } from "@/api/dataStatistics/dywz";
import { getDeptTypeList } from "@/api/inAndOut/formationFilling/out";
import { Search, RefreshRight, Download } from "@element-plus/icons-vue";
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'
import { useDict } from "@/hooks/dict";
import hasBtn from "@/global/hasBtn";
const { province_ch } = useDict("province_ch");

const dcckOptions = ref([]);
const searchList = ref({
  dmUpname2: "",
  provinceSiteIdList: [],
  warehouseDeptId: [],
  outboundTime: []
});
const tableData = ref([])
const mergeObj: any = ref({});

// 获取列表
const getList = () => {
  const data = reactive({
    dmUpcode0List: [100,200],
    ...searchList.value
  });
  selectDistributeListByOutboundTime(data).then((res: any) => {
    if (res.code === 0) {
      tableData.value = res.data
      getSpanArr(tableData.value)
    }
  });
};
const exportToExcel = () => {  
  const wb = XLSX.utils.table_to_book(document.querySelector("#printTest"))
  const wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
  const blob = new Blob([wbout], { type: 'application/octet-stream' })
  saveAs(blob, `防讯抗旱调用批次统计表.xlsx`)
};

interface SpanMethodProps {
  column: any
  rowIndex: number
  columnIndex: number
}


const arraySpanMethod = ({
  column,
  rowIndex,
  columnIndex,
}: SpanMethodProps) => {
  if (rowIndex === 0) {
    if (columnIndex === 0) {
      return [1, 6]
    } else if (columnIndex < 6) {
      return [0, 0]
    }
  }
  const mergeCol = ["outboundTime", "provinceLabel", "warehouseName"];
  // 判断列的属性
  if (mergeCol.indexOf(column.property) !== -1) {
    // 判断其值是不是为0
    if (mergeObj.value[column.property][rowIndex]) {
      return [mergeObj.value[column.property][rowIndex], 1];
    } else {
      // 如果为0则为需要合并的行
      return [0, 0];
    }
  }
}
// getSpanArr方法
const getSpanArr = (data: any) => {
  const mergeCol = ["outboundTime", "provinceLabel", "warehouseName"];
  mergeCol.forEach((key: any, mIndex: number) => {
    let count = 0; // 用来记录需要合并行的起始位置
    mergeObj.value[key] = []; // 记录每一列的合并信息
    data.forEach((item: any, index: number) => {
      // index == 0表示数据为第一行，直接 push 一个 1
      if (index === 0) {
        mergeObj.value[key].push(1);
      } else {
        // 判断当前行是否与上一行其值相等 如果相等 在 count 记录的位置其值 +1 表示当前行需要合并 并push 一个 0 作为占位
        if(mIndex==0){
          if(item[key] === data[index - 1][key]){
            mergeObj.value[key][count] += 1;
            mergeObj.value[key].push(0);
          }else{
            // 如果当前行和上一行其值不相等
            count = index; // 记录当前位置
            mergeObj.value[key].push(1); // 重新push 一个 1
          }
        }else{
          let status = true
          for (let i = 0; i < mergeCol.length; i++) {
            let preKey = mergeCol[mIndex-i]//上一个key
            if(item[preKey] !== data[index - 1][preKey]){
              status = false
              break;
            }
          }
          if(status){
            mergeObj.value[key][count] += 1;
            mergeObj.value[key].push(0);
          }else{
            count = index; // 记录当前位置
            mergeObj.value[key].push(1); // 重新push 一个 1
          }
        }
      }
    });
  });
};
// 查询
const handleSearch = () => {
  getList();
};
// 重置
const clearSearch = () => {
  searchList.value = {
    dmUpname2: "",
    provinceSiteIdList: [],
    warehouseDeptId: [],
    outboundTime: []
  };
  getList();
};

getDeptTypeList().then((res: any) => {
  if (res.code === 0) {
    dcckOptions.value = res.data;
  }
});
getList();
</script>

<style lang="scss" scoped></style>
