<template>
  <view class="page-container">
    <uni-nav-bar
      fixed="true"
      statusBar="true"
      left-icon="back"
      title="搜索"
      @clickLeft="back"
    >
      <!--右菜单-->
      <template slot="right">
        <u-button
          type="success"
          size="small"
          class="u-reset-button nav-right-btn"
          @click="openTreePicker"
          text="选择分类"
        ></u-button>
      </template>
    </uni-nav-bar>

    <!-- 搜索栏 -->
    <view class="search-wrapper">
      <view class="search-bar">
        <view class="search-input-box">
          <uni-icons type="search" size="18" color="#999"></uni-icons>
          <input
            v-model="keyWord"
            placeholder="请输入关键字搜索"
            placeholder-class="search-placeholder"
            class="search-input"
            confirm-type="search"
            @confirm="doSearch"
          />
        </view>
        <view class="search-actions">
          <view class="filter-btn" @click="handleSearch">
            <image
              class="filter-icon"
              src="~@/static/pda/menu.svg"
            ></image>
          </view>
          <view class="search-btn" @click="doSearch">
            <text class="search-btn-text">搜索</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 列表区域 -->
    <view class="list-container">
      <u-list @scrolltolower="scrolltolower">
        <checkbox-group
          v-for="(item, index) in list"
          :key="index"
          @change="(e) => selectVal(e, item, index)"
        >
          <label class="list-card">
            <view class="card-checkbox">
              <checkbox
                v-if="
                  item.rootCategoryLevelId != 11 ||
                  (item.rootCategoryLevelId == 11 && item.status != 1)
                "
                :value="item.code"
                color="#fff"
                :disabled="item.disabled"
                :checked="item.checked"
              />
            </view>

            <view class="card-content">
              <view class="card-header">
                <text class="card-title">{{ item.categoryName }}</text>
                <text class="card-code">{{
                  item.rootCategoryLevelId == 4
                    ? item.codeNumber
                    : item.categoryCode
                }}</text>
              </view>

              <view class="card-body">
                <view
                  v-for="(itm, idx) in tableH(item.rootCategoryLevelId)"
                  :key="idx"
                  class="info-item"
                  v-if="!itm.formatter"
                >
                  <text class="info-label">{{ itm.label }}</text>
                  <text class="info-value">{{ item[itm.prop] }}</text>
                </view>

                <view class="info-item">
                  <text class="info-label">批次号</text>
                  <text class="info-value">{{ item.batchNo }}</text>
                </view>

                <view class="info-item">
                  <text class="info-label">计量库存数量</text>
                  <text class="info-value">{{ item.measureQuantity }} {{ item.measureUnit }}</text>
                </view>

                <view class="info-item">
                  <text class="info-label">重量</text>
                  <text class="info-value">{{ item.weight }} {{ item.weightUnit }}</text>
                </view>

                <view class="info-item">
                  <text class="info-label">编号</text>
                  <text class="info-value">{{ item.codeNumber }}</text>
                </view>

                <view class="info-item">
                  <text class="info-label">仓库</text>
                  <text class="info-value">{{ item.warehouseName }}</text>
                </view>
              </view>
            </view>
          </label>
        </checkbox-group>

        <view v-if="list.length == 0" class="empty-state">
          <u-empty iconSize="150" textSize="32" text="暂无数据"> </u-empty>
        </view>
      </u-list>
    </view>

    <!-- 底部操作栏 -->
    <view class="footer-bar">
      <view class="footer-left">
        <checkbox
          v-if="!seletedAll"
          color="#fff"
          :checked="seletedAll"
          @tap="_seletedAll"
          >全选</checkbox
        >
        <checkbox
          class="select-all"
          color="#fff"
          v-else
          :checked="seletedAll"
          @tap="_seletedAll"
          >取消全选
        </checkbox>
      </view>
      <view class="footer-right">
        <u-button
          type="success"
          size="small"
          class="u-reset-button confirm-btn"
          :disabled="!checkListLen"
          @click="jumpAdd(1)"
        >
          <view> 选择( {{ checkListLen }} ) </view>
        </u-button>

        <!-- 	<u-button v-if='rootCategoryLevelId == 23' type="success" size="small" class="u-reset-button"
					@click="jumpAdd(2)">
					<view> 确认 </view>
				</u-button> -->
      </view>
    </view>

    <ba-tree-picker
      ref="treePicker"
      key="verify"
      :multiple="false"
      @select-change="confirm"
      title="选择分类"
      :localdata="classificationList"
      valueKey="id"
      textKey="name"
      childrenKey="children"
    />

    <SearchPopup mode="top" v-if="searchShow">
      <template v-slot:list>
        <view class="search_list">
          <u-form
            labelPosition="left"
            :model="formData"
            labelWidth="180"
            labelAlign="left"
            class="baseForm"
          >
            <u-form-item
              label="仓库:"
              class="required-form"
              borderBottom
              prop="warehouseId"
            >
              <zxz-uni-data-select
                :localdata="warehouseList"
                v-model="formData.warehouseId"
                dataValue="id"
                format="{name}"
                dataKey="name"
                filterable
              ></zxz-uni-data-select>
            </u-form-item>

            <u-form-item
              label="维度:"
              v-if="isType == 'pick'"
              class="required-form"
              borderBottom
              prop="warehouseId"
            >
              <zxz-uni-data-select
                :localdata="dimensionList"
                v-model="formData.dimension"
                dataValue="id"
                format="{name}"
                dataKey="name"
                filterable
              ></zxz-uni-data-select>
            </u-form-item>
          </u-form>
        </view>
      </template>

      <template v-slot:operate>
        <view class="operate_box rx-bc">
          <u-button size="small" class="u-reset-button" @click="searchCancel">
            重置
          </u-button>

          <u-button
            type="success"
            size="small"
            class="u-reset-button"
            @click="doSearch"
          >
            确定
          </u-button>
        </view>
      </template>
    </SearchPopup>
  </view>
</template>

<script>
import baTreePicker from "@/components/ba-tree-picker/ba-tree-picker.vue";
import { tableHeader } from "../../common.js";
import {
  treeByPid,
  pageeLedgerMain,
  assetPage,
  getWarehouseList,
  listInProduct,
  outsourceEndPick,
  categoryGetList,
  getBatchListInventory,
  getProductListInventory,
} from "@/api/pda/workOrder.js";

import SearchPopup from "../../components/searchPopup.vue";

import { EventBus } from "@/utils/eventBus.js";

let [isEnd] = [false];
export default {
  components: {
    baTreePicker,
    SearchPopup,
  },
  data() {
    return {
      keyWord: null,
      rootCategoryLevelId: null,
      categoryLevelId: null,
      classificationList: [],
      treePickerShow: false,
      list: [],
      page: 1,

      seletedAll: false, //全选状态
      memoList: [],

      isType: null,
      taskId: null,

      pid: null, // 上个页面id
      storageKey: null,

      formData: {
        produceRoutingId: "",
        dimension: 2,
      },
      warehouseList: [],

      searchShow: false,

      stateList: [
        "启动",
        "空闲",
        "运行",
        "故障",
        "检修",
        "停机",
        "待料",
        "占用",
      ],
      classIds: [],

      dimensionList: [
        {
          id: 1,
          name: "物品维度",
        },
        {
          id: 2,
          name: "批次维度",
        },
      ],

      clientEnvironmentId:
        uni.getStorageSync("userInfo") &&
        uni.getStorageSync("userInfo").clientEnvironmentId, // *1 主环境-601环境   2 soll-索尔环境    3 tg-碳谷环境
    };
  },

  //选择的列表长度
  computed: {
    checkListLen() {
      return this.memoList.length;
    },
  },

  onLoad(option) {
    this.pid = option.id;
    this.classIds = option.classIds || [];

    this.isType = option.isType;
    if (option.taskId == "undefined") {
      this.taskId = null;
    } else {
      this.taskId = option.taskId || null;
    }
    if (Object.prototype.hasOwnProperty.call(option, "classIds")) {
      this.classIds = option.classIds;
    }

    if (option.storageKey) {
      this.storageKey = option.storageKey;

      this.memoList = [];

      if (this.isType == "feed") {
        let _arr =
          (this.storageKey && uni.getStorageSync(this.storageKey)) || [];
        this.memoList = [
          ..._arr[0].modelList,
          ..._arr[0].equipmentList,
          ..._arr[0].instanceList,
          ..._arr[0].aridRegionList,
          ..._arr[0].turnover,
          ..._arr[0].palletList,
          ..._arr[0].revolvingDiskList,
          ..._arr[0].semiProductList,
        ];
      } else if (this.isType == "pick") {
        this.memoList =
          (this.storageKey && uni.getStorageSync(this.storageKey)) || [];
      } else if (this.isType == "job") {
        let _obj =
          (this.storageKey && uni.getStorageSync(this.storageKey)) || {};

        if (Object.prototype.hasOwnProperty.call(_obj, "turnover")) {
          this.memoList = this.memoList.concat(_obj.turnover);
        } else if (
          Object.prototype.hasOwnProperty.call(_obj, "equipmentList")
        ) {
          this.memoList = this.memoList.concat(_obj.equipmentList);
        }
      } else if (this.isType == "zdy") {
        let _arr =
          (this.storageKey && uni.getStorageSync(this.storageKey)) || [];

        if (
          _arr.length != 0 &&
          Object.prototype.hasOwnProperty.call(_arr[0], "turnover")
        ) {
          this.memoList = this.memoList.concat(_arr[0].turnover);
        } else if (
          _arr.length != 0 &&
          Object.prototype.hasOwnProperty.call(_arr[0], "equipmentList")
        ) {
          this.memoList = this.memoList.concat(_arr[0].equipmentList);
        } else if (
          _arr.length != 0 &&
          Object.prototype.hasOwnProperty.call(_arr[0], "standardOutputList")
        ) {
          this.memoList = this.memoList.concat(_arr[0].standardOutputList);
        } else if (
          _arr.length != 0 &&
          Object.prototype.hasOwnProperty.call(_arr[0], "bomMaterialList")
        ) {
          this.memoList = this.memoList.concat(_arr[0].bomMaterialList);
        }
      }
    }

    this.getTreeList();

    this.getWarehouseFn();
  },

  onUnload() {
    if (this.storageKey) {
      uni.removeStorage(this.storageKey);
    }
  },

  methods: {
    _seletedAll() {
      if (!this.seletedAll) {
        this.seletedAll = true;

        this.list.map((item) => {
          this.$set(item, "checked", true);
          const idx = this.memoList.findIndex((itm) => itm.id === item.id);
          if (idx === -1) {
            this.memoList.push(item);
          }
        });
      } else {
        this.seletedAll = false;
        this.list.map((item) => {
          this.$set(item, "checked", false);

          const idx = this.memoList.findIndex((itm) => itm.id === item.id);
          if (idx > -1) {
            this.memoList.splice(idx, 1);
          }
        });
      }
    },

    openTreePicker() {
      this.$refs.treePicker._show();
    },
    tableH(type) {
      return [
        {
          label: "型号",
          prop: "categoryModel",
        },
        {
          label: "规格",
          prop: "specification",
        },
        {
          label: "牌号",
          prop: "brandNum",
        },
      ];
      // return tableHeader(type);
    },

    getTreeList() {
      let params = {};
      console.log(this.classIds, "option", this.isType);
      if (this.isType == "feed") {
        // params.ids = [1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 26, 9, 28];
        params.ids = ["4, 5, 7, 8, 11, 14, 26"];
      } else if (this.isType == "pick") {
        // params.ids = [1, 5, 7, 8, 10, 13, 14, 23, 26, 9, 28]
        params.ids = [9, 23, 2, 1, 4, 14, 5, 8, 16, 13, 15, 6, 10, 22];
      } else if (this.isType == "job") {
        // params["ids"] = [4, 7];
        if (this.clientEnvironmentId == 2) {
          params["ids"] = [7];
        } else {
          params["ids"] = [4, 5, 7, 8, 11, 14, 26];
        }
      } else if (this.isType == "zdy") {
        params["ids"] = JSON.parse(this.classIds);
      } else if (this.isType == "weiwai") {
        // params['ids'] = JSON.parse(this.classIds)
        params["ids"] = [9, 23, 2, 1, 4, 14, 5, 8, 16, 13, 15, 6, 10, 22];
      }

      treeByPid(params).then((res) => {
        this.classificationList = res;
        this.confirm([res[0].id], res[0].name, res[0].rootCategoryLevelId);
      });
    },

    confirm(id, name, rootCategoryLevelId) {
      this.rootCategoryLevelId = rootCategoryLevelId;

      this.categoryLevelId = id;

      this.list = [];

      console.log("是这里嘛");
      this.getList();
    },

    doSearch() {
      this.list = [];
      this.getList();
      this.searchShow = false;
    },

    scrolltolower() {
      if (isEnd) return;
      this.page++;
      this.getList();
    },

    getList() {
      let param = {
        categoryLevelId: this.categoryLevelId,
        keyWord: this.keyWord,
        pageNum: this.page,
        size: 100,
        taskId: this.taskId,
      };

      if (this.rootCategoryLevelId == "11") {
        // 干燥区特殊处理
        param.size = 5;
      }
      isEnd = false;
      let URL = null;
      if (this.isType == "pick") {
        // 领料
        // if (this.rootCategoryLevelId == 23) {
        // 	this.list = []
        // 	param = {}
        // 	param.workOrderId = this.pid
        // 	URL = listOutsourceInWarehouse
        // } else {
        // 	param.dimension = 1
        // 	URL = pageeLedgerMain
        if (this.formData.dimension == 1) {
          URL = getProductListInventory;
        } else if (this.formData.dimension == 2) {
          URL = getBatchListInventory;
        }
        // }
        param.dimension = this.formData.dimension;
        // URL = pageeLedgerMain;
      } else if (this.isType == "feed") {
        // 投料

        if ([4, 7, 14].includes(Number(this.rootCategoryLevelId))) {
          URL = assetPage;
        } else if (this.rootCategoryLevelId == 2) {
          param.workOrderId = this.pid;
          delete param.taskId;
          delete param.categoryLevelId;
          URL = listInProduct;
        } else if (![2, 4, 7, 14].includes(Number(this.rootCategoryLevelId))) {
          URL = assetPage;
          // if (this.formData.dimension == 3) { // 包装维度
          // 	URL = getInventoryDetails
          // 	param.dimension = 3
          // 	param.rootCategoryLevelId = this.rootCategoryLevelId
          // } else if (this.formData.dimension == 4) { // 物料维度
          // 	param.dimension = 4
          // 	param.rootCategoryLevelId = this.rootCategoryLevelId
          // 	URL = getMaterielDetails
          // }
        }
      } else if (this.isType == "job" || this.isType == "zdy") {
        // 报工
        URL = assetPage;
      } else if (this.isType == "weiwai") {
        // 出库
        if (this.pid == 3) {
          URL = categoryGetList;
        } else {
          // URL = assetPdaPage
          URL = pageeLedgerMain;
        }
      }

      URL(param).then((res) => {
        if (this.rootCategoryLevelId == "11") {
          res.list.forEach((e) => {
            if (e.aridRegionList && e.aridRegionList.length != 0) {
              e.aridRegionList.map((i) => {
                const checked =
                  this.memoList.findIndex((itm) => itm.id === i.id) > -1;

                let obj = {
                  checked,
                  name: e.name,
                  region: e.extInfo.region,
                  rootCategoryLevelId: e.rootCategoryLevelId,
                  ...i,
                  instanceId: i.id,
                };
                this.list.push(obj);
              });
            }
          });
        } else {
          this.list.push(
            ...res.list.map((i) => {
              const checked =
                this.memoList.findIndex((itm) => itm.id === i.id) > -1;

              const warehouseId = i.pathIds && i.pathIds.split(",")[0];

              return {
                checked,
                warehouseId,
                ...i,
                instanceId: i.id,
              };
            }),
          );
        }

        isEnd = this.list.length >= res.count;
      });
    },

    //勾选
    selectVal(e, val, index) {
      if (val.rootCategoryLevelId == 11 && val.status == 1) {
        return false;
      }
      this.list[index].checked = !this.list[index].checked;
      this.seletedAll = !this.list.some((item) => !item.checked);
      const idx = this.memoList.findIndex(
        (item) => item.id === this.list[index].id,
      );

      if (this.list[index].checked) {
        if (idx === -1) {
          this.memoList.push(this.list[index]);
        }
      } else {
        if (idx > -1) {
          this.memoList.splice(idx, 1);
        }
      }
    },

    handleSearch() {
      this.searchShow = true;
    },

    searchCancel() {
      this.list = [];
      this.page = 1;
      this.getList();
      this.searchShow = false;
    },

    //跳转回添加页面
    jumpAdd(type) {
      if (type == 1) {
        if (
          this.isType == "pick" ||
          this.isType == "feed" ||
          this.isType == "job" ||
          this.isType == "zdy" ||
          this.isType == "weiwai"
        ) {
          this.memoList.map((item) => {
            item.extInfo.heatNumber = "";
          });

          if (
            (this.isType == "zdy" || this.isType == "weiwai") &&
            (this.pid == 2 || this.pid == 3)
          ) {
            let param = {
              memoList: this.memoList,
              pid: this.pid,
            };

            console.log(param, "paramparamparam");

            EventBus.$emit("outEvent", { message: param });
          } else {
            uni.$emit("setSelectList", this.memoList, this.pid);
          }

          uni.navigateBack();
        }
      } else if (type == 2) {
        uni.showModal({
          title: "提示",
          content: "是否领取该工单半成品到此工序！",
          confirmText: "确认", //这块是确定按钮的文字
          success: (rr) => {
            if (rr.confirm) {
              let param = {
                taskId: this.taskId,
                workOrderId: this.pid,
                pickOutInList: this.list,
              };

              outsourceEndPick(param).then((res) => {
                // uni.$emit('setSelectList', this.list, this.pid)
                uni.showToast({
                  title: "半成品领料成功，请先去审核",
                  icon: "none",
                });

                uni.navigateBack();
              });
            }
          },
        });
      }
    },

    getWarehouseFn() {
      getWarehouseList().then((res) => {
        this.warehouseList = res;
      });
    },
  },
};
</script>

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

/* 导航栏右侧按钮 */
.nav-right-btn {
  border-radius: 30rpx !important;
  font-size: 24rpx !important;
  padding: 0 24rpx !important;
}

/* 搜索栏 */
.search-wrapper {
  padding: 16rpx 24rpx;
  background-color: #fff;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.search-input-box {
  flex: 1;
  display: flex;
  align-items: center;
  height: 72rpx;
  background-color: #f5f6f7;
  border-radius: 36rpx;
  padding: 0 24rpx;
  gap: 12rpx;
}

.search-input {
  flex: 1;
  height: 72rpx;
  font-size: 28rpx;
  color: $uni-text-color;
}

.search-placeholder {
  color: #c0c0c0;
  font-size: 26rpx;
}

.search-actions {
  display: flex;
  align-items: center;
  flex-shrink: 0;
  gap: 12rpx;
}

.filter-btn {
  width: 64rpx;
  height: 64rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f6f7;
  border-radius: 50%;

  &:active {
    opacity: 0.7;
  }
}

.filter-icon {
  width: 40rpx;
  height: 40rpx;
}

.search-btn {
  height: 64rpx;
  padding: 0 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: $theme-color;
  border-radius: 32rpx;

  &:active {
    opacity: 0.85;
  }
}

.search-btn-text {
  color: #fff;
  font-size: 26rpx;
  white-space: nowrap;
}

/* 列表容器 */
.list-container {
  flex: 1;
  overflow: hidden;
  padding: 0 24rpx;

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

/* 列表卡片 */
.list-card {
  display: flex;
  align-items: flex-start;
  margin-top: 20rpx;
  padding: 24rpx;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

  /deep/ .uni-checkbox-input-checked {
    background-color: $theme-color !important;
    border-color: $theme-color !important;
  }
}

.card-checkbox {
  flex-shrink: 0;
  margin-right: 16rpx;
  padding-top: 4rpx;
}

.card-content {
  flex: 1;
  min-width: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.card-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #1a1a1a;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.card-code {
  font-size: 24rpx;
  color: $theme-color;
  background-color: rgba(21, 122, 44, 0.08);
  padding: 4rpx 16rpx;
  border-radius: 20rpx;
  flex-shrink: 0;
  margin-left: 16rpx;
}

.card-body {
  display: flex;
  flex-wrap: wrap;
  margin-top: 16rpx;
  gap: 0;
}

.info-item {
  width: 50%;
  display: flex;
  flex-direction: column;
  padding: 12rpx 0;
  box-sizing: border-box;

  &:nth-child(odd) {
    padding-right: 16rpx;
  }

  &:nth-child(even) {
    padding-left: 16rpx;
    border-left: 1rpx solid #f0f0f0;
  }
}

.info-label {
  font-size: 22rpx;
  color: #999;
  margin-bottom: 4rpx;
  line-height: 1.4;
}

.info-value {
  font-size: 26rpx;
  color: #333;
  word-break: break-all;
  line-height: 1.5;
}

/* 空状态 */
.empty-state {
  margin-top: 20vh;
}

/* 底部操作栏 */
.footer-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 110rpx;
  background: #fff;
  padding: 0 32rpx;
  box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.06);
  /* 适配底部安全区域 */
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);

  /deep/ .uni-checkbox-input-checked {
    background-color: $theme-color !important;
    border-color: $theme-color !important;
  }
}

.footer-left {
  font-size: 28rpx;
  color: #333;
}

.footer-right {
  display: flex;
  align-items: center;
}

.confirm-btn {
  border-radius: 32rpx !important;
  padding: 0 36rpx !important;
  height: 68rpx !important;
  line-height: 68rpx !important;
  font-size: 28rpx !important;
}

/* 搜索弹窗 */
.search_list {
  min-height: 100rpx;

  /deep/ .baseForm {
    padding: 0 24rpx;
  }
}

.operate_box {
  padding: 16rpx 24rpx;
}
</style>
