<script>
import BaseCard from "@/components/BaseCard.vue";
import DTFhead from "./components/detailHead.vue";
import DetailDialog from "@/components/detailDialog.vue";
const { remote } = require("electron");
const { pathMap } = require("@/config/index.js");
import platformJson from "@/json/platform.json";
import LogList from "@//components/LogList.vue";
const { Menu } = remote;
import dayjs from "dayjs";

export default {
  name: "dtf-batch-detail",
  components: { BaseCard, DTFhead, DetailDialog, LogList },
  props: {
    user: {
      default: () => ({
        avatar: "",
        factory: {}
      }),
      type: Object
    },
    factoryType: { type: String, default: "CN" }
  },
  data() {
    return {
      logVisible: false,
      detailVisible: false,
      curData: {},
      logList: [],
      selection: [],
      podOrderProductIds: [],
      pageInfo: {
        currentPage: 1,
        pageSize: 10,
        total: 2
      },
      cardList: [],
      timer: null,
      curBatchArrangeNum: "",
      detailRow: {
        batchArrangeNum: { label: "批次号", value: "" },
        operationNum: { label: "操作单数量", value: "" },
        materialNum: { label: "素材数量", value: "" },
        craftType: { label: "工艺类型", value: "" },
        standardDesignImage: { label: "规范素材", value: "" },
        createTime: { label: "创建时间", value: "" },
        layoutStatus: { label: "排版状态", value: "" },
        status: { label: "操作单状态", value: "" }
      },
      platformJson: platformJson,
      layoutStatus: {
        1: { label: "待排版", type: "warning" },
        2: { label: "排版中", type: "info" },
        3: { label: "排版成功", type: "success" },
        4: { label: "排版失败", type: "danger" },
        5: { label: "部分成功", type: "success" }
      }
    };
  },
  mounted() {
    this.loadRowData();
    this.timer = setInterval(() => this.getCardList(), 5 * 60 * 1000);
    this.curData = {};
    this.selection = [];
    this.podOrderProductIds = [];
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    async loadRowData() {
      try {
        const params = this.$route.params;
        this.curBatchArrangeNum = params.batchArrangeNum;
        Object.keys(this.detailRow).forEach(key => {
          // 路由里有对应值就赋值，没有则保留默认值
          if (params[key] !== undefined) {
            this.detailRow[key].value = params[key];
          }
        });
        await this.getCardList();
      } catch (error) {
        console.log(error);
      }
    },
    async getCardList(value) {
      this.selection = [];
      this.podOrderProductIds = [];
      let params = {
        currentPage: this.pageInfo.currentPage,
        pageSize: this.pageInfo.pageSize,
        batchArrangeNumber: this.curBatchArrangeNum
      };
      if (value) {
        params = { ...params, ...value };
      }
      try {
        const { data } = await this.$api.post(
          pathMap["listOperationByBatch"],
          params
        );
        this.cardList = data.records;
        this.pageInfo.total = data.total;
        console.log("listOperationByBatch", data);
      } catch (error) {
        console.log(error);
      }
    },
    handleSelect(rows) {
      console.log("选中行", rows);
    },
    handleSizeChange(size) {
      this.pageInfo.pageSize = size;
      this.pageInfo.currentPage = 1;
      this.getCardList();
    },
    handleCurrentChange(page) {
      this.pageInfo.currentPage = page;
      this.getCardList();
    },
    copyText(text) {
      const { clipboard } = window.require("electron").remote;
      // 复制文本，同步方法，调用即生效
      clipboard.writeText(text);
      this.$message.success(`复制成功`);
    },
    getOrderDelayText(createTime) {
      if (!createTime) return "--";
      const createAt = dayjs(createTime);
      if (!createAt.isValid()) return "--";
      const diffMinutes = Math.max(0, dayjs().diff(createAt, "minute"));
      const baseHours = Math.floor(diffMinutes / 60);
      const remainMinutes = diffMinutes % 60;
      const hours = baseHours + (remainMinutes > 30 ? 1 : 0);
      return `${hours}h`;
    },
    openMenu(e) {
      e.preventDefault();
      const template = [
        {
          label: "全部选择",
          click: () => {
            const cardIds = this.cardList.map(el => el.id);
            this.selection = Array.from(
              new Set([...this.selection, ...cardIds])
            );
            this.rebuildPodOrderProductIds();
          }
        },
        {
          label: "取消选择",
          click: () => {
            const cardIdSet = new Set(this.cardList.map(el => el.id));
            this.selection = this.selection.filter(id => !cardIdSet.has(id));
            this.rebuildPodOrderProductIds();
          }
        }
      ];
      const menu = Menu.buildFromTemplate(template);
      menu.popup({ x: e.clientX, y: e.clientY });
    },

    parseImageAry(imageAry) {
      if (typeof imageAry !== "string" || !imageAry.trim()) return [];
      const trimmed = imageAry.trim();
      if (trimmed.startsWith("http")) {
        return trimmed
          .split(",")
          .map(url => ({ url: url.trim() }))
          .filter(item => item.url);
      }
      try {
        const parsed = JSON.parse(trimmed);
        if (!Array.isArray(parsed)) return [{ url: trimmed }];
        const result = [];
        for (const item of parsed) {
          if (typeof item === "string" && item) {
            result.push({ url: item });
          } else if (item && typeof item === "object" && "url" in item) {
            const url = item.url;
            if (url) {
              result.push({
                url,
                title: item.title
              });
            }
          }
        }
        return result;
      } catch {
        return [{ url: trimmed }];
      }
    },
    async openLogDialog(item) {
      try {
        const { data } = await this.$api.post(pathMap["getPodOrderLog"], {
          id: item.id
        });
        this.logList = data;
        this.logVisible = true;
      } catch (error) {
        console.log(error);
      }
    },
    changeActive(item) {
      const index = this.selection.indexOf(item.id);
      if (index > -1) {
        this.selection.splice(index, 1);
      } else {
        this.selection.push(item.id);
      }
      this.rebuildPodOrderProductIds();
    },
    rebuildPodOrderProductIds() {
      const selectedSet = new Set(this.selection);
      this.podOrderProductIds = this.cardList
        .filter(card => selectedSet.has(card.id))
        .map(card => card.podOrderProductId);
    },
    isSelected(item) {
      return this.selection.includes(item.id);
    },
    handleViewDetail(item) {
      try {
        this.detailVisible = true;
        this.curData = item;
      } catch (e) {
        console.error(e);
      }
    },
    getPlatformImg(code) {
      const lowerCode = code.toLowerCase();
      const item = platformJson.find(el =>
        el.type.toLowerCase().includes(lowerCode)
      );

      if (item) {
        // console.log(item.icon);

        return item.icon.split("/").pop();
      }
      return "";
    }
  }
};
</script>

<template>
  <div style="height:100%" @contextmenu.prevent="openMenu">
    <div class="page">
      <DTFhead
        :user="user"
        :factoryType="factoryType"
        @search="getCardList"
        :selection="selection"
        :podOrderProductIds="podOrderProductIds"
      ></DTFhead>
      <div class="rowBox">
        <div class="rowItem" v-for="(item, index) in detailRow" :key="index">
          <div
            style="display: flex;
        flex-direction: column; align-items: center;"
          >
            <div style="min-height: 22px;">{{ item.label }}</div>
            <div style="min-height: 22px;" v-if="item.label == '排版状态'">
              <el-tag :type="layoutStatus[item.value]?.type">{{
                layoutStatus[item.value]?.label
              }}</el-tag>
            </div>
            <div v-else style="min-height: 22px;">
              {{ item.value }}
            </div>
          </div>
        </div>
      </div>
      <div class="card-content">
        <div class="card-grid">
          <div
            class="card-grid-item"
            v-for="(item, index) in cardList"
            :key="index"
            @click="changeActive(item)"
          >
            <BaseCard
              style="cursor: pointer;"
              :card-item="item"
              :active="isSelected(item)"
              :show-sku="false"
              :show-product-info="false"
              :image-field="'variantImage'"
              :padding-top="'100%'"
            >
              <template #bottom_left>
                <span
                  class="operation-number"
                  :title="`操作单号:${item.operationNo}`"
                  @click.stop="copyText(item.operationNo || '')"
                >
                  {{ item.operationNo }}
                </span>
              </template>
              <template #top_right>
                <el-tooltip
                  v-if="item.layout"
                  effect="light"
                  content="排版完成"
                  placement="bottom"
                >
                  <div
                    style="
                    background-color: #f0f9eb;
                    color: #6fc844;
                    border-radius: 4px;
                    padding:5px;
                    font-size: 20px;
                  "
                  >
                    排
                  </div>
                </el-tooltip>
              </template>

              <template #images>
                <div class="flex-between">
                  <div class="images-position">
                    <div class="images-container">
                      <div
                        v-for="(img, index) in parseImageAry(item.imageAry)"
                        :key="index"
                        :title="img.title"
                        class="item-image"
                      >
                        <el-image
                          :src="img.url"
                          height="50"
                          :preview-src-list="
                            parseImageAry(item.imageAry).map(i => i.url)
                          "
                          :initial-index="index"
                        />
                      </div>
                    </div>
                  </div>
                  <div class="flex-row flex-row-gap15">
                    <el-tooltip
                      class="item"
                      effect="dark"
                      :content="'用户编码: ' + item?.userMark"
                      placement="bottom"
                    >
                      <span
                        style="
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        width: 100%;
                        display: inline-block;
                        margin-right: 8px;
                      "
                        @click.stop="copyText(String(item?.userMark || ''))"
                      >
                        {{ item?.userMark || "AAAF" }}
                      </span>
                    </el-tooltip>
                    <img
                      v-if="item.platform"
                      :src="`/images/icon/${getPlatformImg(item.platform)}`"
                      style="width: 30px"
                    />
                  </div>
                </div>
              </template>
              <template #operations>
                <div class="flex-row flex-row-gap6">
                  <div
                    class="quantity-badge multiple-quantity-badge-color"
                    :title="
                      `类型:${item.customizedQuantity === 1 ? '单面' : '双面'}`
                    "
                  >
                    {{ item.customizedQuantity === 1 ? "单" : "多" }}
                  </div>
                  <i
                    class="el-icon-tickets quantity-badge"
                    style="background-color: #41c792;"
                    @click.stop="openLogDialog(item)"
                    title="操作日志"
                  >
                  </i>
                  <i
                    style="background-color: #2183fe;"
                    class="el-icon-search quantity-badge"
                    @click.stop="handleViewDetail(item)"
                    title="查看详情"
                  >
                  </i>
                </div>
              </template>
              <template #info>
                <div class="card-info-grid">
                  <div class="card-info-row full">
                    <span
                      class="info-value ellipsis"
                      :title="item.productName || ''"
                    >
                      {{ item.productName }}
                    </span>
                  </div>
                  <div class="card-info-row">
                    <span
                      class="info-value clickable ellipsis"
                      :title="`变体SKU:${item.variantSku || ''}`"
                      @click.stop="copyText(item.variantSku || '')"
                    >
                      {{ item.variantSku }}
                    </span>
                  </div>
                  <div class="card-info-row">
                    <span class="info-label">工艺：</span>
                    <span class="info-value">{{ item.craftName }}</span>
                  </div>
                  <div class="card-info-row">
                    <span
                      class="info-value clickable ellipsis"
                      :title="`库存SKU:${item.thirdSkuCode || ''}`"
                      @click.stop="copyText(item.thirdSkuCode || '')"
                    >
                      {{ item.thirdSkuCode }}
                    </span>
                  </div>
                  <div class="card-info-row">
                    <span class="info-label">店铺单号：</span>
                    <span
                      class="info-value clickable ellipsis"
                      :title="`店铺单号:${item.shopNumber || ''}`"
                      @click.stop="copyText(item.shopNumber || '')"
                      >{{ item.shopNumber }}</span
                    >
                  </div>
                  <div class="card-info-row">
                    <span class="info-label">款号：</span>
                    <span
                      class="info-value clickable ellipsis"
                      :title="`款号:${item.supplierProductNo || ''}`"
                      @click.stop="copyText(item.supplierProductNo || '')"
                      >{{ item.supplierProductNo }}</span
                    >
                  </div>
                  <div class="card-info-row">
                    <span class="info-label">客户单号：</span>
                    <span
                      class="info-value clickable ellipsis"
                      :title="`客户单号:${item.thirdOrderNumber || ''}`"
                      @click.stop="copyText(item.thirdOrderNumber || '')"
                      >{{ item.thirdOrderNumber }}</span
                    >
                  </div>
                  <div class="card-info-row">
                    <span class="info-label">批次号：</span>
                    <span
                      class="info-value clickable ellipsis"
                      :title="`批次号:${item.batchArrangeNumber || ''}`"
                      @click.stop="copyText(item.batchArrangeNumber || '')"
                      >{{ item.batchArrangeNumber }}</span
                    >
                  </div>
                  <div class="card-info-row" style="color: red">
                    <span class="info-label">状态：</span>
                    <span class="info-value">{{ item.statusName }}</span>
                  </div>
                  <div class="card-info-row full delay-time-row">
                    <span
                      class="delay-time-value"
                      :title="
                        `订单延期:${getOrderDelayText(item.orderCreateTime)}`
                      "
                    >
                      {{ getOrderDelayText(item.orderCreateTime) }}
                    </span>
                  </div>
                </div>
              </template>
            </BaseCard>
          </div>
        </div>
      </div>
      <div class="table-pagination">
        <el-pagination
          small
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageInfo.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
        />
      </div>
    </div>
    <el-dialog
      :visible.sync="logVisible"
      title="操作日志"
      width="1000px"
      :close-on-click-modal="false"
    >
      <LogList v-if="logList.length" :log-list="logList" />
      <div v-else class="empty-content">暂无数据</div>
    </el-dialog>
    <DetailDialog :show.sync="detailVisible" :info="curData"></DetailDialog>
  </div>
</template>

<style scoped lang="less">
.page {
  display: flex;
  flex-direction: column;
  height: calc(100% - 25px);
}
.table-pagination {
  margin: 10px 0;
  text-align: center;
}

.rowBox {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  justify-items: center;
  align-items: center;
  background-color: #f3f3f3;
  padding: 10px 0;
  .rowItem {
    width: 100%;
    border-right: 1px solid #c6c6c6;
    :nth-last-child {
      border: none;
    }
  }
}

.card-content {
  height: 100%;
  flex: 1;
  overflow-y: auto;
}
.card-pagination {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
}

.card-selected-info {
  font-size: 14px;
  color: #606266;

  .highlight {
    color: red;
    font-weight: bold;
  }
}

.card-grid {
  display: grid;
  grid-template-columns: repeat(7, minmax(0, 1fr));
  grid-template-rows: max-content;
  gap: 10px;
  padding: 5px;
}
.operation-number {
  font-size: 12px;
  cursor: pointer;
  background: rgba(255, 255, 255, 0.75);
  padding: 2px 6px;
  border-radius: 4px;
  max-width: 100%;
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.quantity-badge {
  width: 28px;
  height: 28px;
  color: #fff;
  border-radius: 4px;
  font-size: 16px;
  line-height: 28px;
  text-align: center;
  margin-left: 5px;
}

.multiple-quantity-badge-color {
  background-color: #e6a23c;
}

.product-mark-badge {
  border: 2px solid #f56c6c;
  color: #f56c6c;
  font-weight: 700;
  height: 28px;
  width: 28px;
  text-align: center;
  border-radius: 6px;
  font-size: 16px;
}

.card-info-grid {
  display: grid;
  grid-template-columns: auto auto;
  gap: 4px;
  font-size: 12px;
  margin-top: 6px;

  .full {
    grid-column: span 2;
  }
}

.card-info-row {
  display: flex;
  overflow: hidden;
}

.delay-time-row {
  justify-content: flex-end;
  margin-top: 2px;
}

.delay-time-value {
  color: red;
  font-weight: 600;
}

.info-label {
  flex-shrink: 0;
  color: #909399;
}

.info-value {
  flex: 1;
  min-width: 0;

  &.ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  &.clickable {
    cursor: pointer;
    color: #409eff;

    &:hover {
      text-decoration: underline;
    }
  }
}
.flex-between {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  overflow: hidden;
  gap: 6px;

  .images-position {
    flex: 1;
    overflow: auto hidden;
    .images-container {
      width: 100%;
      display: flex;
      gap: 6px;
    }
    .item-image {
      width: 50px;
      min-width: 50px;
      height: 50px;
      border: 1px solid #eee;
      cursor: pointer;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }

  b {
    margin-right: 5px;
    font-size: 15px;
  }
}

.flex-row {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15px;
}
.flex-row-gap15 {
  gap: 15px;
}
.flex-row-gap6 {
  gap: 6px;
}
@media (max-width: 1920px) {
  .card-grid {
    grid-template-columns: repeat(6, minmax(0, 1fr));
  }
}
@media (max-width: 1750px) {
  .card-grid {
    grid-template-columns: repeat(5, minmax(0, 1fr));
  }
  // .card-info-grid {
  //   grid-template-columns: 1fr 180px;
  // }
}
@media (max-width: 1550px) {
  .card-grid {
    grid-template-columns: repeat(3, minmax(0, 1fr));
  }
  // .card-info-grid {
  //   grid-template-columns: 1fr 200px;
  // }
}
</style>
