<template>
  <view class="page">
    <!-- 顶部标题栏 -->
    <uni-nav-bar
      fixed
      statusBar
      left-icon="back"
      title="新建领料单"
      background-color="#157A2C"
      color="#fff"
      @clickLeft="back"
    />

    <!-- 页面主体滚动区域 -->
    <scroll-view class="scroll-container" scroll-y="true" scroll-with-animation>
      <!-- 顶部表单 -->
      <view class="form-section">
        <view class="form-item">
          <text class="label">领料单编号</text>
          <uni-easyinput v-model="pickForm.pickCode" disabled />
        </view>
        <view class="form-item">
          <text class="label">领料单名称</text>
          <uni-easyinput
            v-model="pickForm.pickName"
            placeholder="请输入领料单名称"
          />
        </view>
        <view class="btn-add">
          <button type="primary" size="mini" @click="openPicking">
            添加物料
          </button>
        </view>
      </view>

      <!-- 物料列表 -->
      <view class="material-list">
        <view
          class="material-card"
          v-for="(mate, idx) in objPick.pickList"
          :key="idx"
        >
          <!-- 删除按钮 -->
          <view class="delete-btn" @click.stop="removeItem(idx)">
            <uni-icons
              custom-prefix="iconfont"
              type="icon-shanchu"
              size="28"
              color="#fa3534"
            />
          </view>

          <!-- 卡片内容 -->
          <view class="card-content">
            <view class="card-row">
              <text class="label">编码：</text>
              <text class="value">{{
                mate.rootCategoryLevelId == 4 ? mate.codeNumber : mate.code
              }}</text>
            </view>
            <view class="card-row">
              <text class="label">名称：</text>
              <text class="value">{{ mate.name }}</text>
            </view>
            <view class="card-row">
              <text class="label">类型：</text>
              <text class="value">{{
                typeName[Number(mate.rootCategoryLevelId)]
              }}</text>
            </view>
            <view class="card-row">
              <text class="label">库存数量：</text>
              <text class="value"
                >{{ mate.measureQuantity }} {{ mate.measuringUnit }}</text
              >
            </view>
            <view class="card-row">
              <text class="label">数量：</text>
              <view class="input-row">
                <uni-easyinput
                  v-model="mate.demandQuantity"
                  placeholder="请输入数量"
                  type="text"
                />
                <text class="unit">{{ mate.measuringUnit }}</text>
              </view>
            </view>
            <view class="card-row">
              <text class="label">型号：</text>
              <text class="value">{{ mate.modelType }}</text>
            </view>
            <view class="card-row">
              <text class="label">规格：</text>
              <text class="value">{{ mate.specification }}</text>
            </view>
            <view class="card-row">
              <text class="label">批次号：</text>
              <text class="value">{{ mate.batchNo }}</text>
            </view>
            <view class="card-row">
              <text class="label">牌号：</text>
              <text class="value">{{ mate.brandNum }}</text>
            </view>
            <view class="card-row">
              <text class="label">领料仓库：</text>
              <zxz-uni-data-select
                :localdata="mate.warehouseList"
                v-model="mate.warehouseId"
                dataValue="warehouse_id"
                format="{warehouse_name}"
                dataKey="warehouse_name"
                filterable
              />
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部操作按钮 -->
    <view class="footer-btn">
      <button @click="close" size="mini">取消</button>
      <button type="primary" @click="save" size="mini">提交</button>
    </view>
  </view>
</template>

<script>
import { unproductive, getCode } from "@/api/pda/selfBuiltPickOrder.js";
import { typeName } from "@/pages/pda/feeding/common.js";

export default {
  data() {
    return {
      pickForm: {
        pickCode: "",
        pickName: "",
      },
      objPick: {
        pickList: [],
      },
      selectionData: [],
      typeName,
    };
  },

  onLoad() {
    this.getOrderCode();
  },

  onShow() {
    uni.$off("setSelectList");

    uni.$on("setSelectList", (selectList, id) => {
      selectList.forEach((item) => {
        item.code = item.categoryCode;
        item.name = item.categoryName;
        item.modelType = item.categoryModel;
        item.measuringUnit = item.measuringUnit
          ? item.measuringUnit
          : item.measureUnit;
        item.unit = item.unit ? item.unit : item.measureUnit;
        item.demandQuantity = "";
      });

      const newData = [];

      if (selectList.length != 0) {
        selectList.forEach((it) => {
          newData.push(this.deepCopy(it));
        });
      }

      this.objPick = {
        pickList: newData,
      };

      this.$forceUpdate();
    });
  },

  methods: {
    async getOrderCode() {
      this.pickForm.pickCode = await getCode("pick_order_code");
    },

    deepCopy(obj, hash = new WeakMap()) {
      if (obj === null) return null;
      if (obj instanceof Date) return new Date(obj);
      if (obj instanceof RegExp) return new RegExp(obj);
      if (typeof obj !== "object" && typeof obj !== "function") return obj;
      if (hash.has(obj)) return hash.get(obj);

      const result = Array.isArray(obj) ? [] : {};
      hash.set(obj, result);

      return Object.keys(obj).reduce((acc, key) => {
        acc[key] = this.deepCopy(obj[key], hash);
        return acc;
      }, result);
    },

    openPicking() {
      // this.$refs.pickingRef.open(this.objPick);
    },

    checkItem(row) {
      row.checked = !row.checked;
    },

    limitNum(row) {
      if (row.demandQuantity > row.measureQuantity) {
        row.demandQuantity = row.measureQuantity;
      }
    },

    // batchDelete() {
    //   const filter = this.objPick.pickList.filter((i) => !i.checked);
    //   if (filter.length === this.objPick.pickList.length) {
    //     return uni.showToast({ title: "请选择需要删除的数据", icon: "none" });
    //   }
    //   this.objPick.pickList = filter;
    // },

    removeItem(index) {
      this.objPick.pickList.splice(index, 1);
    },

    openPicking() {
      const storageKey = Date.now() + "";
      uni.setStorageSync(storageKey, this.objPick.pickList || []);
      uni.navigateTo({
        url: `/pages/pda/selfBuiltPickOrder/components/choosePickList?isType=pick&storageKey=${storageKey}`,
      });
    },

    // allSelection(id, list) {
    //   list.forEach((i) => {
    //     i.code = i.categoryCode;
    //     i.name = i.categoryName;
    //     i.measuringUnit = i.measuringUnit || i.measureUnit;
    //   });
    //   this.objPick.pickList = JSON.parse(JSON.stringify(list));
    // },

    save() {
      if (!this.pickForm.pickName) {
        return uni.showToast({ title: "请输入领料单名称", icon: "none" });
      }

      if (this.objPick.pickList.length == 0) {
        return uni.showToast({ title: "请选择物料", icon: "none" });
      }
      if (this.objPick.pickList.length > 0) {
        let name;
        let bol2;
        let _i;

        bol2 = this.objPick.pickList.every((e, i) => {
          _i = i;
          name = e.name;
          // e.categoryId = e.id;
          // e.id = e.categoryId
          return (
            Object.prototype.hasOwnProperty.call(e, "demandQuantity") &&
            Number(e.demandQuantity) > 0 &&
            e.warehouseId
          );
        });

        if (!bol2) {
          // this.$message.warning(
          //   `${this.objPick.pickList[_i].code}的${name}数据不能为空`
          // );
          // return false;
          return uni.showToast({
            title: `${this.objPick.pickList[_i].code}的${name}数量不能为空`,
            icon: "none",
          });
        }
      }

      let param = {
        detailList: this.objPick.pickList,
        name: this.pickForm.pickName,
        code: this.pickForm.pickCode,
      };

      unproductive(param).then((res) => {
        uni.showToast({ title: "提交成功" });
        setTimeout(() => {
          uni.navigateBack();
        }, 500);
      });
      // if (!this.objPick.pickList.length) {
      //   return uni.showToast({ title: "请选择物料", icon: "none" });
      // }

      // const valid = this.objPick.pickList.every(
      //   (e) => e.demandQuantity > 0 && e.warehouseId
      // );
      // if (!valid) {
      //   return uni.showToast({ title: "请完善物料信息", icon: "none" });
      // }

      // const param = {
      //   detailList: this.objPick.pickList,
      //   name: this.pickForm.pickName,
      //   code: this.pickForm.pickCode,
      // };

      // unproductive(param).then(() => {
      //   uni.showToast({ title: "提交成功" });
      //   this.close(true);
      // });
    },

    close(refresh) {
      uni.$emit("closePick", refresh);
      uni.navigateBack();
    },
  },
};
</script>

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

.scroll-container {
  flex: 1;
  padding: 10rpx 16rpx;
  overflow-y: auto;
}

/* 顶部表单 */
.form-section {
  background: #fff;
  border-radius: 12rpx;
  padding: 16rpx;
  margin-bottom: 16rpx;

  .form-item {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    margin-bottom: 12rpx;

    .label {
      width: 30%;
      font-size: 28rpx;
      color: #666;
      margin-bottom: 4rpx;
    }

    uni-easyinput {
      flex: 1;
    }
  }

  .btn-add {
    display: flex;
    justify-content: flex-end;
  }
}

/* 物料列表卡片 */
.material-list {
  display: flex;
  flex-direction: column;
  gap: 16rpx;

  .material-card {
    position: relative;
    background: #fff;
    border-radius: 12rpx;
    padding: 16rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
    transition: background 0.2s;

    &:active {
      background: #f5f5f5;
    }

    .delete-btn {
      position: absolute;
      top: 8rpx;
      right: 8rpx;
      width: 40rpx;
      height: 40rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: 10;
      background: rgba(255, 255, 255, 0.8);
      border-radius: 50%;
      box-shadow: 0 1rpx 3rpx rgba(0, 0, 0, 0.2);
    }

    .card-content {
      display: flex;
      flex-direction: column;
      gap: 8rpx;

      .card-row {
        display: flex;
        // flex-wrap: wrap;
        align-items: center;

        .label {
          width: 22%;
          flex-shrink: 0;
          font-size: 26rpx;
          color: #666;
          margin-bottom: 4rpx;
        }
        .input-row {
          display: flex;
          align-items: center;
          gap: 8rpx;

          uni-easyinput {
            flex: 1; // 占满剩余空间
            min-width: 0; // ✅允许收缩，防止换行
          }

          .unit {
            flex-shrink: 0; // 单位宽度固定
            font-size: 24rpx;
            color: #666;
          }
        }
      }
    }
  }
}

/* 底部固定按钮 */
.footer-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background: #fff;
  padding: 16rpx;
  display: flex;
  justify-content: space-between;
  box-shadow: 0 -2rpx 6rpx rgba(0, 0, 0, 0.05);
  z-index: 20;
}

/deep/ .uni-easyinput__content-input {
  padding-left: 0;
}
</style>
