<!-- 救灾物资数量价值表 -->
<template>
  <basic-container>
    <el-form class="whole_form">
      <el-row :gutter="20">
        <el-col :span="6" v-if="userInfo.deptType === '1'">
          <el-form-item label="省份">
            <el-select v-model="searchList.provinceDeptIdList" clearable multiple @change="getSupplies">
              <el-option v-for="item in cityList" :key="item.deptId" :label="item.name" :value="item.deptId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="userInfo.deptType === '1'">
          <el-form-item label="储备仓库">
            <el-select
              v-model="searchList.deptIdList"
              clearable
              multiple
              :disabled="searchList.provinceDeptIdList.length === 0"
              :placeholder="searchList.provinceDeptIdList.length === 0 ? '请先选择省份' : '请选择储备仓库'"
            >
              <el-option
                v-for="item in warehouseList"
                :key="item.deptId"
                :label="item.abbreviationName"
                :value="item.deptId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="userInfo.deptType === '2'">
          <el-form-item label="储备仓库">
            <el-select v-model="searchList.deptIdList" clearable multiple placeholder="请选择储备仓库">
              <el-option
                v-for="item in warehouseList"
                :key="item.deptId"
                :label="item.abbreviationName"
                :value="item.deptId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="物资类别">
            <el-select v-model="searchList.dmUpcode1List" clearable multiple>
              <el-option v-for="item in suppliesList" :key="item.id" :label="item.name" :value="item.code" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="物资名称">
            <el-input v-model="searchList.dmUpname2" clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="btn_center">
        <el-button :icon="Search" type="primary" @click="getList">查询</el-button>
        <el-button :icon="RefreshRight" @click="clearSearch">清空</el-button>
      </el-row>
    </el-form>

    <el-table :data="tableData" stripe border :span-method="arraySpanMethod">
      <el-table-column type="index" label="序号" header-align="center" align="center" />
      <el-table-column prop="upidName" label="省份" header-align="center" align="center" />
      <el-table-column prop="username" label="储备仓库" header-align="center" align="center" width="120" />
      <template v-for="item in headerName" :key="item">
        <el-table-column :label="item.dmUpname" header-align="center" align="center">
          <template v-for="iten in item.children" :key="iten">
            <el-table-column :label="iten.dmUpname" header-align="center" align="center">
              <el-table-column :prop="iten.dmUpcode" :label="iten.units" header-align="center" align="center" />
            </el-table-column>
          </template>
        </el-table-column>
      </template>
      <el-table-column prop="tolNum" label="数量总计（件）" header-align="center" align="center" />
      <el-table-column prop="tolMoney" label="总价值（万元）" header-align="center" align="center" />
    </el-table>
  </basic-container>
</template>

<script setup lang="ts">
import { ref } from "vue";

import { handleTree } from "@/utils/util";
import { useGetters } from "@/hooks/storeHooks";
import {
  getDroughtResistantHeader,
  getDroughtResistantList,
  getCityList,
  getSysTreeDict
} from "@/api/dataStatistics/index";
import { Search, RefreshRight } from "@element-plus/icons-vue";

const headerName: any = ref([]);
const headerProps: any = ref([]);
const tableData: any = ref([]);
const searchList: any = ref({});
const mergeObj: any = ref({});
const cityList: any = ref([]);
const warehouseList: any = ref([]);
const suppliesList: any = ref([]);

const { userInfo } = useGetters(["userInfo"]);

if (userInfo.value.deptType === "1") {
  // 获取省份列表
  getCityList({ deptType: 2 }).then((res: any) => {
    if (res.code === 0) {
      cityList.value = res.data;
    }
  });
} else {
  // 获取储备仓库
  getCityList({ parentIdList: [userInfo.value.deptId] }).then((res: any) => {
    if (res.code === 0) {
      warehouseList.value = res.data;
    }
  });
}

// 根据省份列表获取储备仓库
const getSupplies = (value: string[]) => {
  getCityList({ parentIdList: value }).then((res: any) => {
    if (res.code === 0) {
      warehouseList.value = res.data;
    }
  });
};

// 获取物资类别
getSysTreeDict({ type: 1, difference: 2, parentCodeList: ["300"] }).then((res: any) => {
  if (res.code === 0) {
    suppliesList.value = res.data;
  }
});

// 获取表头数据
getDroughtResistantHeader({ matype1: ["300"] }).then((res: any) => {
  if (res.code === 0) {
    res.data
      .map((item: any) => {
        const parent = {
          dmUpcode: item.matypecode2,
          dmUpname: item.matypename2
        };
        const own = {
          dmUpcode: item.matypecode3,
          dmUpname: item.matypename3,
          units: item.matypename4
        };
        return [parent, own];
      })
      .forEach((item: any) => {
        headerName.value.push(...item);
      });
    headerName.value = handleTree(headerName.value, "dmUpcode");
    headerProps.value = res.data.map((item: any) => item.matypecode3);
    headerProps.value.unshift("upidName", "username");
  }
  getList();
});

// getSpanArr方法
const getSpanArr = (data: any) => {
  const mergeCol = ["upidName", "username"];
  mergeCol.forEach((key: any) => {
    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 (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
        }
      }
    });
  });
};

// 获取表格数据
const getList = () => {
  const data = {
    ...searchList.value,
    dmUpcode0List: ["300"]
  };
  getDroughtResistantList(data).then((res: any) => {
    if (res.code === 0) {
      tableData.value = res.data
        .map((item: any) => {
          const retVal: any = ref({
            ...item.map
          });
          retVal.value.upidName = item.upidName;
          retVal.value.username = item.username;
          retVal.value.tolMoney = item.tolMoney;
          retVal.value.tolNum = item.tolNum;

          return retVal.value;
        })
        .filter((item: any) => {
          headerProps.value.filter((ite: any) => {
            if (!item[ite]) {
              item[ite] = 0;
            }
          });
          return item;
        });
      getSpanArr(tableData.value);
    }
  });
};

const clearSearch = () => {
  searchList.value = {
    provinceDeptIdList: [],
    deptIdList: [],
    dmUpcode1List: [],
    dmUpname2: ""
  };
  getList();
};

const arraySpanMethod = ({ column, rowIndex, columnIndex }: any) => {
  if (rowIndex === 0) {
    if (columnIndex === 1) {
      return [1, 2];
    } else if (columnIndex === 2) {
      return [0, 0];
    }
  }
  const mergeCol = ["upidName", "username"];
  // 判断列的属性
  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];
    }
  }
};
</script>
