<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="list_box">
      <u-list @scrolltolower="() => {}" key="list">
        <u-list-item v-for="(item, index) in poList" :key="index">
          <view class="card_box">
            <view class="header rx-sc">
              <view
                class="checkbox-wrap"
                v-if="item.disposalStatus !== 2 && showBtn"
                @click.stop="toggleCheck(item)"
              >
                <u-checkbox-group>
                  <u-checkbox
                    :checked="isChecked(item)"
                    shape="square"
                    size="36rpx"
                    activeColor="#157A2C"
                    @change="toggleCheck(item)"
                  ></u-checkbox>
                </u-checkbox-group>
              </view>
              <view class="round">{{ index + 1 }}</view>
              <view class="orderId">{{ item.categoryName }}</view>
              <view
                class="status-tag"
                :class="'status-' + (item.disposalStatus || 0)"
              >
                {{ disposalStatusMap[item.disposalStatus || 0] }}
              </view>
            </view>

            <view class="row">
              <view class="label">样品编码</view>
              <view class="value">{{ item.sampleCode }}</view>
            </view>
            <view class="row">
              <view class="label">物品编码</view>
              <view class="value">{{ item.categoryCode }}</view>
            </view>
            <view class="row">
              <view class="label">规格</view>
              <view class="value">{{ item.specification }}</view>
            </view>
            <view class="row">
              <view class="label">牌号</view>
              <view class="value">{{ item.brandNum }}</view>
            </view>
            <view class="row">
              <view class="label">型号</view>
              <view class="value">{{ item.modelType }}</view>
            </view>
            <view class="row">
              <view class="label">批次号</view>
              <view class="value">{{ item.batchNo }}</view>
            </view>
            <view class="row">
              <view class="label">计量数量</view>
              <view class="value"
                >{{ item.measureQuantity }}{{ item.measureUnit }}</view
              >
            </view>
            <view class="row">
              <view class="label">不良类型</view>
              <view class="value">{{ item.badTypeName }}</view>
            </view>
            <view class="row">
              <view class="label">不良名称</view>
              <view class="value">{{ item.badNameName }}</view>
            </view>
            <view class="row">
              <view class="label">原因类型</view>
              <view class="value">{{ item.reasonTypeName }}</view>
            </view>
            <view class="row">
              <view class="label">原因</view>
              <view class="value">{{ item.unqualifiedReason }}</view>
            </view>
            <view class="row" v-if="item.disposeType">
              <view class="label">处置类型</view>
              <view class="value">{{
                getDisposeTypeName(item.disposeType)
              }}</view>
            </view>
            <view class="row" v-if="item.disposeTime">
              <view class="label">处置时间</view>
              <view class="value">{{ item.disposeTime }}</view>
            </view>

            <view class="btn-row" v-if="item.disposalStatus !== 2 && showBtn">
              <button class="btn-dispose" @click="disposeFn(2, item)">
                处置
              </button>
              <button class="btn-delete" @click="confirmDelete(item)">
                删除
              </button>
            </view>
          </view>
        </u-list-item>

        <u-list-item v-if="poList.length === 0 && !loading">
          <view style="margin-top: 20vh">
            <u-empty iconSize="150" textSize="32" text="暂无明细数据">
            </u-empty>
          </view>
        </u-list-item>
      </u-list>
    </view>

    <!-- 底部批量操作栏 -->
    <view class="footer-bar" v-if="showBtn">
      <view class="footer-left" @click="toggleSelectAll">
        <u-checkbox-group>
          <u-checkbox
            :checked="isAllChecked"
            shape="square"
            size="36rpx"
            activeColor="#157A2C"
            @change="toggleSelectAll"
          ></u-checkbox>
        </u-checkbox-group>
        <text class="select-all-text">全选</text>
      </view>
      <button
        class="btn-batch"
        :disabled="selection.length === 0"
        @click="disposeFn(1)"
      >
        批量处置{{ selection.length > 0 ? "(" + selection.length + ")" : "" }}
      </button>
    </view>

    <!-- 处置弹窗 -->
    <u-popup
      :show="dialogVisible"
      mode="bottom"
      round="24"
      @close="closeDialog"
    >
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">处置</text>
          <text class="popup-close" @click="closeDialog">✕</text>
        </view>

        <!-- 处置方式 -->
        <view class="form-item">
          <view class="form-label required">处置方式</view>
          <view class="picker-box" @click="showDisposePicker = true">
            <text :class="{ placeholder: !disposeForm.disposeType }">
              {{ disposeTypeName || "请选择处置方式" }}
            </text>
            <text class="arrow">▸</text>
          </view>
        </view>

        <!-- 回流工序 (返工=1/返修=2) -->
        <template
          v-if="disposeForm.disposeType == 1 || disposeForm.disposeType == 2"
        >
          <view class="form-item">
            <view class="form-label">回流工序</view>
            <view class="picker-box" @click="showRefluxPicker = true">
              <text :class="{ placeholder: !disposeForm.taskId }">
                {{ refluxTaskName || "请选择回流工序" }}
              </text>
              <text class="arrow">▸</text>
            </view>
          </view>
        </template>

        <!-- 留样字段 (disposeType=6) -->
        <template v-if="disposeForm.disposeType == 6">
          <view class="form-item">
            <view class="form-label">留样数量</view>
            <view class="input-box">
              <input
                type="digit"
                v-model="disposeForm.keepSampleQuantity"
                placeholder="请输入留样数量"
              />
              <text class="unit" v-if="current && current.measureUnit">{{
                current.measureUnit
              }}</text>
            </view>
          </view>
          <view class="form-item">
            <view class="form-label">留样日期</view>
            <view class="picker-box" @click="showDatePicker = true">
              <text :class="{ placeholder: !disposeForm.sampleDate }">
                {{ disposeForm.sampleDate || "请选择日期" }}
              </text>
              <text class="arrow">▸</text>
            </view>
          </view>
          <view class="form-item">
            <view class="form-label">留样条件</view>
            <view class="input-box">
              <input
                v-model="disposeForm.sampleCondition"
                placeholder="请输入留样条件"
              />
            </view>
          </view>
          <view class="form-item">
            <view class="form-label">生产商/受托生产</view>
            <view class="input-box">
              <input
                v-model="disposeForm.producerManufacturer"
                placeholder="请输入"
              />
            </view>
          </view>
          <view class="form-item">
            <view class="form-label">留样地点</view>
            <view class="input-box">
              <textarea
                v-model="disposeForm.samplePlace"
                placeholder="请输入留样地点"
                :auto-height="true"
              />
            </view>
          </view>
          <view class="form-item">
            <view class="form-label">留样备注</view>
            <view class="input-box">
              <textarea
                v-model="disposeForm.sampleRemark"
                placeholder="请输入留样备注"
                :auto-height="true"
              />
            </view>
          </view>
        </template>

        <!-- 入库仓库 (报废=3/留样=6/转试销=9) -->
        <template
          v-if="
            disposeForm.disposeType == 3 ||
            disposeForm.disposeType == 6 ||
            disposeForm.disposeType == 9
          "
        >
          <view class="form-item">
            <view
              class="form-label"
              :class="{ required: disposeForm.disposeType != 6 }"
              >入库仓库</view
            >
            <view class="picker-box" @click="showWarehousePicker = true">
              <text :class="{ placeholder: !disposeForm.depotId }">
                {{ disposeForm.depotName || "请选择仓库" }}
              </text>
              <text class="arrow">▸</text>
            </view>
          </view>
        </template>

        <view class="popup-footer">
          <button class="btn-cancel" @click="closeDialog">取消</button>
          <button class="btn-confirm" @click="handleDispose">确定</button>
        </view>
      </view>
    </u-popup>

    <!-- 处置方式选择器 -->
    <u-picker
      :show="showDisposePicker"
      :columns="[disposePickerColumns]"
      keyName="label"
      @confirm="onDisposeConfirm"
      @cancel="showDisposePicker = false"
      @close="showDisposePicker = false"
    ></u-picker>

    <!-- 回流工序选择器 -->
    <u-picker
      :show="showRefluxPicker"
      :columns="[refluxPickerColumns]"
      keyName="taskTypeName"
      @confirm="onRefluxConfirm"
      @cancel="showRefluxPicker = false"
      @close="showRefluxPicker = false"
    ></u-picker>

    <!-- 仓库选择器 -->
    <u-picker
      :show="showWarehousePicker"
      :columns="[warehousePickerColumns]"
      keyName="name"
      @confirm="onWarehouseConfirm"
      @cancel="showWarehousePicker = false"
      @close="showWarehousePicker = false"
    ></u-picker>

    <!-- 日期选择器 -->
    <u-datetime-picker
      :show="showDatePicker"
      mode="date"
      @confirm="onDateConfirm"
      @cancel="showDatePicker = false"
      @close="showDatePicker = false"
    ></u-datetime-picker>
  </view>
</template>

<script>
import {
  getById,
  disposeApi,
  refluxTask,
  getWarehouseList,
  deleteUnacceptedProductDetail,
} from "@/api/pda/nonconforming.js";

export default {
  data() {
    return {
      id: "",
      qualityType: null,
      workOrderCode: "",
      viewType: "",
      loading: false,
      poList: [],
      selection: [],

      dialogVisible: false,
      isBatch: false,
      current: null,

      disposeForm: {
        disposeType: "",
        sampleCondition: "",
        sampleDate: "",
        samplePlace: "",
        sampleRemark: "",
        producerManufacturer: "",
        depotId: "",
        depotName: "",
        taskId: "",
        keepSampleQuantity: "",
      },

      allList: [
        { value: 1, label: "返工" },
        { value: 2, label: "返修" },
        { value: 3, label: "报废" },
        { value: 4, label: "降级使用" },
        { value: 5, label: "让步接收" },
        { value: 6, label: "留样" },
        { value: 7, label: "消耗" },
        { value: 8, label: "回用/归批" },
        { value: 9, label: "转试销" },
        { value: 10, label: "退货" },
      ],

      warehouseList: [],
      refluxTaskList: [],

      showDisposePicker: false,
      showRefluxPicker: false,
      showWarehousePicker: false,
      showDatePicker: false,

      disposalStatusMap: { 0: "待处置", 1: "处置中", 2: "处置完成" },
    };
  },

  computed: {
    showBtn() {
      return this.viewType !== "detail";
    },
    canDisposeList() {
      return this.poList.filter((item) => item.disposalStatus !== 2);
    },
    isAllChecked() {
      return (
        this.canDisposeList.length > 0 &&
        this.selection.length === this.canDisposeList.length
      );
    },
    disposeList() {
      if (this.qualityType == 1) {
        return this.allList.filter((item) => [5, 10].includes(item.value));
      }
      if (this.qualityType == 3) {
        return this.allList.filter(
          (item) => item.value !== 8 && item.value !== 10,
        );
      }
      if (this.qualityType == 2) {
        return this.allList.filter((item) => item.value !== 8);
      }
      return this.allList;
    },
    disposePickerColumns() {
      return this.disposeList;
    },
    refluxPickerColumns() {
      return this.refluxTaskList;
    },
    warehousePickerColumns() {
      return this.warehouseList;
    },
    disposeTypeName() {
      const found = this.allList.find(
        (item) => item.value == this.disposeForm.disposeType,
      );
      return found ? found.label : "";
    },
    refluxTaskName() {
      const found = this.refluxTaskList.find(
        (item) => item.taskId == this.disposeForm.taskId,
      );
      return found ? found.taskTypeName : "";
    },
  },

  onLoad(option) {
    this.id = option.id;
    this.qualityType = option.qualityType;
    this.workOrderCode = option.workOrderCode || "";
    this.viewType = option.type || "";
  },

  onShow() {
    this.loadData();
  },

  methods: {
    back() {
      uni.navigateBack();
    },

    async loadData() {
      this.loading = true;
      this.selection = [];
      try {
        const res = await getById(this.id);
        this.poList = res.poList || [];
        if (this.workOrderCode) {
          this.getRefluxTask();
        }
        this.loadWarehouse();
      } catch (e) {
        uni.showToast({ title: "加载失败", icon: "none" });
      } finally {
        this.loading = false;
      }
    },

    async loadWarehouse() {
      try {
        this.warehouseList = await getWarehouseList();
      } catch (e) {
        this.warehouseList = [];
      }
    },

    async getRefluxTask() {
      try {
        const res = await refluxTask({ workOrderCode: this.workOrderCode });
        this.refluxTaskList = res || [];
      } catch (e) {
        this.refluxTaskList = [];
      }
    },

    getDisposeTypeName(val) {
      const found = this.allList.find((item) => item.value == val);
      return found ? found.label : "";
    },

    isChecked(item) {
      return this.selection.some((s) => s.id === item.id);
    },

    toggleCheck(item) {
      const idx = this.selection.findIndex((s) => s.id === item.id);
      if (idx > -1) {
        this.selection.splice(idx, 1);
      } else {
        this.selection.push(item);
      }
    },

    toggleSelectAll() {
      if (this.isAllChecked) {
        this.selection = [];
      } else {
        this.selection = [...this.canDisposeList];
      }
    },

    disposeFn(type, row) {
      if (type == 1) {
        if (this.selection.length === 0) {
          uni.showToast({ title: "请先勾选需要处置的数据", icon: "none" });
          return;
        }
        this.isBatch = true;
      } else {
        this.isBatch = false;
        this.current = row;
      }
      this.resetDisposeForm();
      this.dialogVisible = true;
    },

    resetDisposeForm() {
      this.disposeForm = {
        disposeType: "",
        sampleCondition: "",
        sampleDate: "",
        samplePlace: "",
        sampleRemark: "",
        producerManufacturer: "",
        depotId: "",
        depotName: "",
        taskId: "",
        keepSampleQuantity: "",
      };
    },

    closeDialog() {
      this.dialogVisible = false;
      this.isBatch = false;
      this.current = null;
      this.resetDisposeForm();
    },

    onDisposeConfirm(e) {
      const item = e.value[0];
      this.disposeForm.disposeType = item.value;
      this.showDisposePicker = false;
      this.disposeForm.sampleCondition = "";
      this.disposeForm.sampleDate = "";
      this.disposeForm.samplePlace = "";
      this.disposeForm.sampleRemark = "";
      this.disposeForm.producerManufacturer = "";
      this.disposeForm.depotId = "";
      this.disposeForm.depotName = "";
      this.disposeForm.taskId = "";
      if (item.value == 6 && this.current) {
        this.disposeForm.keepSampleQuantity =
          this.current.measureQuantity || "";
      }
    },

    onRefluxConfirm(e) {
      const item = e.value[0];
      this.disposeForm.taskId = item.taskId;
      this.showRefluxPicker = false;
    },

    onWarehouseConfirm(e) {
      const item = e.value[0];
      this.disposeForm.depotId = item.id;
      this.disposeForm.depotName = item.name;
      this.showWarehousePicker = false;
    },

    onDateConfirm(e) {
      const d = new Date(e.value);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, "0");
      const day = String(d.getDate()).padStart(2, "0");
      this.disposeForm.sampleDate = `${year}-${month}-${day}`;
      this.showDatePicker = false;
    },

    async handleDispose() {
      if (!this.disposeForm.disposeType) {
        uni.showToast({ title: "请选择处置方式", icon: "none" });
        return;
      }

      const dt = this.disposeForm.disposeType;
      if ((dt == 3 || dt == 9) && !this.disposeForm.depotId) {
        uni.showToast({ title: "请选择入库仓库", icon: "none" });
        return;
      }

      if (dt == 6 && this.current) {
        const inputVal = Number(this.disposeForm.keepSampleQuantity);
        const maxVal = Number(this.current.measureQuantity);
        if (inputVal > maxVal) {
          uni.showToast({
            title: `留样数量不能超过${maxVal}`,
            icon: "none",
          });
          return;
        }
      }

      let params = {
        disposeType: this.disposeForm.disposeType,
        poList: [],
        refluxTask: null,
      };

      if (this.isBatch) {
        params.poList = this.selection.map((item) => {
          return { ...item, ...this.disposeForm };
        });
      } else {
        params.poList = [
          { ...JSON.parse(JSON.stringify(this.current)), ...this.disposeForm },
        ];
      }

      if (this.disposeForm.taskId) {
        params.refluxTask = this.refluxTaskList.find(
          (item) => item.taskId == this.disposeForm.taskId,
        );
      }

      try {
        await disposeApi(params);
        uni.showToast({ title: "处置成功", icon: "success" });
        this.closeDialog();
        this.loadData();
      } catch (e) {
        uni.showToast({ title: e || "处置失败", icon: "none" });
      }
    },

    confirmDelete(item) {
      uni.showModal({
        title: "提示",
        content: "确定要删除吗？",
        success: (res) => {
          if (res.confirm) {
            this.removeItem(item);
          }
        },
      });
    },

    async removeItem(item) {
      try {
        await deleteUnacceptedProductDetail([item.id]);
        uni.showToast({ title: "删除成功", icon: "success" });
        this.loadData();
      } catch (e) {
        uni.showToast({ title: e || "删除失败", icon: "none" });
      }
    },
  },
};
</script>

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

.list_box {
  overflow: hidden;
  padding: 16rpx 0;
  padding-bottom: 120rpx;

  .u-list {
    height: 100% !important;
  }

  .card_box {
    width: 686rpx;
    margin: 0 auto 24rpx;
    background: #fff;
    border-radius: 18rpx;
    padding: 26rpx 30rpx;
    box-shadow: 0 6rpx 28rpx rgba(0, 0, 0, 0.06);
    box-sizing: border-box;

    .header {
      display: flex;
      align-items: center;
      margin-bottom: 18rpx;

      .round {
        width: 40rpx;
        height: 40rpx;
        line-height: 40rpx;
        border-radius: 50%;
        background: $theme-color;
        color: #fff;
        text-align: center;
        font-size: 22rpx;
      }

      .checkbox-wrap {
        margin-right: 12rpx;
        display: flex;
        align-items: center;
      }

      .orderId {
        margin-left: 14rpx;
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
        flex: 1;
      }

      .status-tag {
        font-size: 22rpx;
        padding: 6rpx 18rpx;
        border-radius: 32rpx;
        font-weight: 500;
      }

      .status-0 {
        background: #fff3e0;
        color: #e67e22;
      }
      .status-1 {
        background: #eaf3ff;
        color: #2a68ff;
      }
      .status-2 {
        background: #e8f6ec;
        color: #157a2c;
      }
    }

    .row {
      display: flex;
      justify-content: space-between;
      margin-bottom: 12rpx;
      font-size: 26rpx;
      color: #333;

      .label {
        color: #888;
        min-width: 160rpx;
        font-weight: 400;
      }

      .value {
        flex: 1;
        font-weight: 500;
        text-align: right;
        word-break: break-all;
      }
    }

    .btn-row {
      display: flex;
      justify-content: flex-end;
      gap: 20rpx;
      margin-top: 20rpx;
      padding-top: 20rpx;
      border-top: 1rpx solid #f0f0f0;

      button {
        font-size: 26rpx;
        padding: 10rpx 36rpx;
        border-radius: 32rpx;
        line-height: 1.6;
        margin: 0;
      }

      .btn-dispose {
        background: $theme-color;
        color: #fff;
      }

      .btn-delete {
        background: #fff;
        color: #e74c3c;
        border: 1rpx solid #e74c3c;
      }
    }
  }
}

.footer-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 20rpx 32rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  background: #fff;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.06);
  z-index: 100;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  gap: 24rpx;

  .footer-left {
    display: flex;
    align-items: center;
    gap: 8rpx;

    .select-all-text {
      font-size: 28rpx;
      color: #333;
    }
  }

  .btn-batch {
    flex: 1;
    height: 80rpx;
    line-height: 80rpx;
    background: $theme-color;
    color: #fff;
    font-size: 30rpx;
    border-radius: 40rpx;
    margin: 0;

    &[disabled] {
      opacity: 0.5;
    }
  }
}

.popup-content {
  padding: 32rpx;
  max-height: 80vh;
  overflow-y: auto;

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 32rpx;

    .popup-title {
      font-size: 34rpx;
      font-weight: 600;
      color: #333;
    }

    .popup-close {
      font-size: 36rpx;
      color: #999;
      padding: 10rpx;
    }
  }

  .form-item {
    margin-bottom: 28rpx;

    .form-label {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 12rpx;
      font-weight: 500;

      &.required::before {
        content: "*";
        color: #e74c3c;
        margin-right: 6rpx;
      }
    }

    .picker-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 80rpx;
      padding: 0 24rpx;
      background: #f8f8f8;
      border-radius: 12rpx;
      font-size: 28rpx;
      color: #333;

      .placeholder {
        color: #bbb;
      }

      .arrow {
        color: #ccc;
        font-size: 28rpx;
      }
    }

    .input-box {
      display: flex;
      align-items: center;
      background: #f8f8f8;
      border-radius: 12rpx;
      padding: 0 24rpx;
      min-height: 80rpx;

      input {
        flex: 1;
        height: 80rpx;
        font-size: 28rpx;
        color: #333;
      }

      textarea {
        flex: 1;
        font-size: 28rpx;
        color: #333;
        padding: 20rpx 0;
        min-height: 80rpx;
      }

      .unit {
        color: #888;
        font-size: 26rpx;
        margin-left: 12rpx;
      }
    }
  }

  .popup-footer {
    display: flex;
    gap: 24rpx;
    margin-top: 40rpx;
    padding-bottom: env(safe-area-inset-bottom);

    button {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      font-size: 30rpx;
      border-radius: 40rpx;
      margin: 0;
    }

    .btn-cancel {
      background: #f5f5f5;
      color: #666;
    }

    .btn-confirm {
      background: $theme-color;
      color: #fff;
    }
  }
}
</style>
