<template>
  <div class="tenant">
    <byTable
      :source="sourceList.data"
      :pagination="sourceList.pagination"
      :config="config"
      :loading="loading"
      highlight-current-row
      :selectConfig="selectConfig"
      :table-events="{
        select: selectRow,
      }"
      :action-list="[
        {
          text: '采购',
          disabled: selectData.length === 0,
          action: () => start(),
        },
      ]"
      @get-list="getList"
    >
      <template #claimTime="{ item }">
        <div>
          <span v-if="item.claimTime">{{ item.claimTime }}</span>
          <span v-else>未到账</span>
        </div>
      </template>
      <template #details="{ item }">
        <div>
          <el-button
            type="primary"
            link
            v-if="item.expendQuantity >= 0"
            @click="handleClickDetails(item)"
            >查看</el-button
          >
          <el-button
            type="primary"
            link
            style="color: #f54a45"
            v-else
            @click="handleClickDetails(item)"
            >查看</el-button
          >
        </div>
      </template>
      <template #btn="{ item }">
        <el-button type="primary" link @click="start(10, item)">采购</el-button>
      </template>
    </byTable>

    <el-dialog
      title="交接单"
      v-if="openHandover"
      v-model="openHandover"
      width="800"
    >
      <byForm
        :formConfig="formHandoverConfig"
        :formOption="formOption"
        v-model="productRow.data"
      >
        <template #remark>
          <div style="width: 100%">
            <Editor
              ref="remarkEditor"
              :readOnly="true"
              :value="productRow.data.remark"
            />
          </div>
        </template>
        <template #file>
          <div style="width: 100%">
            <el-upload
              v-model:fileList="productRow.data.fileList"
              action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
              multiple
              :on-preview="onPreviewFile"
            >
            </el-upload>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="openHandover = false" size="large">关 闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import { computed, nextTick, ref } from "vue";
import { ElMessage } from "element-plus";
import Editor from "@/components/Editor/index.vue";

const { proxy } = getCurrentInstance();
const loading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
    isReceived: "",
    dataType: "",
    purchaseStatus: "",
  },
});
const purchaseStatus = ref([
  { label: "未采购", value: "0" },
  { label: "部分采购", value: "1" },
  { label: "已采购", value: "2" },
]);
const corporationArr = ref([]);
const selectConfig = computed(() => [
  {
    label: "归属公司",
    prop: "corporationId",
    data: corporationArr.value,
  },
  {
    label: "采购状态",
    prop: "purchaseStatus",
    data: purchaseStatus.value,
  },
]);
const config = computed(() => {
  return [
    {
      type: "selection",
      attrs: {
        checkAtt: "isCheck",
      },
    },
    {
      attrs: {
        label: "归属公司",
        prop: "corporationName",
      },
    },
    {
      attrs: {
        label: "外销合同编号",
        prop: "contractCode",
        width: "160",
      },
    },
    {
      attrs: {
        label: "合同到账时间",
        slot: "claimTime",
        width: "155",
      },
    },
    {
      attrs: {
        label: "业务员",
        prop: "userName",
      },
    },
    {
      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: "quantity",
        width: "110",
      },
    },
    {
      attrs: {
        label: "待处理数量",
        prop: "expendQuantity",
        width: "110",
      },
    },
    {
      attrs: {
        label: "交接单",
        width: "100",
        align: "center",
        slot: "details",
      },
    },
    {
      attrs: {
        label: "操作",
        slot: "btn",
        width: "100",
        align: "center",
        fixed: "right",
      },
    },
  ];
});

const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/contractProduct/page", sourceList.value.pagination)
    .then((message) => {
      sourceList.value.data = message.rows.map((x) => ({
        ...x,
        isCheck: true,
      }));
      sourceList.value.pagination.total = message.total;
      setTimeout(() => {
        loading.value = false;
      }, 200);
    });
};
getList();
const productUnit = ref([]);
const getDict = () => {
  proxy
    .post("/corporation/page", { pageNum: 1, pageSize: 9999 })
    .then((res) => {
      corporationArr.value = res.rows.map((x) => ({
        ...x,
        label: x.name,
        value: x.id,
      }));
    });
  proxy.getDictOne(["unit"]).then((res) => {
    productUnit.value = res["unit"].map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
  });
};
getDict();
const selectData = ref([]);
const selectRow = (data) => {
  selectData.value = data;
};
const start = (type, row) => {
  if (type === 10) {
    selectData.value = [row];
  }
  if (selectData.value.length > 0) {
    let ids = selectData.value.map((x) => x.id).join();
    let arr = selectData.value.map((x) => ({
      contractId: x.contractId,
      contractCode: x.contractCode,
      claimTime: x.claimTime,
    }));
    let newArr = [];
    for (let i = 0; i < arr.length; i++) {
      const e = arr[i];
      let flag = newArr.some((x) => x.contractId === e.contractId);
      if (!flag) {
        newArr.push(e);
      }
    }
    proxy.$router.replace({
      path: "/platform_manage/process/processApproval",
      query: {
        flowKey: "purchase_flow",
        type: "handoverSlip",
        random: proxy.random(),
        ids,
        arr: JSON.stringify(newArr),
      },
    });
  } else {
    return ElMessage({
      message: "请勾选数据！",
      type: "info",
    });
  }
};

const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const formData = reactive({
  data: {
    list: [],
  },
});

watch(selectData, (newVal) => {
  if (newVal.length == 0) {
    sourceList.value.data.forEach((x) => {
      x.isCheck = true;
    });
  } else if (newVal.length == 1) {
    const current = newVal[0];
    sourceList.value.data.forEach((x) => {
      if (x.contractId !== current.contractId) {
        x.isCheck = false;
      }
    });
  }
});

const openHandover = ref(false);
const productRow = reactive({
  data: {
    productName: "",
    productModel: "",
    remark: "",
    fileList: [],
  },
});
const formHandoverConfig = computed(() => {
  return [
    {
      type: "title",
      title: "产品信息",
      label: "",
    },
    {
      type: "input",
      prop: "productName",
      label: "产品名称",
      itemType: "text",
      disabled: true,
    },
    {
      type: "input",
      prop: "productModel",
      label: "规格型号",
      itemType: "text",
      disabled: true,
    },
    {
      type: "slot",
      slotName: "remark",
      label: "交接单",
    },
    {
      type: "slot",
      prop: "file",
      slotName: "file",
      label: "附件",
    },
  ];
});
const remarkEditor = ref(null);
const handleClickDetails = (row) => {
  proxy
    .post("/flowProcess/getStartData", { flowId: row.flowId })
    .then(async (res) => {
      const current = res.contractProductList.find(
        (x) => x.productId === row.productId
      );
      productRow.data = current || {};
      productRow.data.fileList =
        current.fileList.map((x) => ({
          raw: x,
          name: x.fileName,
          url: x.fileUrl,
        })) || [];
      openHandover.value = true;
      await nextTick();
      remarkEditor.value.changeHtml(productRow.data.remark);
    });
};
const onPreviewFile = (file) => {
  window.open(file.raw.fileUrl, "_blank");
};
</script>

<style lang="scss" scoped>
.tenant {
  margin: 20px;
}
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
:deep(.el-table__header-wrapper .el-checkbox) {
  display: none;
}
</style>
<style>
.redClass {
  color: #f54a45 !important;
}
</style>
