<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" filterable 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.provinceSiteIdList" filterable clearable multiple>
              <el-option v-for="item in provinceList" :key="item.id" :label="item.name" :value="item.code" />
            </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
              filterable
              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 filterable 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" placeholder="请输入物资名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6" class="btn_center">
          <el-button :icon="Search" type="primary" @click="getList">查询</el-button>
          <el-button :icon="RefreshRight" @click="clearSearch">清空</el-button>
          <!-- <el-button
            type="primary"
            :disable="!tableLoading"
            :icon="Download"
            @click="downloadExcel"
            >导出</el-button
          > -->
          <el-button type="primary" :icon="Download" v-if="hasBtn('tj:export')" @click="exportTemplate">导出</el-button>
        </el-col>
      </el-row>
    </el-form>

    
    <el-table
      :data="tableData"
      stripe
      border
      style="height: 80%"
      v-loading="tableLoading"
      :span-method="arraySpanMethod"
    >
      <el-table-column fixed type="index" label="序号" header-align="center" align="center" width="60">
        <template #default="scope">
          <span v-if="scope.$index !== 0">
            {{ scope.$index }}
          </span>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column v-if="userInfo.deptType === '1' || userInfo.deptType === '2'" fixed prop="upidName" label="垂管局" header-align="center" align="center" min-width="120" />
      <el-table-column v-if="userInfo.deptType === '1' || userInfo.deptType === '2'" fixed prop="province" label="省份" header-align="center" align="center" min-width="120" />
      <el-table-column fixed 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" min-width="120" header-align="center" align="center" />
            </el-table-column>
          </template>
        </el-table-column>
      </template>
      <el-table-column prop="tolNum" label="数量总计（件）" header-align="center" align="center" min-width="150" />
      <el-table-column prop="tolMoney" label="总价值（万元）" header-align="center" align="center" min-width="160" />
    </el-table>
  </basic-container>
</template>

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

import { deepClone, handleTree } from "@/utils/util";
import { useGetters } from "@/hooks/storeHooks";
import { exportExcel } from "@/utils/exprot";
import exportBlob from "@/global/exportBlob";
import hasBtn from "@/global/hasBtn";
import {
  getDroughtResistantHeader,
  getDroughtResistantList,
  getCityList,
  getSysTreeDict,
  exportJzwzsljzb,
  exportFxkhwzsljzb
} from "@/api/dataStatistics/index";
import { Search, RefreshRight, Download } from "@element-plus/icons-vue";

const headerName: any = ref([]);
const headerProps: any = ref([]);
const tableData: any = ref([]);
const searchList: any = ref({
  provinceDeptIdList: [],
  deptIdList: [],
  dmUpcode1List: [],
  dmUpname2: "",
  provinceSiteIdList: [],
});
const mergeObj: any = ref({});
const cityList: any = ref([]);
const warehouseList: any = ref([]);
const suppliesList: any = ref([]);
const provinceList: any = ref([]);
const tableLoading = ref(false);
const exportHeaderName = ref([]); // 导出用表头

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

console.log(111111111111)
console.log(permissions.value)

const props = defineProps({
  isAvailable: {
    type: String,
    default: ""
  },
  payload: {
    type: Array,
    default: () => []
  },
  fileName: {
    type: String,
    default: ""
  }
});
if (userInfo.value.deptType === "1") {
  // 获取垂管局列表
  getCityList({ deptType: 2 }).then((res: any) => {
    if (res.code === 0) {
      cityList.value = res.data;
    }
  });
} else {
  // 获取储备仓库
  let postData = {
    parentIdList: [userInfo.value.deptId],
    warehouseType: props.fileName.substr(0,2) == "救灾" ? 200 : 100
  }
  getCityList(postData).then((res: any) => {
    if (res.code === 0) {
      warehouseList.value = res.data;
    }
  });
}

// 根据省份列表获取储备仓库
const getSupplies = (value: string[]) => {
  let postData = {
    parentIdList: value,
    warehouseType: props.fileName.substr(0,2) == "救灾" ? 200 : 100
  }
  getCityList(postData).then((res: any) => {
    if (res.code === 0) {
      warehouseList.value = res.data;
    }
  });
};

// 获取物资类别
getSysTreeDict({ type: 1, difference: 2, parentCodeList: props.payload }).then((res: any) => {
  if (res.code === 0) {
    suppliesList.value = res.data;
  }
});
// 获取省份
getSysTreeDict({ type: 2, difference: 1}).then((res: any) => {
  if (res.code === 0) {
    provinceList.value = res.data;
  }
});

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

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

// getSpanArr方法
const getSpanArr = (data: any) => {
  const mergeCol = ["upidName", "province", "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
        }
      }
    });
  });
  tableLoading.value = false;
};

// 获取表格数据
const getList = () => {
  const data = {
    ...searchList.value,
    dmUpcode0List: props.payload,
    isAvailable: props.isAvailable
  };
  tableLoading.value = true;
  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.province = item.province;
          retVal.value.tolNum = item.tolNum;
          retVal.value.tolMoney = item.tolMoney;
          return retVal.value;
        })
        .filter((item: any) => {
          headerProps.value.filter((ite: any) => {
            if (!item[ite]) {
              item[ite] = 0;
            }
          });
          return item;
        });
      getSpanArr(tableData.value);
    }
  });
};

const arraySpanMethod = ({ column, rowIndex, columnIndex }: any) => {
  if (rowIndex === 0 && (userInfo.value.deptType === '1' || userInfo.value.deptType === '2')) {
    if (columnIndex === 1) {
      return [1, 3];
    } else if (columnIndex === 2) {
      return [0, 0];
    } else if (columnIndex === 3) {
      return [0, 0];
    }
  }
  const mergeCol = ["upidName", "province", "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];
    }
  }
};

//导出
const exportTemplate = async () => {  
  try {  
    const data = {
      ...searchList.value,
      dmUpcode0List: props.payload,
      isAvailable: props.isAvailable
    };
    if(props.fileName === "救灾物资数量价值表"){
      const response = await exportJzwzsljzb(data);
      exportBlob(response, "救灾物资数量价值表")
    }else if(props.fileName === "防汛抗旱物资数量价值表"){
      const response = await exportFxkhwzsljzb(data);
      exportBlob(response, "防汛抗旱物资数量价值表")
    }
  } catch (error) {  
    console.error('Error exporting Excel:', error);  
  }
}

const downloadExcel = () => {
  const exportProp = deepClone(headerProps.value);
  exportProp.push("tolNum", "tolMoney");
  const name: string[][] = [[], [], []];
  name[0].push(
    "垂管局",
    "省份",
    "储备仓库",
    ...exportHeaderName.value.map((item: any) => item.matypename2),
    "数量总计（件）",
    "总价值（万元）"
  );
  name[1].push(
    "垂管局",
    "省份",
    "储备仓库",
    ...exportHeaderName.value.map((item: any) => item.matypename3),
    "数量总计（件）",
    "总价值（万元）"
  );
  name[2].push(
    "垂管局",
    "省份",
    "储备仓库",
    ...exportHeaderName.value.map((item: any) => item.matypename4),
    "数量总计（件）",
    "总价值（万元）"
  );
  const data = tableData.value.map((obj: any) => {
    return exportProp.map((prop: string) => obj[prop]);
  });
  const exportPayload = {
    data: data,
    tableheader: name,
    fileName: props.fileName,
    merges: { header: [1, name[0].length], content: [0, 2] },
    fixedCol: 3
  };

  exportExcel(exportPayload);
};
</script>
