<template>
  <div class="tenant">
    <!-- <Banner /> -->
    <div class="content">
      <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        highlight-current-row
        :selectConfig="selectConfig"
        :table-events="{
          //element talbe事件都能传
          select: (data) => selectRow(data, 'row'),
          'select-all': (data) => selectAll(data, 'all'),
          'sort-change': sortChange,
        }"
        :action-list="[
          {
            text: '采购',
            disabled: selectData.length === 0 && selectAllData.length === 0,
            action: () => start(20),
          },
        ]"
        @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>
      </byTable>
    </div>
  </div>
</template>
  
<script setup>
import { ElMessage, ElMessageBox } from "element-plus";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
    status: "15,30",
    subscribeTimeSort: "",
    productNameSort: "",
  },
});
const dialogVisible = ref(false);
let rules = ref({
  name: [{ required: true, message: "请输入供应商名称", trigger: "blur" }],
});
const { proxy } = getCurrentInstance();
const selectConfig = reactive([
  {
    label: "状态",
    prop: "status",
    data: [
      {
        label: "待采购",
        value: "15",
      },
      {
        label: "部分采购",
        value: "30",
      },
    ],
  },
  {
    label: "收货仓库",
    prop: "receiptWarehouseId",
    data: [],
  },
  {
    label: "产品归属部门",
    prop: "deptId",
    data: [],
  },
  {
    label: "提交状态",
    prop: "subStatus",
    data: [
      {
        label: "未提交",
        value: "1",
      },
      {
        label: "部分提交",
        value: "2",
      },
      {
        label: "已提交",
        value: "3",
      },
    ],
  },
]);
const config = computed(() => {
  return [
    {
      type: "selection",
      attrs: {
        checkAtt: "isCheck",
      },
    },
    {
      attrs: {
        label: "申购单号",
        prop: "subscribeCode",
        width: 150,
      },
    },
    {
      attrs: {
        label: "货品类型",
        prop: "productDefinition",
        width: 100,
      },
      render(definition) {
        return definition == 1 ? "产品" : definition == 2 ? "物料" : "";
      },
    },

    {
      attrs: {
        label: "物品编码",
        prop: "productCustomCode",
        width: 150,
      },
    },
    {
      attrs: {
        label: "物品名称",
        prop: "productName",
        "min-width": 150,
        sortable: "custom",
      },
    },
    {
      attrs: {
        label: "产品图片",
        slot: "pic",
        width: 80,
      },
    },
    {
      attrs: {
        label: "规格",
        prop: "productSpec",
        // width: 120,
      },
    },
    {
      attrs: {
        label: "单位",
        prop: "productUnit",
        width: 80,
      },
      render(unit) {
        return proxy.dictDataEcho(unit, productUnit.value);
      },
    },
    {
      attrs: {
        label: "申购数量",
        prop: "count",
        width: 100,
      },
    },
    {
      attrs: {
        label: "已采购数量",
        prop: "purchaseCount",
        width: 100,
      },
    },
    {
      attrs: {
        label: "收货仓库",
        prop: "receiptWarehouseName",
        width: 130,
      },
    },
    {
      attrs: {
        label: "要求到货时间",
        prop: "planArrivalTime",
        width: 130,
      },
    },
    {
      attrs: {
        label: "采购状态",
        prop: "status",
        width: 100,
      },
      render(status) {
        return status == 15 ? "待采购" : status == 20 ? "已采购" : "部分采购";
      },
    },
    {
      attrs: {
        label: "申购人",
        prop: "subcribeName",
        width: 100,
      },
    },
    {
      attrs: {
        label: "申购时间",
        prop: "subcribeTime",
        width: 155,
        sortable: "custom",
      },
    },
    {
      attrs: {
        label: "操作",
        width: "80",
        align: "center",
      },
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "采购",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              selectDataOne.value = [row];
              start(10);
            },
          },
        ];
      },
    },
  ];
});

const formData = reactive({
  data: {
    type: "1",
  },
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);
const formConfig = computed(() => {
  return [];
});

const getList = async (req) => {
  if (req === undefined || req.status === "") {
    req = {
      ...req,
      neStatus: "99",
      status: "15,30",
    };
  }
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  getDeptList();
  loading.value = true;
  proxy
    .post("/subscribeDetail/pageByWdly", sourceList.value.pagination)
    .then((message) => {
      message.rows.forEach((x) => {
        if (x.status <= 30) {
          x.isCheck = true;
        } else {
          x.isCheck = false;
        }
      });
      sourceList.value.data = message.rows.map((x) => ({
        ...x,
        ...JSON.parse(x.victoriatouristJson),
        fileList: [],
      }));
      sourceList.value.pagination.total = message.total;
      setTimeout(() => {
        loading.value = false;
      }, 200);
      const productIdList = message.rows.map((x) => x.bussinessId);
      // 请求文件数据并回显
      if (productIdList && productIdList.length > 0) {
        proxy
          .post("/fileInfo/getList", { businessIdList: productIdList })
          .then((fileObj) => {
            for (let i = 0; i < sourceList.value.data.length; i++) {
              const e = sourceList.value.data[i];
              for (const key in fileObj) {
                if (e.bussinessId === key) {
                  e.fileList = fileObj[key];
                }
              }
            }
          });
      }
    });
};

const selectData = ref([]);
const selectDataOne = ref([]);
const selectAllData = ref([]);
const selectType = ref("row");
const selectRow = (data, type) => {
  selectType.value = type;
  selectData.value = data;
};
const selectAll = (data, type) => {
  selectType.value = type;
  selectAllData.value = data;
};
watch(selectData, (newVal, oldVal) => {
  if (newVal.length == 0) {
    sourceList.value.data.forEach((x) => {
      if (x.status <= 30) {
        x.isCheck = true;
      } else {
        x.isCheck = false;
      }
    });
  } else if (newVal.length == 1) {
    const current = newVal[0];
    sourceList.value.data.forEach((x) => {
      if (
        x.receiptWarehouseId !== current.receiptWarehouseId ||
        x.deptId !== current.deptId
      ) {
        x.isCheck = false;
      }
    });
  }
});

const start = (type) => {
  if (selectType.value === "all") {
    let row = selectAllData.value[0];
    let receiptWarehouseId = row.receiptWarehouseId;
    let deptId = row.deptId;
    const flagReceiptWarehouseId = selectAllData.value.every(
      (x) => x.receiptWarehouseId === receiptWarehouseId
    );
    const flagDeptId = selectAllData.value.every((x) => x.deptId === deptId);
    if (flagReceiptWarehouseId && flagDeptId) {
      let ids = selectAllData.value.map((x) => x.id).join();
      proxy.$router.replace({
        path: "/platform_manage/process/processApproval",
        query: {
          flowKey: "wdly_purchase",
          ids,
          flowName: "采购申请",
          random: proxy.random(),
        },
      });
    } else {
      return ElMessage({
        message: `不能采购不同仓库或不同部门的商品`,
        type: "info",
      });
    }
  } else {
    let ids = [];
    let row = {};
    if (type === 10) {
      row = selectDataOne.value[0];
      ids = selectDataOne.value.map((x) => x.id).join();
    } else if (type === 20) {
      ids = selectData.value.map((x) => x.id).join();
      row = selectData.value[0];
    }
    proxy.$router.replace({
      path: "/platform_manage/process/processApproval",
      query: {
        flowKey: "wdly_purchase",
        ids,
        flowName: "采购申请",
        random: proxy.random(),
      },
    });
  }
};

const warehouseList = ref([]);
const productUnit = ref([]);
const deptData = ref([]);
const getDeptList = () => {
  proxy
    .post("/subscribe/getDepts", { status: sourceList.value.pagination.status })
    .then((res) => {
      deptData.value = res;
      selectConfig[2].data = res.map((x) => ({
        label: x.deptName,
        value: x.deptId,
      }));
    });
};
const getDict = () => {
  proxy.getDict(["unit"]).then((res) => {
    productUnit.value = res["unit"];
  });
  proxy
    .post("/warehouse/page", {
      pageNum: 1,
      pageSize: 999,
    })
    .then((message) => {
      warehouseList.value = message.rows;
      selectConfig[1].data = message.rows.map((x) => ({
        label: x.name,
        value: x.id,
      }));
    });
  // getDeptList();
};
getDict();

const sortChange = ({ column, prop, order }) => {
  sourceList.value.pagination.subscribeTimeSort = "";
  sourceList.value.pagination.productNameSort = "";
  let type = "";
  if (order === "ascending") {
    // 升序
    type = "1";
  } else if (order === "descending") {
    // 降序
    type = "0";
  } else {
    // 默认
  }
  if (column.label === "物品名称") {
    sourceList.value.pagination.productNameSort = type;
  } else if (column.label === "申购时间") {
    sourceList.value.pagination.subscribeTimeSort = type;
  } else {
    sourceList.value.pagination.subscribeTimeSort = "";
    sourceList.value.pagination.productNameSort = "";
  }
  getList();
};

sortChange({
  column: {
    label: "申购时间",
  },
  order: "descending",
  prop: undefined,
});

const handleClickFile = (file) => {
  window.open(file.fileUrl, "_blank");
};
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
// :deep(.el-table__header-wrapper .el-checkbox) {
//   display: none;
// }
.pic {
  object-fit: contain;
  width: 50px;
  height: 50px;
  cursor: pointer;
  vertical-align: middle;
}
</style>