<template>
  <div>
    <div style="margin-bottom: 10px" v-if="!props.selectStatus">
      <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" v-if="!props.selectStatus">
        <el-card style="height: calc(100vh - 242px); 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="props.selectStatus ? 24 : 20">
        <el-card :style="'overflow-y: auto; overflow-x: hidden; ' + (props.selectStatus ? 'height: calc(100vh - 184px)' : 'height: calc(100vh - 242px)')">
          <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>
          </byTable>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import byTable from "/src/components/byTable/index";
import { useRoute } from "vue-router";
import useTagsViewStore from "/src/store/modules/tagsView";

const { proxy } = getCurrentInstance();
const props = defineProps({
  selectStatus: Boolean,
  departmentId: String,
  warehouseId: String,
});
const route = useRoute();
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: "",
    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: 120,
        align: "right",
      },
    },
    {
      attrs: {
        label: "结存总价",
        slot: "total",
        width: 160,
        align: "right",
      },
    },
    {
      attrs: {
        label: "库存",
        prop: "quantity",
        width: 120,
      },
    },
    props.selectStatus
      ? {
          attrs: {
            label: "操作",
            width: 80,
            align: "center",
            fixed: "right",
          },
          renderHTML(row) {
            return [
              {
                attrs: {
                  label: "选择",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  clickSelect(row);
                },
              },
            ];
          },
        }
      : {
          attrs: {
            width: 1,
          },
        },
  ];
});
const getDemandData = () => {
  if (!props.selectStatus) {
    proxy.post("/department/page", { pageNum: 1, pageSize: 999 }).then((res) => {
      let list = [
        { id: "", name: "全部" },
        { id: "0", name: "胜德体育" },
      ];
      departmentList.value = list.concat(res.rows);
      if (!(route.query && route.query.backupDate)) {
        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;
      if (!(route.query && route.query.backupDate)) {
        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";
  if (route.query && route.query.backupDate) {
    path = "/inventoryBackup/detailPage";
  }
  if (props.warehouseId) {
    sourceList.value.pagination.warehouseId = props.warehouseId;
  }
  if (props.departmentId) {
    sourceList.value.pagination.departmentId = props.departmentId;
  }
  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 = () => {
  if (!props.selectStatus) {
    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);
  if (!(route.query && route.query.backupDate)) {
    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(() => {
  if (route.query && route.query.backupDate) {
    useTagsViewStore().visitedViews = useTagsViewStore().visitedViews.map((item) => {
      if (item.query && item.query.backupDateStr === route.query.backupDateStr) {
        return {
          ...item,
          name: "库存快照: " + route.query.backupDateStr,
          title: "库存快照: " + route.query.backupDateStr,
        };
      } else {
        return {
          ...item,
        };
      }
    });
    getList({ backupDate: route.query.backupDate });
  } else {
    getList();
  }
});
const emit = defineEmits(["selectBOM"]);
const clickSelect = (item) => {
  emit("selectBOM", item);
};
const deriveExcel = () => {
  if (route.query && route.query.backupDate) {
    proxy.getFile("/inventory/exportBackExcel", sourceList.value.pagination).then((res) => {
      proxy.downloadFile(res, "库存.xlsx");
    });
  } else {
    proxy.getFile("/inventory/exportExcel", sourceList.value.pagination).then((res) => {
      proxy.downloadFile(res, "库存.xlsx");
    });
  }
};
</script>

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