<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.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
              multiple
              filterable
              clearable
              v-model="searchList.warehouseDeptId"
              :disabled="!searchList.gameDeptId"
              :placeholder="!searchList.gameDeptId ? '请先选择垂管局' : '请选择储备仓库'"
            >
              <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.warehouseDeptId" multiple clearable 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-input v-model="searchList.dmUpname2" 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" @click="exportTemplate" v-if="hasBtn('tj:export')">导出</el-button> -->
        </el-col>
        <!-- <el-col :span="6" class="btn_center">
          <el-button class="color1" @click="handlerColor('success', '1')">超期</el-button>
          <el-button class="color2" @click="handlerColor('danger', '4')">临期</el-button>
          <el-button class="color3" @click="handlerColor('warning', '2')">存储过半</el-button>
        </el-col> -->
      </el-row>
    </el-form>
    <el-table
      :data="tableData"
      :span-method="arraySpanMethod"
      stripe
      border
      style="height: 80%"
      v-loading="tableLoading"
      :row-style="cellStyle"
    >
      <!-- <el-table :data="tableData" stripe border> -->
      <el-table-column fixed type="index" label="序号" header-align="center" align="center" width="60">
        <template #default="scope">
          <span>
            {{ scope.$index + 1 }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="userInfo.deptType === '1' || userInfo.deptType === '2'"
        fixed
        prop="provinceName"
        label="省份"
        header-align="center"
        align="center"
      />
      <el-table-column fixed prop="warehouse" label="储备仓库" header-align="center" align="center">
        <template #default="{ row }">
          <p class="font-style;" style="cursor: pointer" @click="openDetail(row, 'look')">
            {{ row.warehouse }}
          </p>
        </template>
      </el-table-column>
      <el-table-column prop="province" label="储存年限过半" class-name="Bgcolor1" header-align="center" align="center">
        <el-table-column
          prop="quantitygb"
          label="数量"
          class-name="Bgcolor1"
          header-align="center"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="totalPricegb"
          label="价值"
          class-name="Bgcolor1"
          header-align="center"
          align="center"
        ></el-table-column>
      </el-table-column>
      <el-table-column
        prop="province"
        label="22年底到达年限"
        class-name="Bgcolor2"
        header-align="center"
        align="center"
      >
        <el-table-column
          prop="quantity22"
          label="数量"
          class-name="Bgcolor2"
          header-align="center"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="totalPrice22"
          label="价值"
          class-name="Bgcolor2"
          header-align="center"
          align="center"
        ></el-table-column>
      </el-table-column>
      <el-table-column
        prop="quantity23"
        label="23年底到达年限"
        class-name="Bgcolor2"
        header-align="center"
        align="center"
      >
        <el-table-column
          prop="quantity23"
          label="数量"
          class-name="Bgcolor2"
          header-align="center"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="totalPrice23"
          label="价值"
          class-name="Bgcolor2"
          header-align="center"
          align="center"
        ></el-table-column>
      </el-table-column>
      <el-table-column
        prop="totalPrice24"
        label="24年底到达年限"
        class-name="Bgcolor3"
        header-align="center"
        align="center"
      >
        <el-table-column
          prop="quantity24"
          label="数量"
          class-name="Bgcolor3"
          header-align="center"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="totalPrice24"
          label="价值"
          class-name="Bgcolor3"
          header-align="center"
          align="center"
        ></el-table-column>
      </el-table-column>
      <el-table-column
        prop="province"
        label="25年底到达年限"
        class-name="Bgcolor3"
        header-align="center"
        align="center"
      >
        <el-table-column
          prop="quantity25"
          label="数量"
          class-name="Bgcolor3"
          header-align="center"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="totalPrice25"
          label="价值"
          class-name="Bgcolor3"
          header-align="center"
          align="center"
        ></el-table-column>
      </el-table-column>
      <el-table-column
        prop="province"
        label="26年底到达年限"
        class-name="Bgcolor3"
        header-align="center"
        align="center"
      >
        <el-table-column
          prop="quantity26"
          label="数量"
          class-name="Bgcolor3"
          header-align="center"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="totalPrice26"
          label="价值"
          class-name="Bgcolor3"
          header-align="center"
          align="center"
        ></el-table-column>
      </el-table-column>
    </el-table>
  </basic-container>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useGetters } from "@/hooks/storeHooks";
import { getDetaWarninglList, getCityList, getSysTreeDict, exportjzwzmxtjb } from "@/api/dataStatistics/index";
import { Search, RefreshRight, Download } from "@element-plus/icons-vue";
import { exportExcel } from "@/utils/exprot";
import { da } from "element-plus/es/locale";
import { deepClone, handleTree } from "@/utils/util";
import exportBlob from "@/global/exportBlob";
import hasBtn from "@/global/hasBtn";
import { setQuery } from "@/hooks/detailQuery/index";

import { useDict } from "@/hooks/dict";

const { Storage_state } = useDict("Storage_state");

const tableData: any = ref([]);
const tableLoading = ref(false);
const searchList: any = ref({
  gameDeptId: [],
  warehouseDeptId: [],
  provinceSiteIdList: []
});
const mergeObj: any = ref({});
const cityList: any = ref([]);
const warehouseList: any = ref([]);
const suppliesList: any = ref([]);
const provinceList: any = ref([]);

const { userInfo } = useGetters(["userInfo"]);
const props = defineProps({
  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;
      // searchList.value.gameDeptId = [cityList.value[0].deptId];
      getSupplies(searchList.value.gameDeptId);
      getList();
    }
  });
} 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;
      searchList.value.warehouseDeptId =
        warehouseList.value && warehouseList.value.length > 0 ? [warehouseList.value[0].deptId] : [];
      getList();
    }
  });
}

// 根据省份列表获取储备仓库
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;
  }
});

const clearSearch = () => {
  searchList.value = {
    gameDeptId: [],
    warehouseDeptId: [],
    provinceSiteIdList: []
  };
  getList();
};

// 获取表格数据
const getList = () => {
  const data = {
    dmUpcode0List: props.payload,
    ...searchList.value,
    isMaintenance: true
  };
  tableLoading.value = true;
  getDetaWarninglList(data).then((res: any) => {
    if (res.code === 0) {
      tableData.value = res.data;
      getSpanArr(tableData.value);
    }
  });
};

const arraySpanMethod = ({ row, column, rowIndex, columnIndex }: any) => {
  if (columnIndex === 1) {
    const currentValue = row[column.property];
    const preRow = tableData.value[rowIndex - 1];
    const preValue = preRow ? preRow[column.property] : null;
    if (currentValue === preValue) {
      return { rowspan: 0, colspan: 0 };
    } else {
      let rowspan = 1;
      for (let i = rowIndex + 1; i < tableData.value.length; i++) {
        const nextRow = tableData.value[i];
        const nextValue = nextRow[column.property];
        if (nextValue === currentValue) {
          rowspan++;
        } else {
          break;
        }
      }
      return { rowspan, colspan: 1 };
    }
  }
};
const shunxu = [
  "gameName",
  "province",
  "warehouseName",
  "materials1",
  "materials2",
  "materials3",
  "materials4",
  "specs",
  "quantity",
  "inboundTime",
  "years",
  "unitPrice",
  "totalPrice",
  "remarks"
];
const headerName = [
  "垂管局",
  "省份",
  "储备仓库",
  "物资大类",
  "物资类别",
  "物资名称",
  "物资单位",
  "规格",
  "数量",
  "入库时间",
  "建议年限",
  "单价(元)",
  "总价(万元)",
  "备注"
];
// const downloadExcel = () => {
//   let data: any = []
//   tableData.value.forEach((item, index) => {
//     let temp: any = [];
//     shunxu.forEach((item2, index2) => {
//       if (item[item2] == null){
//         temp.push('');
//       }else{
//         temp.push(item[item2]);
//       }

//     })
//     data.push(temp);
//   })
//   const exportPayload = {
//     data: data,
//     tableheader: [headerName],
//     fileName: 'kk',
//     merges: { header: [1, 4], content: [0, 4] },
//     fixedCol:1
//   };
//   console.log(exportPayload);
//   exportExcel(exportPayload);

// };
const downloadExcel = () => {
  console.log(tableData.value);
  tableData.value.forEach((item) => {
    if (item.unitPrice == "合计") {
      item.totalPrice = item.warehouseTotalPrice;
    }
  });
  tableData.value[0].totalPrice = tableData.value[0].warehouseTotalPrice;
  tableData.value[1].totalPrice = tableData.value[1].warehouseTotalPrice;
  let data: any = [];
  tableData.value.forEach((item, index) => {
    let temp: any = [];
    shunxu.forEach((item2, index2) => {
      if (item[item2] == null || undefined) {
        temp.push("");
      } else {
        temp.push(item[item2]);
      }
    });
    data.push(temp);
  });

  const exportPayload = {
    data: data,
    tableheader: [headerName],
    fileName: props.fileName || "*",
    merges: { header: [1, 2], content: [0, 3] },
    fixedCol: 1
  };
  exportExcel(exportPayload);
};

// getSpanArr方法
const getSpanArr = (data: any) => {
  const mergeCol = ["gameName", "province", "warehouseName", "materials1", "materials2"];
  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 exportTemplate = async () => {
  try {
    const data = {
      dmUpcode0List: props.payload,
      ...searchList.value
    };
    const response = await exportjzwzmxtjb(data);
    exportBlob(response, props.fileName);
  } catch (error) {
    console.error("Error exporting Excel:", error);
  }
};
const openDetail = (row: any, type: any) => {
  console.log(row.deptId);
  setQuery("/dataStatistics/WarningDetail", { deptId: row.deptId, type: type, dmUpcode0List: props.payload });
};

const cellStyle = () => {
  // return "background-color: yellow !important;";
};
</script>
<style lang="scss" scoped>
::v-deep .success {
  background: #fc7e6d !important;
}

::v-deep .danger {
  background: #f7bb48 !important;
}

::v-deep .warning {
  background: #f3f44e !important;
}

::v-deep .Bgcolor1 {
  background: rgba(242, 233, 11, 0.5) !important;
}

::v-deep .Bgcolor2 {
  background: rgba(242, 9, 9, 0.5) !important;
}

::v-deep .Bgcolor3 {
  background: rgba(244, 129, 24, 0.5) !important;
}
</style>
