<template>
  <view class="page">
    <text class="title">签退完成</text>
    <view class="card"><text class="label">执行摘要</text><text class="val">{{ completedCount }} / {{ totalCount }} 项已完成</text></view>
    <textarea v-model="summary" placeholder="服务总结（选填）" class="textarea" />
    <view class="card"><text class="label">签退定位</text><text v-if="loc" class="val">经度 {{ loc.longitude.toFixed(6) }} 纬度 {{ loc.latitude.toFixed(6) }}</text></view>
    <button @click="submit" :loading="submitting" class="btn">提交完成</button>
  </view>
</template>

<script>
import { apiPost, getLocation, apiGet } from '@/common/api.js';
import { stopTrajectory } from '@/common/api.js';
import { OfflineQueue } from '@/common/offline.js';

const offline = new OfflineQueue();

export default {
  data() { return { workOrderId: 0, summary: '', loc: null, submitting: false, items: [] }; },
  computed: {
    totalCount() { return this.items.length; },
    completedCount() { return this.items.filter(i => i.status !== 'PENDING').length; }
  },
  async onLoad(options) {
    this.workOrderId = parseInt(options.id) || 0;
    try {
      const res = await apiGet('/delivery/work-orders/' + this.workOrderId + '/detail');
      this.items = res.data?.data?.items || [];
    } catch(e) {}
    try { this.loc = await getLocation(); } catch(e) {}
  },
  methods: {
    async submit() {
      stopTrajectory();
      this.submitting = true;
      const records = this.items.filter(i => i.status !== 'PENDING').map(i => ({ planItemId: i.id, status: i.status, notes: '' }));
      const payload = {
        executionRecords: records,
        serviceSummary: this.summary,
        signOffLatitude: this.loc?.latitude || 0,
        signOffLongitude: this.loc?.longitude || 0
      };
      try {
        const res = await apiPost('/work-orders/' + this.workOrderId + '/finish', payload);
        if (res.data.code === 200) { uni.showToast({ title: '服务完成' }); setTimeout(() => uni.navigateBack(), 800); }
        else { uni.showToast({ title: res.data.message, icon: 'none' }); }
      } catch(e) {
        offline.add({ path: '/work-orders/' + this.workOrderId + '/finish', data: payload });
        uni.showToast({ title: '已缓存，待补传', icon: 'none' });
      }
      this.submitting = false;
    }
  }
};
</script>

<style>
.page { padding: 24rpx; background: #F8F8F8; min-height: 100vh; }
.title { font-size: 36rpx; font-weight: 700; display: block; margin-bottom: 24rpx; }
.card { background: #fff; border-radius: 16rpx; padding: 24rpx; margin-bottom: 16rpx; }
.label { font-size: 26rpx; color: #999; display: block; margin-bottom: 8rpx; }
.val { font-size: 28rpx; color: #333; }
.textarea { width: 100%; height: 150rpx; border: 1px solid #ddd; border-radius: 12rpx; padding: 16rpx; font-size: 28rpx; margin-bottom: 24rpx; background: #fff; }
.btn { background: #155EEF; color: #fff; border-radius: 12rpx; padding: 24rpx; font-size: 32rpx; font-weight: 600; }
</style>
