<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.gameDeptId" multiple filterable clearable @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
              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-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-col :span="6">
          <el-form-item label="储存状态">
            <el-select v-model="searchList.storageState" @change="handlerChange" clearable>
              <el-option v-for="item in Storage_state" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="已维护次数">
            <el-input v-model="searchList.maintenanceCount" 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" @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"
      stripe
      border
      style="height: 80%"
      :span-method="arraySpanMethod"
      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 v-if="scope.$index !== 0 && scope.$index !== 1">
            {{ scope.$index - 1 }}
          </span>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column
        v-if="userInfo.deptType === '1' || userInfo.deptType === '2'"
        fixed
        prop="gameName"
        label="垂管局"
        header-align="center"
        align="center"
      />
      <el-table-column
        v-if="userInfo.deptType === '1' || userInfo.deptType === '2'"
        fixed
        prop="province"
        label="省份"
        header-align="center"
        align="center"
      />
      <el-table-column fixed prop="warehouseName" label="储备仓库" header-align="center" align="center" />
      <el-table-column fixed prop="materials1" label="物资大类" header-align="center" align="center" />
      <el-table-column prop="materials2" label="物资类别" :class-name="Bgcolor" header-align="center" align="center" />
      <el-table-column prop="materials3" label="物资名称" :class-name="Bgcolor" header-align="center" align="center" />
      <el-table-column prop="materials4" label="物资单位" :class-name="Bgcolor" header-align="center" align="center" />
      <el-table-column prop="specs" label="规格" header-align="center" :class-name="Bgcolor" align="center" />
      <el-table-column prop="inboundTime" label="入库时间" :class-name="Bgcolor" header-align="center" align="center">
        <template #default="{ row }">
          {{ row.inboundTime ? row.inboundTime.slice(0, 7) : "" }}
        </template>
      </el-table-column>
      <el-table-column prop="years" label="建议年限" :class-name="Bgcolor" header-align="center" align="center" />
      <el-table-column prop="quantity" label="数量" :class-name="Bgcolor" header-align="center" align="center" />
      <el-table-column prop="unitPrice" label="单价(元)" :class-name="Bgcolor" header-align="center" align="center" />
      <el-table-column prop="totalPrice" label="总价(万元)" :class-name="Bgcolor" header-align="center" align="center">
        <template #default="{ row }">
          {{ row.totalPrice ?? row.warehouseTotalPrice }}
        </template>
      </el-table-column>
      <el-table-column prop="remarks" label="备注" :class-name="Bgcolor" header-align="center" align="center" />
      <el-table-column
        prop="maintenanceCount"
        label="已维护次数"
        :class-name="Bgcolor"
        header-align="center"
        align="center"
      >
        <template #default="{ row }">
          <p class="font-style" @click="openDetail(row, 'look')">{{ row.maintenanceCount }}</p>
        </template>
      </el-table-column>
    </el-table>
  </basic-container>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useGetters } from "@/hooks/storeHooks";
import { getDetailList, 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: [],
  dmUpcode1List: [],
  dmUpname2: "",
  provinceSiteIdList: [],
  storageState: "",
  maintenanceCount: null
});
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;
    }
  });
};
let Bgcolor = ref("");
const handlerColor = (type: string, State: string) => {
  Bgcolor.value = type;
  searchList.value.storageState = State;
  getList();
};

// 获取物资类别
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: [],
    dmUpcode1List: [],
    dmUpname2: "",
    provinceSiteIdList: [],
    storageState: ""
  };
  Bgcolor.value = "";
  getList();
};

// 获取表格数据
const getList = () => {
  const data = {
    dmUpcode0List: props.payload,
    ...searchList.value
  };
  tableLoading.value = true;
  getDetailList(data).then((res: any) => {
    if (res.code === 0) {
      tableData.value = res.data.filter((item: any) => {
        if (item.gameName === null && item.totalPrice === null) {
          item.unitPrice = "总价值";
          return item;
        } else if (item.totalPrice === null) {
          item.unitPrice = "合计";
          return item;
        } else {
          return item;
        }
      });
      getSpanArr(tableData.value);
    }
  });
};

const arraySpanMethod = ({ row, column, rowIndex, columnIndex }: any) => {
  if (userInfo.value.deptType === "3") {
    const firstHidden = [2, 3, 4, 5, 6, 7, 8];
    const secondHidden = [3, 4, 5, 6, 7, 8];
    if (rowIndex === 0) {
      if (columnIndex === 1) {
        return [1, 8];
      } else if (firstHidden.includes(columnIndex)) {
        return [0, 0];
      }
    } else if (row.unitPrice === "合计") {
      if (columnIndex === 2) {
        return [1, 7];
      } else if (secondHidden.includes(columnIndex)) {
        return [0, 0];
      }
    }
  } else {
    const firstHidden = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
    const secondHidden = [5, 6, 7, 8, 9, 10, 11];
    if (rowIndex === 0) {
      if (columnIndex === 1) {
        return [1, 11];
      } else if (firstHidden.includes(columnIndex)) {
        return [0, 0];
      }
    } else if (row.unitPrice === "合计") {
      if (columnIndex === 4) {
        return [1, 8];
      } else if (secondHidden.includes(columnIndex)) {
        return [0, 0];
      }
    }
  }

  const mergeCol = ["gameName", "province", "warehouseName", "materials1", "materials2"];
  // 判断列的属性
  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 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,
      isMaintenance: true
    };
    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);
  setQuery("/dataStatistics/DataStatisticsDetail", { id: row.maintenanceId, type: type });
};

const handlerChange = (value: any) => {
  Bgcolor.value = "color" + value;
  getList();
};

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 .color1 {
  background: rgba(201, 90, 79, 0.8) !important;
}

::v-deep .color2 {
  background: rgba(251, 248, 156, 0.8) !important;
}

::v-deep .color3 {
  background: rgba(215, 131, 124, 0.8) !important;
}

::v-deep .color4 {
  background: rgba(233, 157, 66, 0.8) !important;
}

::v-deep .color5 {
  background: rgba(247, 207, 172, 0.8) !important;
}

::v-deep .color6 {
  background: rgba(255, 227, 187, 0.8) !important;
}

.font-style {
  color: blue;
  cursor: pointer;
}
</style>
