<template>
  <div>
    <div style="margin-bottom: 10px">
      <el-card class="top-card">
        <el-radio-group v-model="sourceList.pagination.departmentId" v-for="(item, index) in departmentList" :key="index" @change="changeDepartment">
          <el-radio-button :label="item.id" style="margin: 0 10px 10px 0">{{ showName(item) }}</el-radio-button>
        </el-radio-group>
      </el-card>
    </div>
    <el-row :gutter="10">
      <el-col :span="4">
        <el-card style="height: calc(100vh - 197px); overflow-y: auto; overflow-x: hidden">
          <el-tree
            ref="treeCategory"
            :data="warehouseList"
            :props="{ children: 'children', label: 'name' }"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
            :render-content="renderContent"
            @node-click="handleNodeClick" />
        </el-card>
      </el-col>
      <el-col :span="20">
        <el-card style="overflow-y: auto; overflow-x: hidden; height: calc(100vh - 197px)">
          <byTable
            :source="sourceList.data"
            :pagination="sourceList.pagination"
            :config="config"
            :loading="loading"
            :searchConfig="searchConfig"
            highlight-current-row
            :action-list="[
              {
                text: '导出Excel',
                action: () => deriveExcel(),
              },
            ]"
            @get-list="getList"
            @clickReset="clickReset">
            <template #total="{ item }">
              <div>{{ getTotal(item) }}</div>
            </template>
            <template #quantity="{ item }">
              <div>{{ item.quantity + item.lockQuantity }}</div>
            </template>
          </byTable>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import byTable from "/src/components/byTable/index";
import { ElMessageBox } from "element-plus";

const { proxy } = getCurrentInstance();
const departmentList = ref([]);
const warehouseList = ref([
  {
    id: "",
    name: "所有仓库",
    children: [],
  },
]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    bomClassifyId: "",
    bomSpecName: "",
    bomSpecCode: "",
    bomSpecies: "",
    bomChromatophore: "",
    bomEmbossingProcess: "",
    bomFrontGrain: "",
    bomReverseGrain: "",
    bomSpecColour: "",
    bomSpecLength: "",
    bomSpecWidth: "",
    departmentId: "0",
    warehouseId: "",
  },
});
const loading = ref(false);
const searchConfig = computed(() => {
  return [
    {
      type: "input",
      prop: "bomSpecName",
      label: "品名",
    },
    {
      type: "input",
      prop: "bomSpecCode",
      label: "品号",
    },
    {
      type: "select",
      prop: "bomSpecies",
      dictKey: "bom_species",
      label: "种类",
    },
    {
      type: "select",
      prop: "bomChromatophore",
      dictKey: "bom_chromatophore",
      label: "色层",
    },
    {
      type: "select",
      prop: "bomEmbossingProcess",
      dictKey: "bom_embossingProcess",
      label: "压纹工艺",
    },
    {
      type: "select",
      prop: "bomFrontGrain",
      dictKey: "bom_frontGrain",
      label: "正面纹路",
    },
    {
      type: "select",
      prop: "bomReverseGrain",
      dictKey: "bom_reverseGrain",
      label: "背面纹路",
    },
    {
      type: "input",
      prop: "bomSpecColour",
      label: "颜色",
    },
    {
      type: "input",
      prop: "bomSpecLength",
      label: "长（cm）",
    },
    {
      type: "input",
      prop: "bomSpecWidth",
      label: "宽（cm）",
    },
  ];
});
const config = computed(() => {
  return [
    {
      attrs: {
        label: "仓库",
        prop: "warehouseName",
        width: 140,
      },
    },
    {
      attrs: {
        label: "品号",
        prop: "bomSpecCode",
        width: 140,
      },
    },
    {
      attrs: {
        label: "品号",
        prop: "bomSpecName",
        "min-width": 500,
      },
    },
    {
      attrs: {
        label: "结存单价",
        prop: "balanceUnitPrice",
        width: 110,
        align: "right",
      },
    },
    {
      attrs: {
        label: "结存总价",
        slot: "total",
        width: 140,
        align: "right",
      },
    },
    {
      attrs: {
        label: "锁定库存",
        prop: "lockQuantity",
        width: 110,
      },
    },
    {
      attrs: {
        label: "可用库存",
        prop: "quantity",
        width: 110,
      },
    },
    {
      attrs: {
        label: "库存",
        slot: "quantity",
        width: 110,
      },
    },
  ];
});
const getDemandData = () => {
  proxy.post("/department/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    let list = [{ id: "0", name: "胜德体育" }];
    if (res.rows && res.rows.length > 0) {
      departmentList.value = list.concat(res.rows.filter((item) => item.id === proxy.useUserStore().user.deptId));
    }
    proxy.post("/inventory/getQuantityByDepartment", {}).then((res) => {
      for (let i = 0; i < departmentList.value.length; i++) {
        let list = res.filter((item) => item.departmentId === departmentList.value[i].id);
        if (list && list.length > 0) {
          departmentList.value[i].quantity = list[0].inventoryQuantity;
        }
      }
    });
  });
  proxy.post("/warehouse/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    warehouseList.value[0].children = res.rows.filter((item) => item.type !== "1");
    proxy.post("/inventory/getQuantityByWarehouse", { departmentId: sourceList.value.pagination.departmentId }).then((res) => {
      if (warehouseList.value[0].children && warehouseList.value[0].children.length > 0) {
        for (let i = 0; i < warehouseList.value[0].children.length; i++) {
          let list = res.filter((item) => item.warehouseId === warehouseList.value[0].children[i].id);
          if (list && list.length > 0) {
            warehouseList.value[0].children[i].quantity = list[0].inventoryQuantity;
          }
        }
      }
    });
  });
};
getDemandData();
const getList = async (req, status) => {
  if (status) {
    sourceList.value.pagination = {
      pageNum: sourceList.value.pagination.pageNum,
      pageSize: sourceList.value.pagination.pageSize,
    };
  } else {
    sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  }
  let path = "/inventory/page";
  loading.value = true;
  proxy.post(path, sourceList.value.pagination).then((res) => {
    sourceList.value.data = res.rows;
    sourceList.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
const clickReset = () => {
  proxy.$refs.treeCategory.setCurrentKey(null);
  getList("", true);
};
const handleNodeClick = (val) => {
  getList({ warehouseId: val.id });
};
const getTotal = (item) => {
  let total = 0;
  if (item.quantity && item.balanceUnitPrice) {
    total = Number(Math.round(item.quantity * item.balanceUnitPrice * 100) / 100);
  }
  return proxy.moneyFormat(total, 2);
};
const changeDepartment = () => {
  proxy.$refs.treeCategory.setCurrentKey(null);
  proxy.post("/inventory/getQuantityByWarehouse", { departmentId: sourceList.value.pagination.departmentId }).then((res) => {
    if (warehouseList.value[0].children && warehouseList.value[0].children.length > 0) {
      for (let i = 0; i < warehouseList.value[0].children.length; i++) {
        let list = res.filter((item) => item.warehouseId === warehouseList.value[0].children[i].id);
        if (list && list.length > 0) {
          warehouseList.value[0].children[i].quantity = list[0].inventoryQuantity;
        } else {
          warehouseList.value[0].children[i].quantity = null;
        }
      }
    }
  });
  getList({ departmentId: sourceList.value.pagination.departmentId });
};
const showName = (item) => {
  let name = item.name;
  if (item.quantity) {
    name = name + "（" + item.quantity + "）";
  }
  return name;
};
const renderContent = (h, data) => {
  if (data.data.quantity) {
    return h("span", h("span", null, data.node.label + "（" + data.data.quantity + "）"));
  } else {
    return h("span", h("span", null, data.node.label));
  }
};
onMounted(() => {
  getList();
});
const emit = defineEmits(["selectBOM"]);
const deriveExcel = () => {
  ElMessageBox.confirm("你是否确认此操作", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      proxy.getFile("/inventory/exportExcel", sourceList.value.pagination).then((res) => {
        proxy.downloadFile(res, "库存.xlsx");
      });
    })
    .catch(() => {});
};
</script>

<style lang="scss" scoped>
::v-deep(.top-card) {
  height: 67px;
  overflow-y: auto;
  overflow-x: hidden;
  display: grid;
  place-items: center;
  .el-card__body {
    width: 100%;
    padding: 15px 20px 10px 20px !important;
  }
}
</style>
