<template>
  <view class="page-three-container">
    <!-- 支付信息卡片 -->
    <view class="info-card">
      <view class="info-card-title">支付信息</view>
      <u-row class="info-row" justify="space-between">
        <u-col span="5.8">
          <view class="info-label">开户人</view>
          <u-input v-model="paymentInfo.customName" placeholder="请输入开户人姓名" class="info-input"
            @blur="handleCustomNameInput" />
        </u-col>
        <u-col span="5.8">
          <view class="info-label">银行名称</view>
          <u-input v-model="paymentInfo.bankName" placeholder="请输入银行名称" class="info-input"
            @blur="handleBankNameInput" />
        </u-col>
      </u-row>
      <u-row class="info-row">
        <u-col span="12">
          <view class="info-label">银行账号</view>
          <u-input v-model="paymentInfo.bankAccount" placeholder="请输入银行账号" class="info-input" type="number"
            @input="handleBankAccountInput" />
        </u-col>
      </u-row>
      <u-row class="info-row">
        <u-col span="12">
          <view class="info-label">身份证号</view>
          <u-input v-model="paymentInfo.idNumber" placeholder="请输入身份证号" class="info-input"
            @blur="handleIdNumberInput" />
        </u-col>
      </u-row>
      <u-row class="info-row">
        <u-col span="12">
          <view class="info-label">支付方式选择</view>
          <u-radio-group iconPlacement="left" v-model="paymentMethodRadio" placement="row"
            @change="handlePaymentMethodRadioChange">
            <u-radio shape="circle" label="小葫芦线上支付" name="online" />
            <u-radio shape="circle" label="线下支付" name="offline" />
          </u-radio-group>
        </u-col>
      </u-row>
      <u-row class="info-row">
        <u-col span="12">
          <view class="info-label">支付方式</view>
          <u-input :disabled="paymentMethodRadio === 'online'" v-model="paymentMethod" placeholder="请输入支付方式"
            class="info-input" />
        </u-col>
      </u-row>
    </view>

    <!-- 高清实物图卡片 -->
    <view class="card-wrap">
      <view class="detail-image-section">
        <view class="detail-image-header">
          <text class="detail-image-title">高清实物图（拖拽排序）</text>
        </view>
        <view class="detail-image-content">
          <view class="detail-image-list">
            <view v-for="(item, index) in displayImages" :key="item.id || `detail-${index}`" class="detail-image-item"
              :class="{
                'dragging': draggingIndex === index,
                'can-drop': canDropIndex === index && draggingIndex !== index
              }" :style="draggingIndex === index ? draggingStyle : ''" @touchstart.stop="onTouchStart($event, index)"
              @touchmove.stop="onTouchMove($event, index)" @touchend.stop="onTouchEnd">
              <PicComp :src="item.fileUrl" @needPreviewPic="previewImageDetail" />
              <view class="image-type-tag">{{ getImageType(index) }}</view>
              <view class="detail-delete-btn" @click.stop="handleHideImage(item, index)">
                ×
              </view>
            </view>
            <view class="detail-upload-btn" @click="handleUploadImage">
              <u-icon name="plus" size="40rpx" color="#999" />
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 支付总额卡片 -->
    <view class="card-wrap payment-card">
      <view class="payment-section">
        <view class="payment-total-container">
          <text class="payment-label">支付总额</text>
          <u-input v-model="paymentAmount" class="payment-amount" type="number" decimal="2" prefix="￥" />
        </view>
        <view class="payment-buttons-row">
          <view class="payment-button" @click="handleUnpaidClick">
            <u-icon name="star" size="40rpx" color="#ff9500" />
            <text class="button-text">未收</text>
          </view>
          <view class="payment-button" @click="handleFollowUpClick">
            <u-icon name="chat" size="40rpx" color="#108cff" />
            <text class="button-text">待跟进</text>
          </view>
        </view>
        <view class="pay-now-button" @click="handlePayNowClick">
          <text class="button-text">立即支付</text>
        </view>
      </view>
    </view>

    <!-- 下一步按钮 -->
    <u-button class="next-btn" @click="handleNext" type="primary" size="middle">
      下一步
    </u-button>

    <!-- 未收评级模态窗 -->
    <u-modal showCancelButton showConfirmButton @confirm="confirmUnpaid" @cancel="unpaidModalVisible = false"
      :show="unpaidModalVisible" title="未收评级">
      <view class="modal-content">
        <u-rate v-model="unpaidRating" :count="5" :size="50" active-color="#ff9500" />
      </view>
    </u-modal>

    <!-- 待跟进模态窗 -->
    <u-modal showCancelButton showConfirmButton @confirm="confirmFollowUp" @cancel="followUpModalVisible = false"
      :show="followUpModalVisible" title="填写跟进细节">
      <view class="modal-content">
        <u--textarea v-model="followUpNotes" placeholder="请输入情况" confirm-type="done"
          style="width: 100%; margin-bottom: 30rpx;" />
      </view>
    </u-modal>

    <!-- 确认支付模态窗 -->
    <u-modal showCancelButton showConfirmButton @confirm="confirmRiskWarning" @cancel="riskWarningModalVisible = false"
      confirmText="确认并继续付款" :show="riskWarningModalVisible" title="付款警示" :content="'湖南耒阳地区身份证号请确认！'">
    </u-modal>

    <u-modal :show="payNowModalVisible" title="确认支付信息" :showConfirmButton="false">
      <view class="modal-content">
        <view class="payment-amount-display">￥{{ paymentAmount }}</view>
        <view class="payment-info-section">
          <view class="info-item">
            <text class="info-label">收款姓名：</text>
            <text class="info-value">{{ paymentInfo.customName || '未填写' }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">开户银行：</text>
            <text class="info-value">{{ paymentInfo.bankName || '未填写' }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">银行卡号：</text>
            <text class="info-value">{{ paymentInfo.bankAccount || '未填写' }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">支付方式：</text>
            <text class="info-value">{{ paymentMethod || '未填写' }}</text>
          </view>
        </view>
        <u-button type="primary" size="large" @click="confirmTransfer" style="margin-top: 40rpx;">
          确认转账
        </u-button>
        <u-button type="primary" :plain="true" @click="payNowModalVisible = false" size="large"
          style="margin-top: 20rpx;">
          取消
        </u-button>
      </view>
    </u-modal>
  </view>
</template>

<script>
import PicComp from './PicComp.vue'
import imageUpload from '../utils/imageUpload.js'

export default {
  name: 'PageThree',
  components: {
    PicComp
  },
  props: {
    orderDetail: {
      type: Object,
      default: () => ({})
    },
    orderId: {
      type: String,
      default: ''
    },
    currentReceipt: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      paymentInfo: {
        customName: '',
        bankName: '',
        bankAccount: '',
        idNumber: ''
      },
      paymentMethodRadio: 'offline',
      paymentMethod: '',
      paymentAmount: '0.00',
      detailImages: [],
      // 拖拽相关
      draggingIndex: -1,
      canDropIndex: -1,
      startX: 0,
      startY: 0,
      currentX: 0,
      currentY: 0,
      // 模态窗
      unpaidModalVisible: false,
      followUpModalVisible: false,
      payNowModalVisible: false,
      riskWarningModalVisible: false,
      unpaidRating: 0,
      followUpNotes: ''
    }
  },
  computed: {
    // 显示前6个图片用于拖拽
    displayImages() {
      return this.detailImages.slice(0, 6)
    },
    // 拖拽时的样式
    draggingStyle() {
      if (this.draggingIndex === -1) return ''
      return {
        transform: `translate(${this.currentX - this.startX}px, ${this.currentY - this.startY}px)`,
        zIndex: 1000
      }
    }
  },
  watch: {
    orderDetail: {
      handler(newVal) {
        if (newVal) {
          this.paymentInfo.customName = newVal.customName || ''
          this.paymentInfo.bankName = newVal.bankName || ''
          this.paymentInfo.bankAccount = newVal.bankCardNumber || ''
          this.paymentInfo.idNumber = newVal.idCard || ''
          this.initPaymentMethod(newVal.paymentMethod)
        }
      },
      deep: true,
      immediate: true
    },
    currentReceipt: {
      handler(newVal) {
        if (newVal) {
          this.paymentAmount = newVal.tableFee || '0.00'
          this.loadDetailImages()
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    /**
     * 刷新图片列表（供父组件调用）
     */
    async refreshImageList() {
      await this.loadDetailImages()
    },

    /**
     * 加载细节图
     */
    async loadDetailImages() {
      if (!this.currentReceipt.id || !this.orderDetail.itemBrand) return

      try {
        const list = await imageUpload.getFileList(
          '2',
          '3',
          this.currentReceipt.id,
          this.orderDetail.itemBrand,
          this.currentReceipt.clueId
        )

        // 按照 fileIds 排序
        if (this.currentReceipt.fileIds && list && list.length > 0) {
          const sortedIds = this.currentReceipt.fileIds.split(',')
          list.sort((a, b) => {
            const indexA = sortedIds.indexOf(a.id)
            const indexB = sortedIds.indexOf(b.id)

            // 如果都不在列表中，保持原顺序
            if (indexA === -1 && indexB === -1) return 0
            // 如果 a 不在列表中，放到后面
            if (indexA === -1) return 1
            // 如果 b 不在列表中，放到后面
            if (indexB === -1) return -1
            // 都在列表中，按 index 排序
            return indexA - indexB
          })
        }

        this.detailImages = list || []
      } catch (error) {
        console.error('加载细节图失败:', error)
      }
    },

    /**
     * 初始化支付方式
     */
    initPaymentMethod(value) {
      if (value === '小葫芦线上支付') {
        this.paymentMethod = '小葫芦线上支付'
        this.paymentMethodRadio = 'online'
      } else {
        this.paymentMethod = value || ''
        this.paymentMethodRadio = 'offline'
      }
    },

    /**
     * 支付方式选择改变
     */
    handlePaymentMethodRadioChange(value) {
      if (value === 'online') {
        this.paymentMethod = '小葫芦线上支付'
      } else {
        this.paymentMethod = ''
      }
    },

    /**
     * 开户人输入处理 - 只允许中文
     */
    handleCustomNameInput(value) {
      // 只保留中文字符（包括中文标点）
      const chineseReg = /[^\u4e00-\u9fa5]/g
      this.paymentInfo.customName = String(value || '').replace(chineseReg, '')
    },

    /**
     * 银行名称输入处理 - 只允许中文
     */
    handleBankNameInput(value) {
      // 只保留中文字符（包括中文标点）
      const chineseReg = /[^\u4e00-\u9fa5]/g
      this.paymentInfo.bankName = String(value || '').replace(chineseReg, '')
    },

    /**
     * 银行账号输入处理 - 只允许数字
     */
    handleBankAccountInput(value) {
      // 只保留数字
      const numberReg = /[^\d]/g
      this.paymentInfo.bankAccount = String(value || '').replace(numberReg, '')
    },

    /**
     * 身份证号输入处理 - 允许数字和X
     */
    handleIdNumberInput(value) {
      // 只保留数字和X
      const reg = /[^\dxX]/g
      this.paymentInfo.idNumber = String(value || '').replace(reg, '')
    },

    /**
     * 获取图片类型
     */
    getImageType(index) {
      const types = ['正面', '反面', '侧面', '扣子', '编号']
      return types[index] || `细节${index - 4}`
    },

    /**
     * 触摸开始
     */
    onTouchStart(event, index) {
      if (this.draggingIndex !== -1) return
      this.draggingIndex = index
      const touch = event.touches[0]
      this.startX = touch.clientX
      this.startY = touch.clientY
      this.currentX = touch.clientX
      this.currentY = touch.clientY
    },

    /**
     * 触摸移动
     */
    onTouchMove(event, index) {
      if (this.draggingIndex === -1 || this.draggingIndex !== index) return
      const touch = event.touches[0]
      this.currentX = touch.clientX
      this.currentY = touch.clientY
      this.findTargetIndex(touch.clientX, touch.clientY)
    },

    /**
     * 触摸结束
     */
    async onTouchEnd() {
      if (this.draggingIndex === -1) return

      if (this.canDropIndex !== -1 && this.canDropIndex !== this.draggingIndex) {
        // 交换位置
        const images = [...this.detailImages]
        const temp = images[this.draggingIndex]
        images[this.draggingIndex] = images[this.canDropIndex]
        images[this.canDropIndex] = temp
        this.detailImages = images
      }

      this.resetDragState()

      //每次拖拽结束后把新的顺序传送给接口
      const fileIds = this.detailImages.map(item => item.id).join(',')
      await uni.$u.api.updateReceiptForm({
        id: this.currentReceipt.id,
        fileIds: fileIds
      })
      this.$emit('update-file-ids', fileIds)
    },

    /**
     * 查找目标索引
     */
    findTargetIndex(x, y) {
      const query = uni.createSelectorQuery().in(this)
      query.selectAll('.detail-image-item').boundingClientRect((rects) => {
        if (!rects || rects.length === 0) return
        let targetIndex = -1
        for (let i = 0; i < rects.length; i++) {
          if (i === this.draggingIndex) continue
          const rect = rects[i]
          if (x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom) {
            targetIndex = i
            break
          }
        }
        this.canDropIndex = targetIndex
      }).exec()
    },

    /**
     * 重置拖拽状态
     */
    resetDragState() {
      this.draggingIndex = -1
      this.canDropIndex = -1
      this.startX = 0
      this.startY = 0
      this.currentX = 0
      this.currentY = 0
    },

    /**
     * 上传图片
     */
    async handleUploadImage() {
      try {
        const filePaths = await imageUpload.chooseImage(9)
        const uploadResults = await imageUpload.uploadFiles(filePaths)
        await imageUpload.bindOrderFile(
          this.currentReceipt.clueId,
          this.currentReceipt.id,
          '3',
          uploadResults
        )
        await this.loadDetailImages()

        //上传新图片完成之后也要把新数据给接口
        const fileIds = this.detailImages.map(item => item.id).join(',')
        await uni.$u.api.updateReceiptForm({
          id: this.currentReceipt.id,
          fileIds: fileIds
        })
        this.$emit('update-file-ids', fileIds)

      } catch (error) {
        console.error('上传失败:', error)
      }
    },

    /**
     * 隐藏图片
     */
    async handleHideImage(item, index) {
      const itemIndex = this.detailImages.findIndex(img => img.id === item.id || img.fileUrl === item.fileUrl)
      if (itemIndex !== -1) {
        this.detailImages.splice(itemIndex, 1)

        // 更新 fileIds
        const fileIds = this.detailImages.map(item => item.id).join(',')
        try {
          await uni.$u.api.updateReceiptForm({
            id: this.currentReceipt.id,
            fileIds: fileIds
          })
          this.$emit('update-file-ids', fileIds)
          uni.$u.toast('图片已隐藏')
        } catch (error) {
          console.error('更新失败:', error)
        }
      }
    },

    /**
     * 预览图片
     */
    previewImageDetail(src) {
      const urlList = this.detailImages.map(item => item.fileUrl)
      uni.previewImage({
        urls: urlList,
        current: src
      })
    },

    /**
     * 未收点击
     */
    handleUnpaidClick() {
      this.unpaidModalVisible = true
    },

    /**
     * 待跟进点击
     */
    handleFollowUpClick() {
      this.followUpModalVisible = true
    },

    /**
     * 立即支付点击
     */
    async handlePayNowClick() {
      // 保存支付信息
      await uni.$u.api.updateReceiptForm({
        id: this.currentReceipt.id,
        tableFee: this.paymentAmount,
        fileIds: this.detailImages.map(item => item.id).join(',')
      })

      await uni.$u.api.updateClueOrderForm({
        id: this.orderDetail.id,
        customName: this.paymentInfo.customName || '',
        bankName: this.paymentInfo.bankName || '',
        bankCardNumber: this.paymentInfo.bankAccount || '',
        idCard: this.paymentInfo.idNumber || '',
        // paymentMethod: this.paymentMethod || ''
      })

      if (!this.paymentInfo.customName || !this.paymentInfo.bankName ||
        !this.paymentInfo.bankAccount || !this.paymentInfo.idNumber || !this.paymentMethod) {
        uni.$u.toast('请填写完整的支付信息')
        return
      }
      if (this.paymentAmount <= 0) {
        uni.$u.toast('请填写正确的支付总额')
        return
      }

      //判断当前账号是否敏感地区
      if (String(this.paymentInfo.idNumber).startsWith('430481')) {
        this.riskWarningModalVisible = true
        return
      }

      this.payNowModalVisible = true
    },

    /**
     * 确认风险警示
     */
    confirmRiskWarning() {
      this.riskWarningModalVisible = false
      this.payNowModalVisible = true
    },

    /**
     * 确认转账
     */
    async confirmTransfer() {
      this.payNowModalVisible = false

      await uni.$u.api.updateClueOrderForm({
        id: this.orderDetail.id,
        paymentMethod: this.paymentMethod || ''
      })
      //如果是小葫芦线上刚支付就调用接口，如果不是小葫芦线上支付就不要调用接口，直接点击下一步
      if (this.paymentMethod === '小葫芦线上支付') {
        this.$emit('confirm-pay')
      } else {
        this.handleNext()
      }
    },

    /**
     * 确认未收
     */
    async confirmUnpaid() {
      try {
        await uni.$u.api.addOrderFollow({
          orderId: this.orderId,
          content: `未收评分_${this.unpaidRating}`
        })
        await uni.$u.api.oderForm({
          status: '4',
          id: this.orderId
        })
        uni.$u.toast('提交未收评级成功')
        this.unpaidModalVisible = false
      } catch (error) {
        console.error('提交失败:', error)
        uni.$u.toast('提交失败')
      }
    },

    /**
     * 确认跟进
     */
    async confirmFollowUp() {
      try {
        await uni.$u.api.addOrderFollow({
          orderId: this.orderId,
          content: `待跟进_${this.followUpNotes}`
        })
        uni.$u.toast('提交待跟进记录成功')
        this.followUpModalVisible = false
        this.followUpNotes = ''
      } catch (error) {
        console.error('提交失败:', error)
        uni.$u.toast('提交失败')
      }
    },

    /**
     * 下一步
     */
    async handleNext() {
      await uni.$u.api.updateReceiptForm({
        id: this.currentReceipt.id,
        tableFee: this.paymentAmount,
        fileIds: this.detailImages.map(item => item.id).join(',')
      })

      await uni.$u.api.updateClueOrderForm({
        id: this.orderDetail.id,
        customName: this.paymentInfo.customName || '',
        bankName: this.paymentInfo.bankName || '',
        bankCardNumber: this.paymentInfo.bankAccount || '',
        idCard: this.paymentInfo.idNumber || ''
      })

      this.$emit('save', {
        nowPage: 'formThree',
        form: {
          ...this.paymentInfo
        },
        fileIds: this.detailImages.map(item => item.id).join(',')
      })

      this.$emit('next', {
        nowPage: 'formThree',
        form: {
          ...this.paymentInfo
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
@import '../styles/common.scss';

.page-three-container {
  @extend .page-container;
  padding-bottom: 100rpx;
}

.info-card {
  @extend .card-wrap;
  padding: 20rpx;
  margin-top: 20rpx;
  box-sizing: border-box;
  width: 100%;
  max-width: 100%;
}

.info-card-title {
  @include font-styles($size: title, $weight: bold, $color: primary);
  margin-bottom: 25rpx;
  padding-bottom: 15rpx;
  border-bottom: 1rpx solid map-get($colors, border);
}

.info-row {
  margin-bottom: 20rpx;
}

.info-label {
  @include font-styles($size: tiny, $weight: regular, $color: tertiary);
  margin-bottom: 8rpx;
  display: block;
}

.info-input {
  border-radius: 8rpx;
  border: 1rpx solid #e5e7eb;
  padding: 12rpx 16rpx;
  width: 100%;
  box-sizing: border-box;
}

.detail-image-section {
  padding: 20rpx;
}

.detail-image-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid map-get($colors, border);
}

.detail-image-title {
  @include font-styles($size: content, $weight: bold, $color: primary);
}

.detail-image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  position: relative;
}

.detail-image-item {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  touch-action: none;
  transition: transform 0.2s ease, opacity 0.2s ease;
  z-index: 1;
  box-sizing: border-box;

  &.dragging {
    opacity: 0.6;
    transform: scale(1.05);
    z-index: 999;
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.2);
  }

  &.can-drop {
    outline: 2rpx dashed #108cff;
    outline-offset: -2rpx;
    background-color: rgba(16, 140, 255, 0.1);
    border-radius: 8rpx;
  }
}

.image-type-tag {
  position: absolute;
  top: 10rpx;
  left: 10rpx;
  background-color: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 5rpx 10rpx;
  border-radius: 12rpx;
  font-size: 22rpx;
  z-index: 1;
}

.detail-delete-btn {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: #ff4d4f;
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  z-index: 10;
  cursor: pointer;
}

.detail-upload-btn {
  width: 200rpx;
  height: 200rpx;
  border: 8rpx dashed #ddd;
  border-radius: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f9f9f9;
  cursor: pointer;
}

.payment-card {
  margin-top: 20rpx;
}

.payment-section {
  padding: 20rpx;
}

.payment-total-container {
  background-color: #f5f7fa;
  border: 2rpx solid #e5e7eb;
  border-radius: 12rpx;
  padding: 0rpx 30rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24rpx;
}

.payment-label {
  font-size: 36rpx;
  font-weight: 700;
  min-width: 140rpx;
}

.payment-amount {
  font-size: 48rpx;
  font-weight: 600;
  color: #f53f3f;
  width: auto;
  min-width: 150rpx;
  border: none;
  text-align: right !important;
}

.payment-buttons-row {
  display: flex;
  gap: 20rpx;
  margin-bottom: 24rpx;
}

.payment-button {
  flex: 1;
  border-radius: 12rpx;
  padding: 5rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border: 2rpx solid #e5e7eb;
  cursor: pointer;
  gap: 12rpx;
}

.pay-now-button {
  width: 100%;
  border-radius: 12rpx;
  padding: 32rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #108cff;
  color: #fff;
  cursor: pointer;
  box-shadow: 0 4rpx 12rpx rgba(16, 140, 255, 0.2);
}

.button-text {
  font-size: 28rpx;
  font-weight: 500;
  color: inherit;
}

.modal-content {
  width: 100%;
  padding: 40rpx 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.payment-amount-display {
  font-size: 64rpx;
  font-weight: bold;
  color: #108cff;
  text-align: center;
  margin-bottom: 40rpx;
  width: 100%;
}

.payment-info-section {
  width: 100%;
  background-color: #f5f7fa;
  border: 2rpx solid #e5e7eb;
  border-radius: 12rpx;
  padding: 30rpx 20rpx;
  margin-bottom: 40rpx;
}

.info-item {
  display: flex;
  margin-bottom: 20rpx;
  align-items: center;
  justify-content: space-between;

  &:last-child {
    margin-bottom: 0;
  }
}

.next-btn {
  position: fixed;
  bottom: 10rpx;
  left: 2.5%;
  width: 95%;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  border-radius: 20rpx;
  z-index: 1000;
}
</style>
