<template>
  <div class="user">
    <div class="tree">
      <AllTreeList title="分类" submitType="2" :hiddenBtn="true" :data="treeListData" v-model="sourceList.pagination.productClassifyId"
                   @change="treeChange">
      </AllTreeList>
    </div>
    <div class="content">
      <byTable :source="sourceList.data" :pagination="sourceList.pagination" :config="config" :loading="loading" :selectConfig="selectConfig"
               highlight-current-row :action-list="[
        ]" @get-list="getList">

        <template #pic="{ item }">
          <div v-if="item.fileList.length > 0">
            <img :src="item.fileList[0].fileUrl" class="pic" @click="handleClickFile(item.fileList[0])" />
          </div>
          <div v-else></div>
        </template>
        <template #name="{ item }">
          <div>
            <span class="el-click">{{ item.name }}</span>
          </div>
        </template>
        <template #size="{ item }">
          <div v-if="item['length'] && item.width && item.height">
            <span>{{ item['length'] }}cm</span>*
            <span>{{ item.width }}cm</span>*
            <span>{{ item.height }}cm</span>
          </div>
          <div v-else></div>
        </template>
        <template #price="{ item }">
          <div v-if="item.price">
            <span>{{ item.currency }} {{ moneyFormat(item.price ,2)}}</span>
          </div>
          <div v-else></div>
        </template>
        <template #costPrice="{ item }">
          <div v-if="item.costPrice">
            <span>{{ item.currency }} {{ moneyFormat(item.costPrice ,2)}}</span>
          </div>
          <div v-else></div>
        </template>
      </byTable>
    </div>
  </div>
</template>

<script setup>
import { computed, ref } from "vue";
import byTable from "@/components/byTable/index";
import useUserStore from "@/store/modules/user";
import AllTreeList from "@/components/product/allTreeList.vue";
import { ElMessage, ElMessageBox } from "element-plus";

const { proxy } = getCurrentInstance();
const props = defineProps({
  selectStatus: Boolean,
  warehouseId: String,
  rowId: {
    type: String,
    default: "",
  },
});
const warehouseList = ref([]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    keyword: "",
    companyId: "",
    definition: "",
    productClassifyId: "",
  },
});
const productUnit = ref([]);
const definition = ref([
  {
    label: "产品",
    value: "1",
  },
  {
    label: "物料",
    value: "2",
  },
]);
const loading = ref(false);
const companyData = ref([]);
const selectConfig = computed(() => {
  return [
    {
      label: "归属公司",
      prop: "companyId",
      data: companyData.value,
      isShowAll: false,
    },
    {
      label: "物品类型",
      prop: "definition",
      data: definition.value,
    },
  ];
});
const config = computed(() => {
  return [
    {
      attrs: {
        label: "图片",
        slot: "pic",
        align: "center",
        width: 80,
      },
    },
    {
      attrs: {
        label: "物料分类",
        prop: "classifyName",
        "min-width": 150,
      },
    },
    {
      attrs: {
        label: "物料编码",
        prop: "customCode",
        width: 120,
      },
    },
    {
      attrs: {
        label: " 物料名称",
        slot: "name",
        "min-width": 150,
      },
    },
    {
      attrs: {
        label: "物料材质",
        prop: "material",
        width: 120,
      },
    },
    {
      attrs: {
        label: "物料型号",
        prop: "spec",
        width: 120,
      },
    },
    {
      attrs: {
        label: "单位",
        prop: "unit",
        width: 80,
      },
      render(val) {
        return proxy.dictKeyValue(val, materialUnitData.value);
      },
    },
    {
      attrs: {
        label: "尺寸",
        slot: "size",
        width: 180,
      },
    },
    {
      attrs: {
        label: "净重",
        prop: "netWeight",
        width: 100,
      },
      render(val) {
        if (val) {
          return val + " kg";
        }
      },
    },
    {
      attrs: {
        label: "成本价",
        slot: "costPrice",
        width: 100,
      },
    },

    // {
    //   attrs: {
    //     label: "操作",
    //     slot: "btn",
    //     width: 120,
    //     fixed: "right",
    //     align: "center",
    //   },
    // },
  ];
});

const treeListData = ref([]);

const arrayRecursion = (arr, definition) => {
  arr.forEach((item) => {
    item.definition = definition;
    if (item.children && item.children.length > 0) {
      arrayRecursion(item.children, definition);
    }
  });
  return arr;
};
const getDict = () => {
  proxy
    .get("/tenantDept/list", {
      pageNum: 1,
      pageSize: 9999,
      keyword: "",
      tenantId: proxy.useUserStore().user.tenantId,
      type: 0,
    })
    .then((res) => {
      companyData.value = res.data.map((x) => ({
        ...x,
        label: x.deptName,
        value: x.deptId,
      }));
      if (res.data && res.data.length > 0) {
        sourceList.value.pagination.companyId = companyData.value[0].value;
      }
      getList();
    });

  Promise.all([
    proxy.post("/productClassify/tree", {
      parentId: "",
      name: "",
      definition: "1",
    }),
    proxy.post("/productClassify/tree", {
      parentId: "",
      name: "",
      definition: "2",
    }),
  ]).then((res) => {
    if (res && res.length > 1) {
      res[1].forEach((x) => {
        x.id = x.id + "";
      });
      treeListData.value = [
        {
          id: "-1",
          label: "全部",
          parentId: "",
          children: [
            {
              id: "1",
              definition: "1",
              label: "产品",
              parentId: "-1",
              children: arrayRecursion(res[0], "1"),
            },
            {
              id: "2",
              definition: "2",
              label: "物料",
              parentId: "-1",
              children: arrayRecursion(res[1], "2"),
            },
          ],
        },
      ];
    }
  });
};

const getList = (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.post("/productInfo/page", sourceList.value.pagination).then((res) => {
    sourceList.value.data = res.rows;
    sourceList.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
    const productIdList = res.rows.map((x) => x.id);
    // 请求文件数据并回显
    if (productIdList.length > 0) {
      proxy.getFile(productIdList, sourceList.value.data, "id");
    }
  });
};

const treeChange = (e) => {
  if (e.id != undefined && e.id != "-1") {
    let productClassifyId = "";
    if (["1", "2"].includes(e.id)) {
      sourceList.value.pagination.productClassifyId = "";
      sourceList.value.pagination.definition = e.id;
    } else {
      if (e.id != e.definition) {
        productClassifyId = e.id;
      }
      sourceList.value.pagination.productClassifyId = productClassifyId;
      sourceList.value.pagination.definition = e.definition;
    }
    getList();
  } else {
    sourceList.value.pagination.productClassifyId = "";
    sourceList.value.pagination.definition = "";
    getList();
  }
};
getDict();

const checkTheFlow = (item) => {
  proxy.$router.replace({
    path: "/purchaseSales/stockManage/record",
    query: {
      productId: item.productId,
      warehouseId: item.warehouseId,
    },
  });
};
const deriveExcel = () => {
  console.log("deriveExcel");
};
// const clickSelect = (item) => {
//   proxy.$emit("select", item);
// };
const goodList = ref([]);
const clickSelect = (row) => {
  const flag = goodList.value.some((x) => x.id === row.id);
  if (flag)
    return ElMessage({
      message: "该物品已选择",
      type: "info",
    });
  goodList.value.push({
    ...row,
    goodType: sourceList.value.pagination.definition,
  });
  return ElMessage({
    message: "选择成功",
    type: "success",
  });
  proxy.$emit("select", item);
};
const handleRemove = (index) => {
  goodList.value.splice(index, 1);
  return ElMessage({
    message: "删除成功",
    type: "success",
  });
};

const handleCancel = () => {
  goodList.value = [];
  proxy.$emit("cancel");
};

const handleSubmit = () => {
  if (!goodList.value.length > 0)
    return ElMessage({
      message: "请添加货品",
      type: "info",
    });
  proxy.$emit("select", goodList.value);
  goodList.value = [];
};
</script>

<style lang="scss" scoped>
.user {
  padding: 10px;
  display: flex;
  justify-content: space-between;
  .tree {
    width: 300px;
  }
  .content {
    width: calc(100% - 310px);
  }
}
.pic {
  object-fit: contain;
  width: 50px;
  height: 50px;
  cursor: pointer;
  vertical-align: middle;
}
</style>
