<template>
  <view class="order-detail-view">
    <!-- 页面切换 -->
    <view 
      class="page-item" 
      v-show="activeIndex === 0"
    >
      <PageOne 
        :order-detail="orderDetail" 
        :order-id="orderId"
        :current-receipt="currentReceipt"
        @next="handleNext"
      />
    </view>
    
    <view 
      class="page-item" 
      v-show="activeIndex === 1"
    >
      <PageTwo 
        :order-detail="orderDetail" 
        :order-id="orderId"
        :current-receipt="currentReceipt"
        :follow-up-list="followUpList"
        @next="handleNext"
        @update-file-ids="handleUpdateFileIds"
      />
    </view>
    
    <view 
      class="page-item" 
      v-show="activeIndex === 2"
    >
      <PageThree 
        :order-detail="orderDetail" 
        :order-id="orderId"
        :current-receipt="currentReceipt"
        @next="handleNext"
        @save="handleNeedSave"
        @confirm-pay="handleConfirmPay"
        @update-file-ids="handleUpdateFileIds"
        ref="pageThreeRef"
      />
    </view>
    
    <view 
      class="page-item" 
      v-show="activeIndex === 3"
    >
      <PageFour 
        :order-detail="orderDetail"
        :current-receipt="currentReceipt"
        @next="handleNext"
        @confirm-warehouse="handleConfirmWarehouse"
      />
    </view>

    <!-- 页面导航 -->
    <ul class="page-navigation">
      <li 
        v-for="(tab, index) in tabs" 
        :key="index"
        :class="{ 'active': activeIndex === index }"
        @click="handleTabClick(index)"
      >
        {{ tab }}
      </li>
    </ul>
  </view>
</template>

<script>
import PageOne from './PageOne.vue'
import PageTwo from './PageTwo.vue'
import PageThree from './PageThree.vue'
import PageFour from './PageFour.vue'

export default {
  name: 'OrderDetailView',
  components: {
    PageOne,
    PageTwo,
    PageThree,
    PageFour
  },
  props: {
    orderDetail: {
      type: Object,
      default: () => ({})
    },
    topInfo: {
      type: Object,
      default: () => ({})
    },
    orderId: {
      type: String,
      default: ''
    },
    currentReceipt: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      activeIndex: 0,
      tabs: ['一', '二', '三', '四'],
      // 表单数据
      formData: {
        formOne: {},
        formTwo: {},
        formThree: {},
        formFour: {}
      },
      pageThreeForm: {},
      fileIds: '',
      // 跟进记录
      followUpList: []
    }
  },
  watch: {
    orderDetail: {
      handler(newVal) {
        if (newVal && newVal.clueId) {
          this.loadFollowUpList()
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    /**
     * 加载跟进记录
     */
    async loadFollowUpList() {
      try {
        const res = await uni.$u.api.getDuplicateOrderFollowListByClueId({
          clueId: this.orderDetail.clueId
        })
        const data = res.data || {}
        const followUpList = []
        for (const key in data) {
          followUpList.push(...(data[key] || []))
        }
        this.followUpList = followUpList
      } catch (error) {
        console.error('获取跟进记录失败:', error)
        uni.$u.toast('获取跟进记录失败')
      }
    },

    /**
     * 处理下一步
     */
    handleNext({ nowPage, form }) {
      this.activeIndex++
      if (nowPage) {
        this.formData[nowPage] = form
      }
      // 当切换到第三页时，更新第三页的图片列表
      if (nowPage === 'formTwo' && this.$refs.pageThreeRef) {
        this.$refs.pageThreeRef.refreshImageList()
      }
    },

    /**
     * 处理保存
     */
    handleNeedSave({ nowPage, form, fileIds }) {
      this.pageThreeForm = form
      this.fileIds = fileIds
    },

    /**
     * 处理确认支付
     */
    async handleConfirmPay() {
      try {
        const response = await uni.$u.api.saveOrderFileAndTransfer({
          id: this.orderId,
          clueId: this.orderDetail.clueId
        })
        uni.$u.toast(response.msg || '支付成功')
      } catch (error) {
        console.error('支付失败:', error)
        uni.$u.toast(`支付失败：${error}`)

        //支付失败回滚支付信息
        await uni.$u.api.updateClueOrderForm({
          id: this.orderDetail.id,
          paymentMethod: ''
        })
      }
    },

    /**
     * 处理确认入库
     */
    async handleConfirmWarehouse({ warehouseInfo }) {
      try {
        const params = {
          searchValue: this.orderDetail.searchValue,
          createBy: this.orderDetail.createBy,
          createTime: this.orderDetail.createTime,
          updateBy: this.orderDetail.updateBy,
          updateTime: this.orderDetail.updateTime,
          params: this.orderDetail.params,
          id: this.currentReceipt.id,
          sendFormId: this.orderId,
          clueId: this.orderDetail.clueId,
          item: warehouseInfo.item || '',
          code: warehouseInfo.codeStorage || '',
          phone: this.orderDetail.phone,
          tableFee: warehouseInfo.watchPrice || '',
          benefitFee: warehouseInfo.benefitFee || '',
          freight: warehouseInfo.freight || '',
          checkCodeFee: warehouseInfo.checkCodeFee || '',
          receiptRemark: `${warehouseInfo.remarks || ''};${warehouseInfo.uploadedImage || ''}`,
          repairAmount: warehouseInfo.repairAmount || '',
          grossPerformance: warehouseInfo.grossPerformance || '',
          expressOrderNo: warehouseInfo.expressOrderNo || '',
          fileIds: this.fileIds,
          customerServiceName: warehouseInfo.customerServiceName || '1',
          deptId: this.orderDetail.deptId,
          category: warehouseInfo.category || this.orderDetail.category,
          delFlag: this.orderDetail.delFlag,
          idCard: this.pageThreeForm.idNumber || '',
          paymentMethod: '小葫芦线上支付',
          bankCardNumber: this.pageThreeForm.bankAccount || '',
          bankName: this.pageThreeForm.bankName || '',
          customName: this.pageThreeForm.customName || ''
        }

        if (this.currentReceipt.id) {
          await uni.$u.api.updateReceiptForm(params)
        } else {
          await uni.$u.api.addReceiptForm(params)
        }
        uni.$u.toast('入库成功')
      } catch (error) {
        console.error('入库失败:', error)
        uni.$u.toast('入库失败')
      }
    },

    /**
     * 处理标签点击
     */
    handleTabClick(index) {
      this.activeIndex = index
      // 切换到第三页时刷新图片列表
      if (index === 2 && this.$refs.pageThreeRef) {
        this.$refs.pageThreeRef.refreshImageList()
      }
    },

    /**
     * 更新 fileIds
     */
    handleUpdateFileIds(fileIds) {
      if (this.currentReceipt) {
        this.$set(this.currentReceipt, 'fileIds', fileIds)
        this.fileIds = fileIds
      }
    }
  }
}
</script>

<style scoped lang="scss">
.order-detail-view {
  padding: 20rpx;
  min-height: calc(100vh - 200rpx);
}

.page-item {
  width: 100%;
}

.page-navigation {
  position: fixed;
  right: 20rpx;
  top: 40%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  list-style: none;
  color: #000;
  font-size: 20rpx;
  font-weight: 800;
  z-index: 100;

  li {
    opacity: 0.7;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    border-radius: 50%;
    width: 70rpx;
    height: 70rpx;
    line-height: 70rpx;
    text-align: center;
    margin-bottom: 20rpx;
    transition: all 0.3s ease-in-out;
    font-weight: 800;
    box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
    cursor: pointer;

    &.active {
      color: #fff;
      opacity: 1;
      background-color: rgb(37 99 235 / 1);
    }

    &:hover {
      opacity: 0.9;
      transform: scale(1.05);
    }
  }
}
</style>
