<!-- 样品列表页面 -->
<template>
  <view class="mainBox">
    <uni-nav-bar
      fixed="true"
      statusBar="true"
      left-icon="back"
      :title="title"
      @clickLeft="handleClose"
    >
    </uni-nav-bar>

    <!-- <view class="nav-placeholder"></view> -->

    <view class="wrapper">
      <scroll-view class="scroll-wrapper" scroll-y>
        <view class="sample-list">
          <view
            class="sample-item"
            v-for="(sample, sampleIndex) in projectId
              ? tableData.filter((item) => item.id == projectId)
              : tableData"
            :key="sampleIndex"
          >
            <view class="sample-header" @click="toggleExpand(sampleIndex)">
              <view class="sample-info">
                <view class="info-row">
                  <text class="label">编码:</text>
                  <text class="value">{{ sample.categoryCode }}</text>
                </view>
                <view class="info-row">
                  <text class="label">名称:</text>
                  <text class="value">{{ sample.categoryName }}</text>
                </view>
                <view class="info-row" v-if="sample.batchNo">
                  <text class="label">批次号:</text>
                  <text class="value">{{ sample.batchNo }}</text>
                </view>
                <view class="info-row" v-if="sample.packageNo">
                  <text class="label">包装编码:</text>
                  <text class="value">{{ sample.packageNo }}</text>
                </view>
              </view>
              <view
                class="expand-arrow"
                :class="{ expanded: expandedItems[sampleIndex] }"
                >›</view
              >
            </view>

            <view
              class="quality-table-wrapper"
              v-if="expandedItems[sampleIndex]"
            >
              <scroll-view class="quality-table-scroll" scroll-x>
                <view class="quality-table">
                  <view class="table-header">
                    <view class="table-cell">质检项名称</view>
                    <view class="table-cell">质检内容</view>
                    <view class="table-cell">质检结果</view>
                    <view class="table-cell">质检方案编码</view>
                    <view class="table-cell">质检方案名称</view>
                    <view class="table-cell">质检类型</view>
                    <view class="table-cell">工艺参数</view>
                  </view>
                  <view class="table-body">
                    <view
                      class="table-row"
                      v-for="(
                        quality, qualityIndex
                      ) in sample.qualitySampleTemplateList"
                      :key="qualityIndex"
                    >
                      <view class="table-cell">
                        <text
                          class="cell-text"
                          :class="{ warn: quality.qualityResults === 2 }"
                          >{{ quality.inspectionName }}</text
                        >
                      </view>
                      <view class="table-cell">
                        <u-input
                          v-model="quality.qualityResultContent"
                          placeholder="请输入"
                          border="none"
                          @change="
                            clientEnvironmentId == 10
                              ? newHandleInput(
                                  sample.qualitySampleTemplateList,
                                  sampleIndex,
                                )
                              : handleInput(
                                  quality,
                                  quality.qualityResultContent,
                                  tableData,
                                )
                          "
                          :class="{ warn: quality.qualityResults === 2 }"
                          :disabled="
                            type === 'detail' ||
                            ((!pageName || pageName == 'myList') &&
                              sample.correlationId)
                          "
                        >
                          <template #suffix v-if="quality.unitName">
                            <text class="unit">{{ quality.unitName }}</text>
                          </template>
                        </u-input>
                      </view>
                      <view
                        class="table-cell"
                        v-if="
                          ['炉水电导率', '给水电导率'].includes(
                            quality.inspectionName,
                          )
                        "
                      ></view>
                      <view class="table-cell" v-else>
                        <u-input
                          disabled
                          placeholder=" "
                          v-if="
                            type === 'detail' ||
                            ((!pageName || pageName == 'myList') &&
                              sample.correlationId)
                          "
                          border="surround"
                          :value="
                            quality.qualityResults &&
                            qualityResultsList.find(
                              (item) => item.value == quality.qualityResults,
                            ).text
                          "
                        >
                        </u-input>
                        <uni-data-picker
                          v-else
                          v-model="quality.qualityResults"
                          placeholder="请选择"
                          :localdata="qualityResultsList"
                          @change="qualityResultsListChange(tableData)"
                          :clear-icon="false"
                        >
                        </uni-data-picker>
                      </view>
                      <view class="table-cell">
                        <text
                          class="cell-text"
                          :class="{ warn: quality.qualityResults === 2 }"
                          >{{ quality.qualitySchemeTemplateCode }}</text
                        >
                      </view>
                      <view class="table-cell">
                        <text
                          class="cell-text"
                          :class="{ warn: quality.qualityResults === 2 }"
                          >{{ quality.qualitySchemeTemplateName }}</text
                        >
                      </view>
                      <view class="table-cell">
                        <text
                          class="cell-text"
                          :class="{ warn: quality.qualityResults === 2 }"
                          >{{ quality.categoryLevelClassName }}</text
                        >
                      </view>
                      <view class="table-cell parameter-cell">
                        <text
                          class="cell-text"
                          :class="{ warn: quality.qualityResults === 2 }"
                        >
                          <text v-if="quality.textType == 3">
                            {{ quality.symbol }}
                            {{ quality.minValue }}-{{ quality.maxValue }}
                          </text>
                          <text v-else-if="quality.textType == 8">
                            标准值：{{ quality.defaultValue
                            }}{{ quality.unitName || "" }} 下限：{{
                              quality.minValue || 0
                            }}{{ quality.unitName || "" }} 上限：{{
                              quality.minValue || 0
                            }}{{ quality.unitName || "" }}
                          </text>
                          <text v-else>
                            {{ quality.symbol }} {{ quality.defaultValue }}
                          </text>
                          <text v-if="quality.textType != 8">
                            {{ quality.unitName }}</text
                          >
                        </text>
                      </view>
                    </view>
                  </view>
                </view>
              </scroll-view>
            </view>

            <view class="quality-summary" v-if="sample.qualityResults">
              <view style="min-width: 10px; margin-left: 16rpx">
                <text>
                  {{
                    sample.status == 1
                      ? "已检"
                      : sample.status == 2
                        ? "已派单"
                        : sample.status == 3
                          ? "已请托"
                          : "待检"
                  }}
                </text>
              </view>
              <view>
                <text class="summary-label">样品质检结果:</text>
                <text
                  class="summary-value"
                  :class="getQualityResultClass(sample.qualityResults)"
                >
                  {{ formatQualityResult(sample.qualityResults) }}
                </text>
              </view>
            </view>
          </view>

          <view class="empty-state" v-if="!tableData || tableData.length === 0">
            <text>暂无数据</text>
          </view>
        </view>
      </scroll-view>

      <view style="height: 84rpx"></view>
      <view class="footerButton">
        <u-button @click="handleClose" type="default" text="返回"></u-button>
        <u-button
          v-if="
            type != 'view' &&
            !isCorrelationId &&
            workData.status != 1 &&
            clientEnvironmentId != 10
          "
          type="primary"
          @click="save"
          text="保存"
        ></u-button>
        <u-button
          v-if="type != 'view' && !isCorrelationId && workData.status != 1"
          type="primary"
          @click="exeReportWork"
          text="报工"
        ></u-button>
      </view>
    </view>
    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
import {
  getById,
  update,
  queryQualityInventory,
  exeReportWork,
  getTaskmonadById,
} from "@/api/inspectionWork/index.js";
import { handleInput, qualityResultsListChange } from "./unit.js";
import dayjs from "dayjs";
export default {
  components: {},
  data() {
    return {
      title: "样品列表",
      rowIndex: 0,
      type: "",
      pageName: "",
      tableData: [],
      handleInput,
      qualityResultsListChange,
      isCorrelationId: false,
      expandedItems: {},
      workData: {},
      inventoryList: [],
      projectId: "",
      qualityResultsList: [
        {
          text: "合格",
          value: 1,
        },
        {
          text: "不合格",
          value: 2,
        },
        {
          text: "让步接收",
          value: 3,
        },
      ],
    };
  },
  onLoad(data) {
    if (data.workId) {
      this.projectId = data.projectId;
      this.type = data.type || "";
      this.pageName = data.pageName || "";
      this.clientEnvironmentId =
        uni.getStorageSync("userInfo").clientEnvironmentId;
      let api = [
        "myInspectionProjectEntrusted",
        "myInspectionProjectTask",
      ].includes(this.pageName)
        ? getTaskmonadById
        : getById;
      api(data.workId).then((res) => {
        this.workData = res;
        if (data.projectId) {
          const qualitySampleList = res.qualitySampleList.filter(
            (item) => item.id == data.projectId,
          );

          if (
            qualitySampleList[0].correlationId &&
            ![
              "myInspectionProjectEntrusted",
              "myInspectionProjectTask",
            ].includes(this.pageName)
          ) {
            this.isCorrelationId = true;
          } else {
            qualitySampleList[0].status = 1;
          }
        } else {
          this.isCorrelationId = true;
          res.qualitySampleList.forEach((item) => {
            if (
              !item.correlationId ||
              [
                "myInspectionProjectEntrusted",
                "myInspectionProjectTask",
              ].includes(this.pageName)
            ) {
              this.isCorrelationId = false;
              item.status = 1;
            }
          });
        }

        this.tableData = res.qualitySampleList.map((item) => {
          if (
            !item.qualitySampleTemplateList.length &&
            res.templateList.length
          ) {
            item.qualitySampleTemplateList = JSON.parse(
              JSON.stringify(res.templateList),
            );
          }

          return item;
        });
      });

      this.expandedItems = {};
      this.getQueryQualityInventory(data.workId);
    }
  },
  methods: {
    async getQueryQualityInventory(workId) {
      const res = await queryQualityInventory({
        qualityWorkerId: workId,
        size: -1,
      });

      if (res.list.length > 0) {
        this.inventoryList = res.list;
      }
    },
    handleClose() {
      uni.navigateBack();
    },

    handleConfirm() {
      this.tableData.forEach((item) => {
        if (!this.pageName && item.correlationId) {
          return;
        }
        item.status = 1;
      });

      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];
      if (prevPage) {
        prevPage.$vm.handleConfirm &&
          prevPage.$vm.handleConfirm(this.tableData, this.rowIndex);
      }

      uni.navigateBack();
    },

    toggleExpand(index) {
      this.$set(this.expandedItems, index, !this.expandedItems[index]);
    },
    setNum() {
      let sampleQualifiedNumber = 0; //  样品合格数
      let sampleNoQualifiedNumber = 0; //  样品不合格数
      let sampleQualificationRate = 0; //样品合格率
      let sampleNoQualificationRate = 0; //样品不合格率

      let qualifiedNumber = 0; // 合格数
      let noQualifiedNumber = 0; //  不合格数
      let qualificationRate = 0; //  合格率
      let noQualificationRate = 0; //不合格率

      this.tableData.forEach((item) => {
        if (item.qualityResults == 2) {
          sampleNoQualifiedNumber += item.measureQuantity;
        }
      });
      sampleQualifiedNumber =
        this.workData.sampleQuantity - sampleNoQualifiedNumber;

      sampleQualificationRate =
        ((sampleQualifiedNumber / this.workData.sampleQuantity) * 100).toFixed(
          2,
        ) || "";
      sampleNoQualificationRate =
        (
          (sampleNoQualifiedNumber / this.workData.sampleQuantity) *
          100
        ).toFixed(2) || "";
      if (this.workData.qualityMode == 2 && this.workData.qualityResults == 2) {
        qualifiedNumber = sampleQualifiedNumber;
        noQualifiedNumber = this.workData.total - sampleQualifiedNumber;
      } else {
        qualifiedNumber = this.workData.total - sampleNoQualifiedNumber;
        noQualifiedNumber = sampleNoQualifiedNumber;
      }

      qualificationRate =
        ((qualifiedNumber / this.workData.total) * 100).toFixed(2) || "";
      noQualificationRate =
        ((noQualifiedNumber / this.workData.total) * 100).toFixed(2) || "";
      this.workData.sampleQualifiedNumber = sampleQualifiedNumber;
      this.workData.sampleNoQualifiedNumber = sampleNoQualifiedNumber;
      this.workData.sampleQualificationRate = sampleQualificationRate;
      this.workData.sampleNoQualificationRate = sampleNoQualificationRate;
      this.workData.qualifiedNumber = qualifiedNumber;
      this.workData.noQualifiedNumber = noQualifiedNumber;
      this.workData.qualificationRate = qualificationRate;
      this.workData.noQualificationRate = noQualificationRate;
      // qualityMode
    },
    /* 保存编辑 */
    save() {
      this.workData.isUpdate = 1;
      this.setNum();
      let params = {
        ...this.workData,
        sampleList: this.tableData,
        planTemplateList: this.workData.templateList,
        templateList: this.workData.templateList,
        qualityInventoryList: this.inventoryList,
      };

      update(params)
        .then((msg) => {
          uni.$emit("successInit");
          this.back();
        })
        .catch((e) => {});
    },
    exeReportWork() {
      if (this.clientEnvironmentId == 10) {
        this.doExeReportWork();
      } else if (
        ["myInspectionProjectEntrusted", "myInspectionProjectTask"].includes(
          this.pageName,
        )
      ) {
        this.doExeReportWork();
      } else {
        uni.showActionSheet({
          itemList: ["合格", "不合格"],
          success: (res) => {
            this.workData.qualityResults = res.tapIndex === 0 ? 1 : 2;
            this.doExeReportWork();
          },
        });
      }
    },
    doExeReportWork() {
      this.workData.isUpdate = 1;
      this.tableData.qualityTimeEnd = dayjs().format("YYYY-MM-DD HH:mm:ss");
      this.workData.executeUserId = uni.getStorageSync("userInfo").userId;
      this.workData.executeUserName = uni.getStorageSync("userInfo").name;
      if (this.clientEnvironmentId == 10) {
        this.workData.qualityResults = this.tableData[0].qualityResults;
      }
      this.setNum();
      let params = {
        ...this.workData,
        sampleList: this.tableData,
        planTemplateList: this.workData.templateList,
        templateList: this.workData.templateList,
        qualityInventoryList: this.inventoryList,
      };

      exeReportWork(params)
        .then((msg) => {
          uni.$emit("successInit");
          this.back();
        })
        .catch((e) => {});
    },
    formatQualityResult(value) {
      const map = {
        1: "合格",
        2: "不合格",
        3: "让步接收",
      };
      return map[value] || "";
    },
    //宇信特殊处理
    newHandleInput(arr, index) {
      let num = arr.find(
        (item) => item.inspectionName == "炉水电导率",
      )?.qualityResultContent;
      let num1 = arr.find(
        (item) => item.inspectionName == "给水电导率",
      )?.qualityResultContent;
      console.log(num, num1);

      arr.forEach((item, i) => {
        if (num && num1 && item.inspectionName == "干度值") {
          let val = parseFloat((((num - num1 / 1000) / num) * 100).toFixed(5));
          this.$set(
            this.tableData[index].qualitySampleTemplateList[i],
            "qualityResultContent",
            val,
          );

          this.handleInput(item, val, this.tableData);
        }
      });
    },
    getQualityResultClass(value) {
      return {
        1: "result-pass",
        2: "result-fail",
        3: "result-concession",
      }[value];
    },
  },
};
</script>

<style lang="scss" scoped>
.mainBox {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f3f8fb;
}

.nav-placeholder {
  height: calc(var(--status-bar-height, 0px) + 44px);
}

.wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.scroll-wrapper {
  flex: 1;
  height: 0;
  padding: 20rpx;

  .sample-list {
    padding-bottom: 20rpx;

    .sample-item {
      background: #fff;
      border-radius: 30rpx;
      margin-bottom: 20rpx;
      overflow: hidden;
      //   box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
      //   border: 1rpx solid #f0f0f0;

      .quality-summary {
        padding: 24rpx;
        background: #fff;
        border-top: 1rpx solid #f5f3f3;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 28rpx;
        font-weight: bold;

        .summary-label {
          color: #333;
          margin-right: 20rpx;
        }

        .summary-value {
          padding: 8rpx 20rpx;
          border-radius: 8rpx;

          &.result-pass {
            color: #52c41a;
            background: #f6ffed;
          }

          &.result-fail {
            color: #ff4d4f;
            background: #fff2f0;
          }

          &.result-concession {
            color: #faad14;
            background: #fffbe6;
          }
        }
      }

      .empty-state {
        padding: 100rpx 0;
        text-align: center;
        font-size: 28rpx;
        color: #999;
      }

      .sample-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 40rpx 40rpx 20rpx 40rpx;
        background: #ffffff;
        box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);

        .sample-info {
          flex: 1;
        }

        .info-row {
          display: flex;
          margin-bottom: 8rpx;

          &:last-child {
            margin-bottom: 0;
          }

          .label {
            font-size: 28rpx;
            color: #333;

            font-weight: 800;

            margin-right: 10rpx;
            min-width: 120rpx;
          }

          .value {
            font-size: 26rpx;
            color: #333;
            flex: 1;
            font-weight: 800;
          }
        }

        .expand-arrow {
          font-size: 40rpx;
          color: #999;
          margin-left: 20rpx;
          transform: rotate(0deg);
          transition: transform 0.3s;
          background: #fff;
          width: 48rpx;
          height: 48rpx;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

          &.expanded {
            transform: rotate(90deg);
          }
        }
      }

      .quality-table-wrapper {
        // margin: 20rpx;
        margin-top: 0;
        // border-radius: 12rpx;
        overflow: hidden;
        // box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
      }

      // 自定义滚动条样式
      ::v-deep .quality-table-scroll ::-webkit-scrollbar {
        width: 6rpx;
        height: 6rpx;
      }

      ::v-deep .quality-table-scroll ::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 3rpx;
      }

      ::v-deep .quality-table-scroll ::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 3rpx;
      }

      ::v-deep .quality-table-scroll ::-webkit-scrollbar-thumb:hover {
        background: #a8a8a8;
      }

      ::v-deep .table-cell:last-child::-webkit-scrollbar {
        width: 4rpx;
      }

      ::v-deep .table-cell:last-child::-webkit-scrollbar-track {
        background: #f9f9f9;
        border-radius: 2rpx;
      }

      ::v-deep .table-cell:last-child::-webkit-scrollbar-thumb {
        background: #d9d9d9;
        border-radius: 2rpx;
      }

      .quality-table-scroll {
        width: 100%;
      }

      .quality-table {
        min-width: 100%;
        width: 1540rpx;
        background: #fff;
      }

      .table-header {
        display: flex;
        background: #f5f5f5;
        border-bottom: 2rpx solid #e5e5e5;

        .table-cell {
          padding: 24rpx 12rpx;
          font-size: 26rpx;
          font-weight: bold;
          color: #333;
          text-align: center;
          border-right: 1rpx solid #e5e5e5;
          white-space: nowrap;
          flex-shrink: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          background: #f5f5f5;
          width: 200rpx;

          &:last-child {
            border-right: none;
            background: #f5f5f5;
          }

          &:nth-child(2) {
            width: 260rpx;
          }

          &:nth-child(3) {
            width: 220rpx;
          }

          &:nth-child(7) {
            width: 260rpx;
          }
        }
      }

      .table-body {
        .table-row {
          display: flex;
          border-bottom: 1rpx solid #e5e5e5;
          transition: background 0.2s;

          &:nth-child(even) {
            // background: #fafafa;
          }

          &:last-child {
            border-bottom: none;
          }

          .table-cell {
            padding: 20rpx 12rpx;
            font-size: 24rpx;
            // color: #666;
            text-align: center;
            border-right: 1rpx solid #e5e5e5;
            white-space: nowrap;
            flex-shrink: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            width: 200rpx;

            &:last-child {
              border-right: none;
              //   background: #f5f5f5;
            }

            &:nth-child(2) {
              width: 260rpx;
            }

            &:nth-child(3) {
              width: 220rpx;
            }

            &:nth-child(7) {
              width: 260rpx !important;
            }

            .cell-text {
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              max-width: 100%;

              &.warn {
                color: #ff4d4f;
              }
            }

            .unit {
              font-size: 22rpx;
              color: #999;
              margin-left: 6rpx;
            }

            &.parameter-cell {
              max-height: 120rpx;
              overflow-y: auto;
              align-items: flex-start;
              padding: 16rpx 12rpx;
              width: 200rpx;
            }
          }
        }
      }
    }
  }
}

.footerButton {
  width: 100%;
  height: 84rpx;
  display: flex;
  position: fixed;
  bottom: 0;
  z-index: 10;
  background-color: #fff;

  /deep/.u-button {
    height: 100%;
  }

  > view {
    flex: 1;
  }
}

.warn {
  color: #ff4d4f !important;
}

/deep/.text-color {
  font-size: 28rpx;
}
</style>
