<template>
  <view class="con-body">
    <view class="con-bg">
      <!-- 头部 -->
      <customHeader ref="customHeaderRef" :title="'质量反馈'" :leftFlag="true" :rightFlag="true">
        <template #right>
          <view class="head-right" @click="handleAdd">
            <uni-icons type="plus" size="24" color="#B7D2FF"></uni-icons>新增
          </view>
        </template>
      </customHeader>

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

      <!-- 正文内容 -->
      <view class="all-body">
        <!-- 搜索  @blur="blur" @focus="focus" @input="input" @cancel="cancel" @clear="clear"-->
        <view class="search">
          <uni-search-bar class="custom-search" radius="28" placeholder="请输入客户名称" clearButton="auto"
                          cancelButton="none" bgColor="#6FA2F8" textColor="#ffffff" v-model="searchValue" />
          <button type="default" @click="handleSearch" size="mini" class="btn-search">查询</button>
        </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 }">
          <view class="white-bg margin-bottom20" v-for="(item, index) in list" :key="index"
                @touchstart.prevent="touchstart(item)" @touchend.prevent="touchend">
            <view>
              <view class="report-list">
                <view class="title">客户：{{ item.customerName }}-{{ item.id }}</view>
                <view class="r-list">
                  <view class="r-name">{{ item.qualityCode }}</view>
                  <view @touchstart.stop="handleStatusTouchStart"
                        @touchend.stop="handleStatusTouchEnd" @click.stop="chooseStatus(item)">
                    <view class="r-right btn-orange" size="mini">
                      {{ item.status }}
                    </view>
                  </view>

                </view>
                <view class="border-bottom"></view>
                <view class="r-list">
                  <view class="r-left">外反类型</view>
                  <view class="r-right">{{ item.productType }}</view>
                </view>
                <view class="border-bottom"></view>
                <view class="r-list">
                  <view class="r-left">问题现象描述</view>
                  <view class="r-right">{{ item.ppNameDescribe }}</view>
                </view>
                <view class="border-bottom"></view>
                <view class="r-list">
                  <view class="r-left">问题发生阶段</view>
                  <view class="r-right">{{ item.posName }}</view>
                </view>
                <view class="border-bottom"></view>
                <view class="r-list">
                <view class="r-left">明细信息</view>
                  <view class="r-right detail-info" @click="showDetailInfo(item)">
                    <view class="detail-item">
                      <span class="detail-label">合同号：</span>
                      <span class="detail-value">{{ formatTextWithLineBreak(item.customerCode) }}</span>
                    </view>
                    <view class="detail-item">
                      <span class="detail-label">批号：</span>
                      <span class="detail-value">{{ formatTextWithLineBreak(item.batchNumber) }}</span>
                    </view>
                  </view>
                </view>
                <view class="border-bottom"></view>
                <view class="r-list">
                  <view class="r-left">创建人</view>
                  <view class="r-right">{{ item.createName }}</view>
                </view>
                <view class="border-bottom"></view>
                <view class="r-list">
                  <view class="r-left">创建日期</view>
                  <view class="r-right">{{ item.createTime }}</view>
                </view>

              </view>
            </view>
          </view>
        </mescroll-uni>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import customHeader from '@/components/customHeader.vue'
import { getNavBarPaddingTop } from '@/utils/system.js'
import { listFeedback, removeQualityFeedback, updateStatus } from '@/api/eqf/qualityFeedback.js';

// 获取导航栏高度用于内容区域padding
const navBarPaddingTop = ref(0);
onMounted(() => {
  navBarPaddingTop.value = getNavBarPaddingTop() * 2;
})

let informationId = ref(0);
let id = ref(null);
// 定义存储列表数据的响应式变量
// 查询列表
let list = ref([]);
let totalCount = ref(0);

onLoad((options) => {
  informationId.value = options.informationId;
  // 调用时传入分页参数，首次加载第一页，每页10条
  getQualityFeedbackList(1, 10)
    .then(data => {
      // 将数据更新到响应式变量
      list.value = data.list;
      totalCount.value = data.total;
    })
    .catch(error => {
      console.error('获取数据失败:', error);
    });
    
  // 监听刷新列表事件
  uni.$on('refreshFeedbackList', refreshList);
});

onShow(() => {
  // 页面显示时重新加载数据，确保数据最新
  getQualityFeedbackList(1, 10)
    .then(data => {
      list.value = data.list;
      totalCount.value = data.total;
    })
    .catch(error => {
      console.error('刷新数据失败:', error);
    });
});

// 在页面卸载时移除事件监听，避免内存泄漏
uni.$on('onUnload', () => {
  uni.$off('refreshFeedbackList', refreshList);
});

// 刷新列表数据的函数
const refreshList = () => {
  getQualityFeedbackList(1, 10)
    .then(data => {
      list.value = data.list;
      totalCount.value = data.total;
      // 如果有滚动组件实例，重置上拉加载状态
      if (mescrollRef.value) {
        mescrollRef.value.resetUpScroll();
      }
    })
    .catch(error => {
      console.error('刷新列表数据失败:', error);
    });
};



let searchValue = ref(null)

//监视查询的内容的变化
watch(searchValue, (newValue, oldValue) => {
  //变化了之后，重新查询内容
  var data = {
    pageNum: 1,
    pageSize: 10,
  };
  listFeedback(data).then(res => {
    if (res.code === 200) {
      //设置列表数据
      list.value = res.rows;
    }
  })
})

// 添加显示详细信息的函数
const showDetailInfo = (item) => {
  uni.showModal({
    title: '明细信息',
    content: `合同号：${formatEmptyValue(item.customerCode)}\n批号：${formatEmptyValue(item.batchNumber)}`,
    showCancel: false
  });
};

// 添加数据格式化和验证的辅助函数
const formatTextWithLineBreak = (text) => {
  if (!text || typeof text !== 'string') return '-';
  // 将逗号替换为换行符
  return text.split(',').join('\n');
};

// 显示空值的默认文本
const formatEmptyValue = (value) => {
  if (value === null || value === undefined || value === '') {
    return '-';
  }
  return value;
};

// 查询搜索跳转
let handleSearch = () => {
  var data = {
    pageNum: 1,
    pageSize: 10,
  };
  listFeedback(data).then(res => {
    if (res.code == 200) {
      //设置列表数据
      list.value = res.rows;
    } else {
      uni.showToast({
        icon: 'none',
        title: "请求失败",
      });
      list.value = null;
    }

  })
}

// 新增
let handleAdd = () => {
  uni.navigateTo({url: '/pages/business/EQF/qualityFeedback/qualityFeedbackAdd'})
}


const mescrollRef = ref(null);
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: '刷新中...'
});

let cssFlag = ref(false);//控制样式
const mescrollInit = (mescroll) => {
  cssFlag.value = true;
  mescrollRef.value = mescroll;
};

// 下拉刷新
const downCallback = async (mescroll) => {
  try {
    setTimeout(async () => {
      const res = await getQualityFeedbackList(1, upOption.value.page.size);
      cssFlag.value = false;
      list.value = res.list;
      mescroll.resetUpScroll();
    }, 500);
  } catch (error) {
    mescroll.endErr();
  } finally {
    setTimeout(async () => {
      mescroll.endSuccess();
    }, 500);
  }
}
// 上拉加载更多
const upCallback = async (mescroll) => {
  try {
    setTimeout(async () => {
      const res = await getQualityFeedbackList(mescroll.num, mescroll.size);
      if (mescroll.num === 1) {
        list.value = res.list;
      } else {
        list.value.push(...res.list);
      }
      mescroll.endBySize(res.list.length, res.total);
    }, 500);
  } catch (error) {
    mescroll.endErr();
  }
}

// 获取数据列表 - 完善版本
const getQualityFeedbackList = (pageNum, pageSize) => {
  return new Promise(async (resolve, reject) => {
    try {
      // 检查分页参数是否存在
      if (!pageNum || !pageSize) {
        reject(new Error('分页参数不能为空'));
        return;
      }
      
      let param = {
        pageNum,
        pageSize,
        // 可能还需要传递informationId作为查询条件
        informationId: informationId.value
      };
      
      let res = await listFeedback(param);
      
      // 检查接口返回是否有效
      if (!res) {
        reject(new Error('接口返回为空'));
        return;
      }
      
      console.log('接口返回数据:', res);
      resolve({
        list: res.rows || [],
        total: res.total || 0
      });
    } catch (error) {
      console.error('请求过程出错:', error);
      reject(error);
    }
  });
};

 // 空依赖数组确保只在组件挂载时执行一次

let Loop = ref(0)
let now
const visistId = ref();
const cusName = ref();
const cusId = ref();
const status = ref();
const productType = ref();

function touchstart(item) {
  cusName.value = item.cusName
  cusId.value = item.cusId
  status.value = item.status
  id.value = item.id
  productType.value = item.productType
  now = new Date();
  clearInterval(Loop.value); //再次清空定时器，防止重复注册定时器
  Loop.value = setTimeout(() => {
    uni.showModal({
      title: '删除',
      content: '请问要删除本条消息吗？',
      success: (res) => {
        if (res.confirm) {
          const data = {
            num: 1,
            pageSize: 10,
            status: "录入"
          };
          const parm = {
            id: item.id
          };
          removeQualityFeedback(parm).then(res => {
            if (res.code == 500) {
              uni.showToast({
                icon: 'none',
                title: "存在明细项，不能直接删除！",
              });
            } else {
              uni.showToast({
                title: "删除成功",
                duration: 2000
              });
            }
            // 刷新内容
            upCallback()
          });
        }
      }
    });
  }, 750);

}

function touchend() {
  if(productType.value == '电阻器'){
    uni.navigateTo({
      url: "/pages/business/EQF/qualityFeedback/qualityFeedbackEnter?id=" + id.value + '&status=' + status.value
    })
  }else if(productType.value == '管壳'){
    uni.navigateTo({
      url: "/pages/business/EQF/qualityFeedback/gkQualityFeedbackEnter?id=" + id.value + '&status=' + status.value
    })
  }
    
  clearInterval(Loop.value);
}

//点击状态按钮
function chooseStatus(item) {
  console.log(item,"item")
  updateStatus(item).then(
      res => {
        if (res.code == 200) {
          uni.showToast({
            title: '提交成功',
            duration: 2000
          });
          setTimeout(function () {
            uni.navigateBack({
              success: () => {
              }
            })
          }, 500);
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'none',
          });
        }
      },
      rej => {
      }
  );
}

//保留点击状态，关闭长按的冒泡
function handleStatusTouchStart(e) {
  // e.stopPropagation(); // 阻止冒泡
  // e.preventDefault();  // 阻止默认行为（如滚动）
}

function handleStatusTouchEnd(e) {
  // e.stopPropagation();
  // e.preventDefault();
}

</script>

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

.search {
  display: flex;
}

.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;
}

.search .custom-search {
  width: 80%;

}

.search .custom-search.uni-searchbar {
  padding-right: 0 !important;
}

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

.white-bg {
  padding-bottom: 10rpx;
}

/* 新增样式：为列表行设置flex布局 */
.r-list {
  display: flex;
  justify-content: space-between;
  padding: 10rpx 0;
}

/* 新增样式：为左侧标签设置固定宽度 */
.r-left {
  width: 180rpx;
  font-weight: bold;
}

/* 新增样式：为右侧内容设置自动换行 */
.r-right {
  flex: 1;
  word-break: break-all;
  text-align: right;
  padding-left: 40rpx;
}

/* 保持边框样式 */
.border-bottom {
  height: 1rpx;
  background-color: #f0f0f0;
  margin: 0 20rpx;
}

/* 添加悬停效果 */
.detail-info {
  text-align: left;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  cursor: pointer;
  transition: background-color 0.3s;
  padding: 10rpx;
  border-radius: 8rpx;
}

.detail-info:active {
  background-color: rgba(111, 162, 248, 0.1);
}
</style>