<template>
  <div class="tenant">
    <div class="content">
      <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        :selectConfig="selectConfig"
        highlight-current-row
        :action-list="[
          {
            text: '导出Excel',
            action: () => deriveExcel(),
          },
        ]"
        @get-list="getList"
        ref="table"
      >
        <template #warehouseName="{ item }">
          <div>
            <!-- <span v-if="item.opType == 1">{{ item.toWarehouseName }}</span>
            <span v-else>{{ item.warehouseName }}</span> -->
            <span>{{ item.warehouseName }}</span>
          </div>
        </template>
      </byTable>
    </div>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from "element-plus";
import { computed, nextTick, ref, toRef } from "vue";
import byTable from "@/components/byTable/index";
import { getToken } from "@/utils/auth";
const actionUrl = import.meta.env.VITE_APP_BASE_API;

const { proxy } = getCurrentInstance();
const route = useRoute();

const warehouseList = ref([]);
const productUnit = ref([]);
const currencyType = ref([]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    keyword: "",
    year: "",
    month: "",
    warehouseId: "",
  },
});
const loading = ref(false);
const yearData = ref([]);

const monthData = ref([]);
for (let i = 1; i < 13; i++) {
  const obj = {
    label: i + " 月",
    value: i + " ",
  };
  monthData.value.push(obj);
}
const selectConfig = computed(() => {
  return [
    {
      label: "年份",
      prop: "year",
      isShowAll: false,
      data: yearData.value,
    },
    {
      label: "月份",
      prop: "month",
      isShowAll: false,
      data: monthData.value,
    },
    {
      label: "仓库名称",
      prop: "warehouseId",
      data: warehouseList.value,
    },
  ];
});
const config = computed(() => {
  return [
    {
      attrs: {
        label: "仓库名称",
        prop: "warehouseName",
      },
    },
    {
      attrs: {
        label: "物品编码",
        prop: "productCode",
      },
    },

    {
      attrs: {
        label: "物品名称",
        prop: "productName",
      },
    },
    {
      attrs: {
        label: "规格型号",
        prop: "productSpec",
      },
    },
    {
      attrs: {
        label: "单位",
        prop: "productUnit",
        width: 80,
      },
      render(unit) {
        return proxy.dictValueLabel(unit, productUnit.value);
      },
    },
    {
      attrs: {
        label: "期初数量",
        prop: "initialQuantity",
        width: 120,
      },
    },
    {
      attrs: {
        label: "入库数量",
        prop: "receiptQuantity",
        width: 120,
      },
    },
    {
      attrs: {
        label: "出库数量",
        prop: "outboundQuantity",
        width: 120,
      },
    },
    {
      attrs: {
        label: "结存数量",
        prop: "balanceQuantity",
        width: 120,
      },
    },
    {
      attrs: {
        label: "结存单价",
        prop: "balanceUnitPrice",
        width: 120,
      },
      render(money) {
        return proxy.moneyFormat(money, 2);
      },
    },
    {
      attrs: {
        label: "结存金额",
        prop: "balanceAmount",
        width: 120,
      },
      render(money) {
        return proxy.moneyFormat(money, 2);
      },
    },
  ];
});
const table = ref(null);
const searchItemSelct = (data, item) => {
  // 默认选中的方法
  table.value.searchItemSelct(data, item);
};

const getDict = () => {
  proxy.post("/warehouse/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    if (res.rows && res.rows.length > 0) {
      warehouseList.value = res.rows.map((item) => {
        return {
          label: item.name,
          value: item.id,
        };
      });
    }
  });
  loading.value = true;
  proxy.get("/monthlyInventoryReport/getYearList").then((res) => {
    yearData.value = res.data.map((x) => {
      return {
        label: x,
        value: x,
      };
    });
    let date = new Date();
    setTimeout(() => {
      searchItemSelct(
        { label: date.getFullYear(), value: date.getFullYear() },
        selectConfig.value[0]
      );
    }, 500);
    setTimeout(() => {
      searchItemSelct(
        { label: date.getMonth(), value: date.getMonth() },
        selectConfig.value[1]
      );
    }, 500);
  });

  proxy.getDictOne(["unit"]).then((res) => {
    productUnit.value = res["unit"].map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
  });
};

const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/monthlyInventoryReport/page", sourceList.value.pagination)
    .then((res) => {
      sourceList.value.data = res.rows;
      sourceList.value.pagination.total = res.total;
      setTimeout(() => {
        loading.value = false;
      }, 200);
    });
};
getDict();
// getList();
const deriveExcel = () => {
  ElMessage({
    message: "请稍后",
    type: "success",
  });
  let xhr = new XMLHttpRequest();
  //域名是华为云的
  xhr.open("POST", `${actionUrl}/monthlyInventoryReport/exportExcel`, true);
  xhr.responseType = "blob";
  xhr.setRequestHeader("Authorization", `Bearer ${getToken()}`);
  xhr.setRequestHeader("Content-Type", "application/json");
  xhr.send(JSON.stringify(sourceList.value.pagination));
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      let url = window.URL.createObjectURL(xhr.response);
      const a = document.createElement("a");
      a.href = url;
      a.download = "月度库存报表.xlsx"; // 下载后文件名
      a.style.display = "none";
      document.body.appendChild(a);
      a.click(); // 点击下载
      window.URL.revokeObjectURL(a.href);
      document.body.removeChild(a); // 下载完成移除元素
    }
  };
};
</script>

<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
</style>
