<template>
  <view class="con-body">
    <view class="con-bg">
      <!-- 头部 -->
      <customHeader ref="customHeaderRef" :title="'客户订单列表'" :leftFlag="true" :rightFlag="true">
        <template #right>
          <view class="head-right" @click="handleConfirm">
            确定
          </view>
        </template>
      </customHeader>

      <!-- 高度来避免头部遮挡 -->
      <view class="top-height" :style="{ paddingTop: navBarPaddingTop + 'px' }"></view>

      <!-- 正文内容 -->
      <view class="all-body">
        <!-- 搜索 -->
        <view class="search">
          <uni-search-bar class="custom-search" radius="28" placeholder="请输入合同名称" clearButton="auto"
                          cancelButton="none" bgColor="#6FA2F8" textColor="#ffffff"
                          v-model="cusCode" @clear="cusCode=''"></uni-search-bar>
        </view>

        <!-- 分页部分 -->
        <mescroll-uni ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback"
                      :up="upOption" :down="downOption" :fixed="false" textColor="#ffffff" bgColor="#ffffff"
                      class="scroll-h" :class="{'loading-scroll':cssFlag}"
        >
          <checkbox-group class="block">
            <view class="white-bg" v-for="(item, index) in list" :key="index">
              <checkbox class='checkbox' 
                     :checked="selectedItems.includes(index)"
                     @click.stop="toggleItem(index)"
              ></checkbox>

              <view class="report-list">
                <view class="title">批号：{{ item.tokenCode }}</view>
                <view class="title">数量：{{ item.amount }}</view>
                <view class="title">合同号：{{ item.orderCoode }}</view>
                <view class="title">母批：{{ item.texing }}</view>
                <view class="title">产品大类：{{ item.code }}</view>
                <view class="title">规格型号：{{ item.name }}</view>
                <view class="title">产品ID：{{ item.materialId }}</view>
                <view class="border-bottom"></view>
              </view>
            </view>
          </checkbox-group>
        </mescroll-uni>
      </view>
    </view>
  </view>
</template>

<script setup>

import {ref, onMounted, getCurrentInstance, watch} from 'vue'
import customHeader from '@/components/customHeader.vue'
import {getNavBarPaddingTop} from '@/utils/system.js'
import {onLoad} from "@dcloudio/uni-app";
import {getCustomerOrderList} from "@/api/eqf/qualityFeedback.js";

let instance = null;
// 获取导航栏高度用于内容区域padding
const navBarPaddingTop = ref(0);
// 查询列表
let list = ref([]);
const mescrollRef = ref(null);
let cusCode = ref('')

let cssFlag=ref(false);//控制样式

const upOption = ref({
  page: { num: 0, size: 10 },
  noMoreSize: 5,
  empty: {
    tip: '~ 空空如也 ~',
    icon: "../../../../static/images/mescroll-empty.png"
  },
  textLoading: '加载中...',
  textNoMore: '已经到底了'
});

const downOption = ref({
  auto: true,
  textInOffset: '下拉刷新',
  textOutOffset: '释放更新',
  textLoading: '刷新中...'
});

const mescrollInit = (mescroll) => {
  cssFlag.value = true;
  mescrollRef.value = mescroll;
};

onMounted(() => {
  navBarPaddingTop.value = getNavBarPaddingTop() * 2;
})


onLoad((options)=>{
  instance = getCurrentInstance().proxy;
  const eventChannel = instance.getOpenerEventChannel();
  eventChannel.on('requestCusList', async (res) => {
    let {cusName} = res.data;
    cusCode.value = cusName;
  })
})

let timerId = null;
// 搜索
watch(cusCode, (newValue, oldValue) => {
  if(timerId) clearTimeout(timerId);
  timerId = setTimeout(async ()=>{
    handleSearch();
    clearTimeout(timerId);
    timerId = null;
  }, 500);
});

// 下拉刷新
const downCallback = async (mescroll) => {
  try {
    const res = await getList(1, upOption.value.page.size);
    list.value = res.list;
    // 清空选中状态
    selectedItems.value = [];
    // 正确结束下拉刷新状态
    if (mescroll && typeof mescroll.endSuccess === 'function') {
      mescroll.endSuccess(res.list.length, res.total >= upOption.value.page.size);
    }
  } catch (error) {
    // 发生错误时结束下拉刷新，添加空值检查
    if (mescroll && typeof mescroll.endErr === 'function') {
      mescroll.endErr();
    } else {
      console.error('mescroll 对象不存在或 endErr 方法未定义', error);
    }
  }
}

// 上拉加载更多
const upCallback = async (mescroll) => {
  try {
    const res = await getList(mescroll.num, mescroll.size);
    if (mescroll.num === 1) {
      list.value = res.list;
      // 清空选中状态
      selectedItems.value = [];
    } else {
      list.value.push(...res.list);
    }
    // 正确结束上拉加载状态
    if (mescroll && typeof mescroll.endSuccess === 'function') {
      mescroll.endSuccess(res.list.length, res.list.length >= mescroll.size);
    }
  } catch (error) {
    // 发生错误时结束上拉加载，添加空值检查
    if (mescroll && typeof mescroll.endErr === 'function') {
      mescroll.endErr();
    } else {
      console.error('mescroll 对象不存在或 endErr 方法未定义', error);
    }
  }
}

// 查询搜索跳转
let handleSearch = async () => {
  // 触发下拉刷新以重新加载数据
  if (mescrollRef.value) {
    cssFlag.value = true;
    uni.showLoading()
    await downCallback(mescrollRef.value.mescroll);
    uni.hideLoading()
    cssFlag.value = false;
  }
}
// 获取数据列表
const getList = async (pageIndex, pageSize) => {
  const param = {
    pageNum: pageIndex,
    pageSize,
    cusCode: cusCode.value
  }
  let { rows, total } = await getCustomerOrderList(param)
  return {list: rows, total};
}

// 存储选中项的索引数组
const selectedItems = ref([]);

// 切换单项选中状态
const toggleItem = (index) => {
  if (selectedItems.value.includes(index)) {
    // 取消选中
    selectedItems.value = selectedItems.value.filter(item => item !== index);
  } else {
    // 选中
    selectedItems.value.push(index);
  }
  console.log('当前选中的索引:', selectedItems.value);
}

// 不再需要checkboxChange函数，因为已经通过toggleItem处理了所有选择逻辑

// 确认选择并返回
const handleConfirm = () => {
  // 确保list.value和selectedItems.value有效
  if (!list.value || !selectedItems.value || selectedItems.value.length === 0) {
    uni.showToast({ title: '请选择数据', icon: 'none' });
    return;
  }
  
  // 获取选中的实际数据项，添加安全检查
  const selectedData = selectedItems.value
    .filter(index => index >= 0 && index < list.value.length) // 确保索引有效
    .map(index => list.value[index]);  
  
  console.log('所有选中的数据:', selectedData);
  
  // 发送全局事件，传递选中的数据和逗号分隔的字符串
  uni.$emit('onCustomerSelected', {
    originalData: selectedData,
  });
  
  // 设置标记，表示从选择页面返回
  uni.setStorageSync('isFromCustomerOrderPage', true);
  
  // 返回上一页
  uni.navigateBack();
}

</script>

<style lang="scss" scoped>
.all-body {
  /* #ifdef APP-PLUS */
  top: 150rpx;
  height: calc(100vh - 75px);
  /* #endif */
  /* #ifndef APP-PLUS */
  top: 120rpx;
  height: calc(100vh);
  /* #endif */
}

.search .btn-search {
  border: none;
  background: none;
  line-height: normal;
  color: #fff;
  line-height: 56rpx !important;
  padding: 10rpx 0 0;
  text-align: left;
  cursor: pointer;
}

.search .btn-search::after {
  display: none;
}

.scroll-h {
  /* #ifdef APP-PLUS */
  height: calc(100vh - 120px);
  /* #endif */
  /* #ifndef APP-PLUS */
  height: calc(100vh - 110px);
  /* #endif */
}

.white-bg {
  //padding-bottom:10rpx;
  margin-bottom: 0;
  overflow: hidden;
  display: flex;
  align-items: center;
}

.checkbox {
  padding-right: 20rpx;
  transform: scale(0.8); // 调整复选框大小以匹配UI
}

.title {
  font-size: 32rpx;
  line-height: 48rpx;
}

.report-list {
  width: calc(100% - 70rpx);
  //background-color: pink;
}

.border-bottom {
  margin-top: 6rpx;
}
</style>