<template>
  <view class="container">
    <!-- 搜索栏 -->
    <view class="info-row btn-panel search-bar">
      <view class="search-input">
		  <input type="text" v-model="productNo" placeholder="请输入产品号"/>
	  </view>
      <view class="scan-btn" @click="scanQRCode">
        <uni-icons type="scan" size="32" color="#00aaff"></uni-icons>
      </view>
    </view>
    <!-- 按钮面板 -->
    <view class="info-row btn-panel">
      <button class="btn btn-first" @click="download">
        下载数据
      </button>
    </view>
    <!-- 列表内容 -->
    <!-- #ifdef APP -->
    <scroll-view style="flex:1">
    <!-- #endif -->
      <view class="download-card" v-for="(item, index) in downloads" :key="index" >
		<view @click="enterItem(item.pdid)">
			<view class="info-row">
			  <text class="label">工作令：</text>
			  <text class="value">{{ item.workorder }}</text>
			</view>
			<view class="info-row">
			  <text class="label">产品名称：</text>
			  <text class="value">{{ item.invname }}</text>
			</view>
			<view class="info-row">
			  <text class="label">物料编码：</text>
			  <text class="value">{{ item.graphid }}</text>
			</view>
			<view class="info-row">
			  <text class="label">路卡号：</text>
			  <text class="value">{{ item.cardno }}</text>
			</view>
			<view class="info-row">
			  <text class="label">产品码：</text>
			  <text class="value">{{ item.productno }}</text>
			</view>
			<view class="info-row">
			  <text class="label">最近更新时间：</text>
			  <text class="value">{{ item.updatetime == "" ? item.createtime : item.updatetime }}</text>
			</view>
			<view class="info-row">
			  <text class="label">进度：</text>
			  <text class="process-value" :class="{
			    'bg-green': item.statusRecordCount === item.totalRecord,
			    'bg-yellow': item.statusRecordCount < item.totalRecord,
			    'bg-black': item.statusRecordCount === 0
			  }"> {{ item.statusRecordCount }} / {{ item.totalRecord }} </text>
			</view>
		</view>  
		
		<view class="info-row">
			<button class="btn btn-second" @click="upload(item.statusRecordCount === item.totalRecord)">
			  上传数据
			</button>
		</view>
      </view>
	  
    <!-- #ifdef APP -->
    </scroll-view>
    <!-- #endif -->
  </view>
</template>

<script setup>
  import { ref, reactive } from 'vue'
  import { getRecordInfoList } from '@/api/work';
  import { downloadDataFromAPI, uploadDataToAPI } from '@/utils/dataProcessor';

  // 产品号输入框数据
  const productNo = ref('');
  
  const backPressOptions = reactive({
    from: 'backbutton'
  } as OnBackPressOptions)

  onBackPress((options : OnBackPressOptions) : boolean | null => {
    console.log('onBackPress', options)
    // 使用reLaunch代替switchTab，避免多层跳转时的闪回问题
    // reLaunch会关闭所有页面并打开到目标页面，适合需要完全重置导航栈的场景
    uni.reLaunch({
      url: `/pages/work/index`,
    })
    // 返回true表示拦截默认返回行为
    return true
  })

  type Download = {
    pdid : number,
    workorder : string,
    invname : string,
    productno : string,
    graphid : string,
    cardno : string,
    processno : string,
    updatetime : string,
    createtime: string,
    progress : string,
    status : number,
    totalRecord : number,
    statusRecordCount : number,
    status4RecordCount : number
  }

  var initDownloads = [] as Download[]
  var downloads = ref<Download[]>([]);
  const map = ref(new Map<number, string>([[1, '未执行'], [2, '执行中'], [3, '执行完'], [4, '有错误']]))

  // #ifdef APP-ANDROID
  getRecordInfoList(null).then((res : UTSJSONObject) => {
    console.log(res)
    let dataList = res?.['data'] as UTSJSONObject[] ?? Array<UTSJSONObject>()
    if (dataList != null && dataList.length > 0) {
      dataList.forEach(item => {
        if (item != null) {
          let download = JSON.parse<Download>(item.toJSONString());
          if (download != null) {
            initDownloads.push(download)
          }
        }
      });
    }
    downloads.value = initDownloads
    console.log(initDownloads)
  })
  // #endif

  // #ifdef H5
  downloads = [{
    pdid: 1,
    workorder: "632-P-01",
    invname: "箱间段",
    productno: "1CFA1040-00#S",
    cardno: "LK20230707070012",
    processno: "Pb/XXX-E11",
    updatetime: "2025-06-23",
    progress: "3/3",
    status: 3

  }, {
    pdid: 2,
    workorder: "712-SY-10-6",
    invname: "级间架",
    productno: "1XA1020-00A",
    cardno: "LK20250215003",
    processno: "Pb/XXX-E11",
    updatetime: "2025-08-25",
    progress: "2/4",
    status: 2
  }, {
    pdid: 3,
    workorder: "712-SY-10-6",
    invname: "级间架",
    productno: "1XA1020-00A",
    cardno: "LK20250215003",
    processno: "Pb/XXX-E11",
    updatetime: "2025-08-25",
    progress: "0/4",
    status: 1
  }] as Download[];

  // #endif

  const download = async (e : any) => {
    console.log("开始下载...")
    // 调用数据处理工具中的方法下载数据
	if(productNo.value == null || productNo.value == '') {
		uni.showToast({
		  title: '请先扫描或者输入产品号',
		  icon: 'error'
		});
		return
	}
	
    await downloadDataFromAPI(productNo.value, () => {
      // 回调函数中执行刷新，确保数据都保存好，进度条跑完
      uni.reLaunch({ url: '/pages/work/record/InfoList' })
    }).then((res) => {
      // 移除这里的刷新逻辑，避免过早刷新
    })
  }
  
  const upload = async (e : any) => {
	if(e == false) {
		uni.showToast({
		  title: '当前任务还未完成！',
		  icon: 'error'
		});
	}
    console.log("开始上传...")
    uploadDataToAPI(productNo.value, () => {
	  // 回调函数中执行刷新，确保数据都保存好，进度条跑完
	  uni.reLaunch({ url: '/pages/work/record/InfoList' })
	}).then((res) => {
	  // 移除这里的刷新逻辑，避免过早刷新
	  // 处理断点续传
	})

  }
  
  const enterItem = (id : number) => {
    uni.navigateTo({
      url: `/pages/work/record/InfoDetail?id=${id}`
    });
  }
  
  // 扫描二维码功能
  const scanQRCode = () => {
    uni.scanCode({
      success: (res) => {
        // 扫描成功，将结果填充到输入框
        productNo.value = res.result;
        console.log('扫描结果:', res.result);
      },
      fail: (err) => {
        console.error('扫描失败:', err);
        uni.showToast({
          title: '扫描失败，请重试',
          icon: 'error'
        });
      }
    });
  }

  defineExpose({
    backPressOptions
  })
</script>

<style scope>
  .container {
    padding: 24rpx;
    background-color: #f0f4f8;
    flex: 1;
    display: flex;
    flex-direction: column;
    font-family: "PingFang SC", "Helvetica Neue", Helvetica, Arial, sans-serif;
    /* #ifndef APP-ANDROID */
    min-height: 100vh;
    /* #endif */
    height: 120rpx;
  }

  .search-bar {
	  background-color: #ffffff;
	  border-radius: 10rpx;
	  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

/* 搜索输入框：占满容器剩余空间，放在按钮左侧 */
	.search-input {
	  /* 清除默认输入框样式 */
	  border: none;
	  background: transparent;
	  width: 70%;
	  margin-left: 10rpx;
	}

/* 扫描按钮：放在输入框右侧，距离最右10rpx */
	.scan-btn {
	  justify-content: center;
	  align-items: center; /* 新增：按钮内部图标垂直居中 */
	  /* 关键：右侧10rpx边距，实现"距离最右10rpx" */
	  margin-left: auto; /* 自动推到flex容器最右侧 */
	  margin-right: 10rpx; /* 与容器右边缘保持10rpx间距 */
	}

  .download-card {
    background: #ffffff;
    border-radius: 20rpx;
    padding: 24rpx 32rpx;
    box-shadow: 0 8rpx 15rpx rgba(0, 43, 92, 0.1);
    display: flex;
    flex-direction: column;
    margin-bottom: 20rpx;
    margin-top: 40rpx;
    margin-left: 20rpx;
    margin-right: 20rpx;
  }

  .download-card .view {
    margin-bottom: 16rpx;
  }

  /* 信息行 */
  .info-row {
    display: flex;
    flex-direction: row;
    font-size: 28rpx;
    color: #33475b;
    align-items: center;
  }

  .info-row>.label {
    margin-left: 10rpx;
  }

  .info-row>.value {
    margin-left: 10rpx;
  }

  .btn-panel {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-left: 5rpx;
    margin-right: 5rpx;
  }

  .label {
    font-weight: bold;
    color: #102a43;
    min-width: 100rpx;
  }

  .value {
    flex: 1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .btn {
    align-self: flex-end;
    background-color: #00aaff;
    color: #fff;
    border: none;
    border-radius: 32rpx;
    padding: 2rpx 30rpx;
    font-size: 24rpx;
    font-weight: bold;
    /* #ifndef APP-ANDROID */
    transition: background-color 0.3s ease;
    /* #endif */
    margin-top: 30rpx;
  }

  .process-value {
    width: 120rpx;
    min-width: 100rpx;
    text-align: center;
    border-radius: 10rpx;
  }

  .bg-green {
    background-color: seagreen;
  }

  .bg-yellow {
    background-color: yellow;
  }

  .bg-black {
    background-color: #102a43;
  }

  .btn-first {
    margin-left: 5rpx;
  }

  .btn-second {
    margin-right: 5rpx;
	margin-left: auto;
  }
  
</style>