<template>
  <view class="content-box">
    <uni-nav-bar
      fixed="true"
      statusBar="true"
      left-icon="back"
      title="任务报工"
      background-color="#157A2C"
      color="#fff"
      @clickLeft="back"
    ></uni-nav-bar>

    <view class="tabs_wrap">
      <view
        v-for="tab in tabs"
        :key="tab.value"
        class="tab_item"
        :class="{ active: tabValue === tab.value }"
        @click="handleTabClick(tab.value)"
      >
        {{ tab.label }}
      </view>
    </view>

    <view class="top-wrapper">
      <uni-easyinput
        prefixIcon="search"
        style="flex: 1"
        v-model="searchFrom.workOrderCode"
        placeholder="订单编码"
      ></uni-easyinput>
      <button class="search_btn" @click="doSearch">搜索</button>
      <button class="search_btn" @click="filterShow = true">筛选</button>
    </view>

    <view class="list_box">
      <u-list @scrolltolower="scrolltolower">
        <u-list-item v-for="(item, index) in dataList" :key="item.id || index">
          <view class="card_box">
            <view class="item_box rx-bc">
              <view class="round">{{ index + 1 }}</view>
              <view class="item_one perce100 rx-sc">
                <view class="lable">任务编号：</view>
                <view class="val">{{
                  tabValue === "4" ? item.code : item.assigneeCode
                }}</view>
              </view>
            </view>

            <view v-if="tabValue !== '4'" class="item_box rx-bc">
              <view class="item_one perce100 rx-sc">
                <view class="lable">订单编号：</view>
                <view class="val">{{ item.workOrderCode }}</view>
              </view>
            </view>

            <view class="item_box rx-bc">
              <view class="item_one perce100 rx-sc">
                <view class="lable">计划编号：</view>
                <view class="val">{{ item.productionPlanCode }}</view>
              </view>
            </view>

            <view class="item_box rx-bc">
              <view class="item_one perce100 rx-sc">
                <view class="lable">产品名称：</view>
                <view class="val">{{
                  tabValue === "4" ? item.categoryName : item.productName
                }}</view>
              </view>
            </view>

            <view class="item_box rx-bc">
              <view class="item_one perce100 rx-sc">
                <view class="lable">工序名称：</view>
                <view class="val">{{ item.taskName }}</view>
              </view>
            </view>

            <view v-if="tabValue !== '4'" class="item_box rx-bc">
              <view class="item_one perce50 rx-sc">
                <view class="lable">任务数量：</view>
                <view class="val">{{ item.quantity }}</view>
              </view>
              <view class="item_one perce50 rx-sc">
                <view class="lable">班组：</view>
                <view class="val">{{ item.assignTeamName }}</view>
              </view>
            </view>

            <template v-if="tabValue === '4'">
              <view class="item_box rx-bc">
                <view class="item_one perce50 rx-sc">
                  <view class="lable">执行部门：</view>
                  <view class="val">{{ item.executeGroupName || "-" }}</view>
                </view>
                <view class="item_one perce50 rx-sc">
                  <view class="lable">执行人：</view>
                  <view class="val">{{ item.executorName || "-" }}</view>
                </view>
              </view>
              <view class="item_box rx-bc">
                <view class="item_one perce50 rx-sc">
                  <view class="lable">产品编码：</view>
                  <view class="val">{{ item.categoryCode || "-" }}</view>
                </view>
                <view class="item_one perce50 rx-sc">
                  <view class="lable">牌号：</view>
                  <view class="val">{{ item.brandNum || "-" }}</view>
                </view>
              </view>
              <view class="item_box rx-bc">
                <view class="item_one perce50 rx-sc">
                  <view class="lable">型号：</view>
                  <view class="val">{{ item.modelType || "-" }}</view>
                </view>
                <view class="item_one perce50 rx-sc">
                  <view class="lable">规格：</view>
                  <view class="val">{{ item.specification || "-" }}</view>
                </view>
              </view>
              <view
                class="item_box rx-bc"
                v-if="item.realStartTime || item.realEndTime"
              >
                <view class="item_one perce100 rx-sc">
                  <view class="lable">实际时间：</view>
                  <view class="val"
                    >{{ item.realStartTime || "-" }} ~
                    {{ item.realEndTime || "-" }}</view
                  >
                </view>
              </view>
              <view class="item_box rx-bc" v-if="item.remark">
                <view class="item_one perce100 rx-sc">
                  <view class="lable">订单备注：</view>
                  <view class="val">{{ item.remark }}</view>
                </view>
              </view>
              <view class="item_box rx-bc" v-if="item.reportRemark">
                <view class="item_one perce100 rx-sc">
                  <view class="lable">报备注：</view>
                  <view class="val">{{ item.reportRemark }}</view>
                </view>
              </view>
            </template>

            <view v-if="tabValue !== '4'" class="item_box rx-bc">
              <view class="item_one perce100 rx-sc">
                <view class="lable">状态：</view>
                <view class="val">
                  <text class="tag" :class="disposalCls(item.disposalStatus)">{{
                    disposalText(item.disposalStatus)
                  }}</text>
                  <text class="tag tag-default" v-if="item.statusText">{{
                    item.statusText
                  }}</text>
                </view>
              </view>
            </view>

            <view class="action_row">
              <!-- 我的任务 / 班组任务：未处置时可接收 / 拒绝 -->
              <button
                v-if="canAcceptReject(item)"
                class="op_btn primary"
                @click="receiveTask(item.id, '1')"
              >
                接收
              </button>
              <button
                v-if="canAcceptReject(item)"
                class="op_btn warn"
                @click="receiveTask(item.id, '2')"
              >
                拒绝
              </button>

              <!-- 全部任务: 已拒绝可转派 -->
              <button
                v-if="tabValue === '2' && item.disposalStatus == '2'"
                class="op_btn primary"
                @click="reassignTask(item)"
              >
                转派
              </button>

              <!-- 详情 -->
              <button class="op_btn ghost" @click="details('detail', item)">
                详情
              </button>

              <!-- 报工 -->
              <button
                v-if="canReport(item)"
                class="op_btn primary"
                @click="details('report', item)"
              >
                报工
              </button>

              <!-- 报工记录 -->
              <button
                v-if="item.disposalStatus == '1' && tabValue !== '4'"
                class="op_btn ghost"
                @click="viewRecords(item.id)"
              >
                报工记录
              </button>
            </view>
          </view>
        </u-list-item>

        <u-list-item v-if="dataList.length === 0">
          <view style="margin-top: 20vh">
            <u-empty iconSize="150" textSize="32" text="暂无任务"></u-empty>
          </view>
        </u-list-item>
      </u-list>
    </view>

    <searchPopup
      :show="filterShow"
      ref="filterRef"
      @close="filterShow = false"
      @search="onFilterSearch"
    ></searchPopup>

    <reportDialog ref="reportRef" @success="reload"></reportDialog>
    <ncReportDialog ref="ncReportRef" @refreshList="reload"></ncReportDialog>
    <recordDialog ref="recordRef"></recordDialog>
    <reassignDialog ref="reassignRef" @success="reload"></reassignDialog>
  </view>
</template>

<script>
import {
  pageByCurrentUser,
  pageByCurrentUserLeader,
  pageByCurrentCurrentUserTeam,
  getNCtaskListData,
  taskManagement,
  listUpdateRealTimeRecord,
} from "@/api/pda/workReport.js";

import searchPopup from "../components/searchPopup.vue";
import reportDialog from "../components/reportDialog.vue";
import ncReportDialog from "../components/ncReportDialog.vue";
import recordDialog from "../components/recordDialog.vue";
import reassignDialog from "../components/reassignDialog.vue";

let isEnd = false;

export default {
  components: {
    searchPopup,
    reportDialog,
    ncReportDialog,
    recordDialog,
    reassignDialog,
  },
  data() {
    return {
      tabValue: "1",
      page: 1,
      size: 10,
      dataList: [],
      filterShow: false,
      searchFrom: {
        workOrderCode: "",
        teamName: "",
        productName: "",
        workTaskName: "",
        disposalStatus: "",
        status: "",
      },
    };
  },
  onShow() {
    if (!this.tabs.find((t) => t.value === this.tabValue)) {
      this.tabValue = this.tabs.length ? this.tabs[0].value : "1";
    }
    this.page = 1;
    this.getList();
  },
  computed: {
    tabs() {
      const list = [{ label: "我的任务", value: "1" }];
      if (this.$isAuthorities("mes:taskreport:allorder")) {
        list.push({ label: "全部任务", value: "2" });
      }
      if (this.$isAuthorities("mes:taskreport:teamorder")) {
        list.push({ label: "班组任务", value: "3" });
      }
      if (this.$isAuthorities("mes:taskreport:programmingorder")) {
        list.push({ label: "NC编程任务", value: "4" });
      }
      return list;
    },
  },
  methods: {
    back() {
      uni.navigateBack();
    },
    handleTabClick(val) {
      if (val === this.tabValue) return;
      this.tabValue = val;
      this.page = 1;
      this.dataList = [];
      this.getList();
    },
    doSearch() {
      this.page = 1;
      this.getList();
    },
    onFilterSearch(e) {
      this.searchFrom = { ...this.searchFrom, ...e };
      this.doSearch();
    },
    reload() {
      this.page = 1;
      this.getList();
    },
    scrolltolower() {
      if (isEnd) return;
      this.page++;
      this.getList();
    },
    async getList() {
      const params = {
        ...this.searchFrom,
        pageNum: this.page,
        size: this.size,
      };
      if (
        params.status !== undefined &&
        params.status !== null &&
        params.status !== "" &&
        this.tabValue !== "4"
      ) {
        params.status = params.status;
      }
      if (this.tabValue === "3") {
        const userInfo = uni.getStorageSync("userInfo") || {};
        params.teamIdsStr = userInfo.teamId || "";
      }
      Object.keys(params).forEach((k) => {
        if (params[k] === "" || params[k] === null || params[k] === undefined) {
          delete params[k];
        }
      });

      const api =
        this.tabValue === "1"
          ? pageByCurrentUser
          : this.tabValue === "2"
            ? pageByCurrentUserLeader
            : this.tabValue === "3"
              ? pageByCurrentCurrentUserTeam
              : getNCtaskListData;

      isEnd = false;
      try {
        const res = await api(params);
        if (!res) return;
        if (this.page === 1) this.dataList = [];
        const list = res.list || [];
        this.dataList.push(...list);

        // 判断是否到底：优先用 total/count，否则看本次返回数量是否小于 pageSize
        if (res.total !== undefined || res.count !== undefined) {
          const total = res.total || res.count;
          isEnd = this.dataList.length >= total;
        } else {
          isEnd = list.length < this.size;
        }
      } catch (err) {
        uni.showToast({ title: err.message || "加载失败", icon: "none" });
      }
    },

    /* 卡片操作的可见性条件（与 PC 端保持一致） */
    canAcceptReject(row) {
      const result =
        row.disposalStatus != "1" &&
        row.disposalStatus != "2" &&
        this.tabValue !== "2" &&
        this.tabValue !== "4";
      return result;
    },
    canReport(row) {
      if (this.tabValue === "4") {
        return !row.status || row.status.code != 5;
      }
      const noInspect =
        row.disposalStatus == "1" && row.hasFirstArticleDualInspection == "0";
      const inspectDone =
        row.disposalStatus == "1" &&
        row.totalFirstArticleDualInspectionStatus == 2 &&
        row.hasFirstArticleDualInspection == "1";
      return noInspect || inspectDone;
    },

    disposalText(s) {
      if (s == 0) return "待接收";
      if (s == 1) return "已接收";
      if (s == 2) return "已拒绝";
      return "";
    },
    disposalCls(s) {
      if (s == 0) return "tag-warn";
      if (s == 1) return "tag-success";
      if (s == 2) return "tag-danger";
      return "";
    },

    async receiveTask(id, type) {
      try {
        const res = await taskManagement({ id, disposalStatus: Number(type) });
        console.log("[receiveTask] api success", res);
        uni.showToast({
          title: type === "1" ? "已接收" : "已拒绝",
          icon: "success",
        });
        this.reload();
      } catch (err) {
        console.error("[receiveTask] api error", err);
        uni.showToast({
          title: err.message || err || "操作失败",
          icon: "none",
        });
      }
    },

    reassignTask(row) {
      this.$refs.reassignRef.open(row);
    },

    viewRecords(apsAssigneeId) {
      listUpdateRealTimeRecord(apsAssigneeId)
        .then((res) => {
          if (res && res.length > 0) {
            this.$refs.recordRef.open(res);
          } else {
            uni.showToast({ title: "暂无修改历史记录数据", icon: "none" });
          }
        })
        .catch((err) => {
          uni.showToast({ title: err.message || "加载失败", icon: "none" });
        });
    },

    /* 跳转报工/详情/NC */
    details(type, row) {
      if (this.tabValue === "4") {
        if (type === "detail") {
          this.$refs.ncReportRef.open(
            JSON.parse(JSON.stringify(row)),
            "detail",
          );
          return;
        }
        const data = {
          realStartTime: "",
          realEndTime: "",
          brandNum: row.brandNum,
          categoryName: row.categoryName,
          categoryCode: row.categoryCode,
          code: row.code,
          productionPlanCode: row.productionPlanCode,
          produceRoutingName: row.produceRoutingName,
          taskName: row.taskName,
          modelType: row.modelType,
          specification: row.specification,
          fileParam: [],
          reportRemark: row.reportRemark,
          id: row.id,
          sourceTaskId: row.sourceTaskId,
        };
        this.$refs.ncReportRef.open(data);
        return;
      }

      const currentRow = {
        assignCode: row.assignCode,
        mesWorkOrderCode: row.mesWorkOrderCode,
        workOrderCode: row.workOrderCode,
        workOrderId: row.workOrderId,
        productionPlanCode: row.productionPlanCode,
        produceRoutingName: row.produceRoutingName,
        formingNum: row.formingNum,
        assignTeamName: row.assignTeamName,
        formingWeight: row.formingWeight,
        planStartTime: row.planStartTime,
        planCompleteTime: row.planCompleteTime,
        startTime: row.startTime,
        firstTaskId: row.firstTaskId,
        endTime: row.endTime,
        taskName: row.taskName,
        firstTaskName: row.firstTaskName,
        assigneeType: row.assigneeType ? row.assigneeType.desc : "",
        assigneeName: row.assigneeName,
        weight: row.weight,
        quantity: row.quantity,
        durationText: row.durationText,
        apsAssigneeId: row.id,
        batchNo: row.batchNo,
        productCode: row.productCode,
        productName: row.productName,
        specification: row.specification,
        newWeightUnit: row.newWeightUnit,
        measuringUnit: row.measuringUnit,
        reportQuantityReported: row.reportQuantity || 0,
        lossQuantityReported: row.lossQuantity || 0,
      };

      const taskQuantity = Number(row.quantity) || 0;
      const actualQuantity = this.add(
        row.reportQuantity ? row.reportQuantity : 0,
        row.lossQuantity ? row.lossQuantity : 0,
      );
      const remaining = Math.max(this.sub(taskQuantity, actualQuantity), 0);
      const form = {
        realEndTime: row.realEndTime,
        realStartTime: row.realStartTime,
        remark: row.assigneeRemark,
        reportQuantity: row.reportQuantity ? remaining : taskQuantity,
        lossQuantity: 0,
        workOrderCode: row.workOrderCode,
        workOrderId: row.workOrderId,
        taskId: row.taskId,
      };

      this.$refs.reportRef.open(type, currentRow, form);
    },

    getDecimalLength(num) {
      return (num.toString().split(".")[1] || "").length;
    },
    toInteger(num) {
      const len = this.getDecimalLength(num);
      return {
        int: Math.round(num * Math.pow(10, len)),
        factor: Math.pow(10, len),
      };
    },
    add(a, b) {
      const { int: aInt, factor: aFactor } = this.toInteger(a);
      const { int: bInt, factor: bFactor } = this.toInteger(b);
      const maxFactor = Math.max(aFactor, bFactor);
      return (
        (aInt * (maxFactor / aFactor) + bInt * (maxFactor / bFactor)) /
        maxFactor
      );
    },
    sub(a, b) {
      const { int: aInt, factor: aFactor } = this.toInteger(a);
      const { int: bInt, factor: bFactor } = this.toInteger(b);
      const maxFactor = Math.max(aFactor, bFactor);
      return (
        (aInt * (maxFactor / aFactor) - bInt * (maxFactor / bFactor)) /
        maxFactor
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.content-box {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: $page-bg;
}

.tabs_wrap {
  display: flex;
  background: #fff;
  border-bottom: 1rpx solid #eee;
  .tab_item {
    flex: 1;
    text-align: center;
    padding: 22rpx 0;
    font-size: 28rpx;
    color: #666;
    position: relative;
    &.active {
      color: $theme-color;
      font-weight: 600;
      &::after {
        content: "";
        position: absolute;
        left: 50%;
        bottom: 0;
        transform: translateX(-50%);
        width: 60rpx;
        height: 4rpx;
        background: $theme-color;
        border-radius: 2rpx;
      }
    }
  }
}

.top-wrapper {
  background: #fff;
  display: flex;
  align-items: center;
  padding: 20rpx 26rpx;
  gap: 20rpx;
  box-sizing: border-box;
  .search_btn {
    padding: 0 26rpx;
    height: 64rpx;
    line-height: 64rpx;
    background: $theme-color;
    color: #fff;
    border-radius: 8rpx;
    font-size: 26rpx;
    white-space: nowrap;
  }
}

.list_box {
  // flex: 1;
  min-height: 0;
  overflow: hidden;
  padding: 16rpx 0;
  display: flex;
  flex-direction: column;

  /deep/ .u-list {
    flex: 1;
    height: 0 !important;
    min-height: 0;
    padding: 20rpx;
  }

  .card_box {
    width: 100%;
    padding: 24rpx 28rpx;
    box-sizing: border-box;
    border-bottom: 2rpx solid #f0f0f0;
    background: #fff;
    border-radius: 12rpx;
    margin-bottom: 16rpx;

    .item_box {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      margin-top: 14rpx;

      .round {
        width: 46rpx;
        height: 46rpx;
        line-height: 46rpx;
        border-radius: 50%;
        background: $theme-color;
        color: #fff;
        font-size: 24rpx;
        text-align: center;
        margin-right: 16rpx;
        flex-shrink: 0;
      }

      .item_one {
        width: 100%;
        display: flex;
        font-size: 26rpx;
        line-height: 44rpx;
        color: #333;
        word-wrap: break-word;
        .lable {
          color: #666;
          margin-right: 8rpx;
          flex-shrink: 0;
        }
        .val {
          flex: 1;
          word-break: break-all;
        }
      }
      .perce50 {
        width: 48%;
      }
      .perce100 {
        width: 100%;
      }
    }

    .tag {
      display: inline-block;
      padding: 0 12rpx;
      height: 36rpx;
      line-height: 36rpx;
      font-size: 22rpx;
      border-radius: 4rpx;
      margin-right: 8rpx;
      background: #f0f0f0;
      color: #555;
      &.tag-warn {
        background: #fff7e6;
        color: #fa8c16;
      }
      &.tag-success {
        background: #e6f6ec;
        color: $theme-color;
      }
      &.tag-danger {
        background: #ffece8;
        color: #f5222d;
      }
      &.tag-default {
        background: #f0f0f0;
        color: #555;
      }
    }

    .action_row {
      display: flex;
      flex-wrap: wrap;
      gap: 14rpx;
      margin-top: 20rpx;
      padding-top: 14rpx;
      border-top: 1rpx dashed #eee;
      .op_btn {
        height: 56rpx;
        line-height: 56rpx;
        padding: 0 22rpx;
        border-radius: 6rpx;
        font-size: 24rpx;
        margin: 0;
      }
      .primary {
        background: $theme-color;
        color: #fff;
      }
      .warn {
        background: #fff;
        color: #fa8c16;
        border: 1rpx solid #fa8c16;
      }
      .ghost {
        background: #fff;
        color: $theme-color;
        border: 1rpx solid $theme-color;
      }
    }
  }
}
</style>
