<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '优惠券详情',
  },
}
</route>

<template>
  <view class="bg-gray-100 min-h-screen pb-20">
    <!-- 基本信息 -->
    <view class="bg-white px-4 py-4 mb-3 shadow-sm">
      <view class="flex items-center mb-4">
        <view class="text-lg font-bold text-gray-800">基本信息</view>
        <view class="ml-2 flex-1 h-px bg-gray-100"></view>
      </view>

      <view class="space-y-3">
        <view class="flex items-center">
          <view class="text-sm text-gray-600 w-24">优惠券编号：</view>
          <view class="text-sm text-gray-800 flex-1">
            {{ couponDetail.coupon2code || '-' }}
          </view>
        </view>
        <view class="flex items-center">
          <view class="text-sm text-gray-600 w-24">优惠券名称：</view>
          <view class="text-sm text-gray-800 flex-1">
            {{ couponDetail.coupon2mc || '-' }}
          </view>
        </view>
        <view class="flex items-center">
          <view class="text-sm text-gray-600 w-24">申请时间：</view>
          <view class="text-sm text-gray-800 flex-1">
            {{ formatDateTime(couponDetail.coupon2adddatetime) }}
          </view>
        </view>
        <view class="flex items-center">
          <view class="text-sm text-gray-600 w-24">当前状态：</view>
          <view class="flex-1">
            <wd-tag :type="getStatusTagType(couponDetail.coupon2sype)" size="small">
              {{ getStatusText(couponDetail.coupon2sype) }}
            </wd-tag>
          </view>
        </view>
      </view>
    </view>

    <!-- 申请人信息 -->
    <view class="bg-white px-4 py-4 mb-3 shadow-sm">
      <view class="flex items-center mb-4">
        <view class="text-lg font-bold text-gray-800">申请人信息</view>
        <view class="ml-2 flex-1 h-px bg-gray-100"></view>
      </view>

      <view class="space-y-3">
        <view class="flex items-center">
          <view class="text-sm text-gray-600 w-24">用户类型：</view>
          <view class="text-sm text-gray-800 flex-1">
            {{ couponDetail.userstype || '-' }}
          </view>
        </view>
        <view class="flex items-center">
          <view class="text-sm text-gray-600 w-24">{{ usersnameLabel }}：</view>
          <view class="text-sm text-gray-800 flex-1">
            {{ couponDetail.usersname || '-' }}
          </view>
        </view>
        <view class="flex items-center">
          <view class="text-sm text-gray-600 w-24">{{ idNumberLabel }}：</view>
          <view class="text-sm text-gray-800 flex-1">
            {{ getIdNumber() }}
          </view>
        </view>
        <view class="flex items-center">
          <view class="text-sm text-gray-600 w-24">手机号：</view>
          <view class="text-sm text-gray-800 flex-1">
            {{ couponDetail.coupon2phone || '-' }}
          </view>
        </view>
        <view class="flex items-center">
          <view class="text-sm text-gray-600 w-24">地址：</view>
          <view class="text-sm text-gray-800 flex-1">
            {{ couponDetail.usersaddress || '-' }}
          </view>
        </view>
      </view>
    </view>

    <!-- 证件照片 -->
    <view class="bg-white px-4 py-4 mb-3 shadow-sm">
      <view class="flex items-center mb-4">
        <view class="text-lg font-bold text-gray-800">证件照片</view>
        <view class="ml-2 flex-1 h-px bg-gray-100"></view>
      </view>

      <view class="space-y-4">
        <!-- 身份证/营业执照 -->
        <view>
          <view class="text-sm text-gray-600 mb-2">{{ idPhotoLabel }}：</view>
          <view v-if="identityImages.length > 0" class="flex flex-wrap gap-2">
            <view
              v-for="(image, index) in identityImages"
              :key="index"
              class="w-20 h-20 rounded border border-gray-200 overflow-hidden"
              @click="
                previewImage(
                  image.url,
                  identityImages.map((img) => img.url),
                )
              "
            >
              <image :src="image.url" mode="aspectFill" class="w-full h-full" />
            </view>
          </view>
          <view v-else class="text-sm text-gray-400">暂无照片</view>
        </view>

        <!-- 购机者照片 -->
        <view>
          <view class="text-sm text-gray-600 mb-2">购机者照片：</view>
          <view v-if="buyerImages.length > 0" class="flex flex-wrap gap-2">
            <view
              v-for="(image, index) in buyerImages"
              :key="index"
              class="w-20 h-20 rounded border border-gray-200 overflow-hidden"
              @click="
                previewImage(
                  image.url,
                  buyerImages.map((img) => img.url),
                )
              "
            >
              <image :src="image.url" mode="aspectFill" class="w-full h-full" />
            </view>
          </view>
          <view v-else class="text-sm text-gray-400">暂无照片</view>
        </view>
      </view>
    </view>

    <!-- 审核信息 -->
    <view class="bg-white px-4 py-4 mb-3 shadow-sm">
      <view class="flex items-center mb-4">
        <view class="text-lg font-bold text-gray-800">审核信息</view>
        <view class="ml-2 flex-1 h-px bg-gray-100"></view>
      </view>

      <!-- 已审核状态显示 -->
      <view v-if="couponDetail.coupon2sype !== 0" class="space-y-3">
        <view class="flex items-center">
          <view class="text-sm text-gray-600 w-24">审核状态：</view>
          <view class="flex-1">
            <wd-tag :type="getStatusTagType(couponDetail.coupon2sype)" size="small">
              {{ getStatusText(couponDetail.coupon2sype) }}
            </wd-tag>
          </view>
        </view>
        <view v-if="couponDetail.coupon2shbz" class="flex items-start">
          <view class="text-sm text-gray-600 w-24">审核备注：</view>
          <view class="text-sm text-gray-800 flex-1">
            {{ couponDetail.coupon2shbz }}
          </view>
        </view>
        <view v-if="couponDetail.coupon2shdate" class="flex items-center">
          <view class="text-sm text-gray-600 w-24">审核时间：</view>
          <view class="text-sm text-gray-800 flex-1">
            {{ formatDateTime(couponDetail.coupon2shdate) }}
          </view>
        </view>
        <view v-if="couponDetail.coupon2shuser" class="flex items-center">
          <view class="text-sm text-gray-600 w-24">审核人员：</view>
          <view class="text-sm text-gray-800 flex-1">
            {{ couponDetail.coupon2shuser }}
          </view>
        </view>
      </view>

      <!-- 待审核状态表单 -->
      <wd-form v-else ref="auditFormRef" :model="auditForm">
        <wd-cell-group border>
          <!-- 审核状态 -->
          <wd-cell
            title="审核状态"
            title-width="100px"
            prop="coupon2sype"
            required
            custom-class="custom-cell"
          >
            <wd-radio-group
              v-model="auditForm.coupon2sype"
              @change="handleAuditStatusChange"
              inline
              shape="dot"
              :rules="[{ required: true, message: '请选择审核状态' }]"
            >
              <wd-radio :value="1">审核通过</wd-radio>
              <wd-radio :value="2">驳回</wd-radio>
            </wd-radio-group>
          </wd-cell>

          <!-- 审核备注 -->
          <wd-textarea
            label="审核备注"
            label-width="100px"
            prop="coupon2shbz"
            v-model="auditForm.coupon2shbz"
            placeholder="请输入审核备注（驳回时必填）"
            :maxlength="200"
            show-word-limit
            :required="auditForm.coupon2sype === 2"
            :rules="
              auditForm.coupon2sype === 2 ? [{ required: true, message: '驳回时审核备注必填' }] : []
            "
          />
        </wd-cell-group>
      </wd-form>
    </view>

    <!-- 提交按钮 -->
    <view
      v-if="couponDetail.coupon2sype === 0"
      class="fixed-bottom bg-white p-4 border-t border-gray-100"
    >
      <wd-button
        type="primary"
        block
        size="large"
        @click="handleSubmitAudit"
        :loading="submitLoading"
      >
        提交审核
      </wd-button>
    </view>

    <!-- loading -->
    <wd-overlay :show="overlayShow">
      <view class="wrapper w-full h-full flex items-center justify-center">
        <wd-loading />
      </view>
    </wd-overlay>
  </view>
</template>

<script lang="ts" setup>
import { reactive, ref, computed } from 'vue'
import { useMessage } from 'wot-design-uni'
import { onLoad } from '@dcloudio/uni-app'
import { useCouponStore } from '@/store/coupon'
import { useUserStore } from '@/store/user'
import { useFileStore } from '@/store/file'

const message = useMessage()
const couponStore = useCouponStore()
const userStore = useUserStore()
const fileStore = useFileStore()

// 页面参数
const coupon2sid = ref('')

// 优惠券详情数据
const couponDetail = ref<any>({})

// 图片数据
const identityImages = ref([])
const buyerImages = ref([])

// 审核表单
const auditFormRef = ref<any>()
const auditForm = reactive({
  coupon2sype: 1, // 默认审核通过
  coupon2shbz: '', // 审核备注
})

const overlayShow = ref(false)
const submitLoading = ref(false)

// 计算属性
const usersnameLabel = computed(() =>
  couponDetail.value.userstype === '个人' ? '姓名' : '企业名称',
)
const idNumberLabel = computed(() =>
  couponDetail.value.userstype === '个人' ? '身份证号' : '统一社会信用代码',
)
const idPhotoLabel = computed(() =>
  couponDetail.value.userstype === '个人' ? '身份证正面' : '营业执照',
)

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 0:
      return '待审核'
    case 1:
      return '已通过'
    case 2:
      return '已驳回'
    default:
      return '未知'
  }
}

// 获取状态标签类型
const getStatusTagType = (status: number) => {
  switch (status) {
    case 0:
      return 'warning'
    case 1:
      return 'success'
    case 2:
      return 'danger'
    default:
      return 'primary'
  }
}

// 获取证件号
const getIdNumber = () => {
  if (couponDetail.value.userstype === '个人') {
    return couponDetail.value.usersidcardnumber || '-'
  } else {
    return couponDetail.value.usersshtyxydm || '-'
  }
}

// 预览图片
const previewImage = (current: string, urls: string[]) => {
  uni.previewImage({
    current,
    urls,
  })
}

// 审核状态变化处理
const handleAuditStatusChange = () => {
  // 如果选择审核通过，清空备注
  if (auditForm.coupon2sype === 1) {
    auditForm.coupon2shbz = ''
  }
}

// 获取图片信息
const loadImageFiles = async () => {
  try {
    // 获取身份证/营业执照图片
    const identityResult = await fileStore.getAttachmentList({
      attlsh: coupon2sid.value,
      attmodel: 'coupon_identity',
    })
    identityImages.value = identityResult || []

    // 获取购机者照片
    const buyerResult = await fileStore.getAttachmentList({
      attlsh: coupon2sid.value,
      attmodel: 'coupon_buyer',
    })
    buyerImages.value = buyerResult || []

    console.log('获取到的图片信息:', {
      identityImages: identityImages.value,
      buyerImages: buyerImages.value,
    })
  } catch (error) {
    console.error('获取图片信息失败:', error)
  }
}

// 提交审核
const handleSubmitAudit = async () => {
  try {
    const valid = await auditFormRef.value.validate()
    if (!valid) {
      return
    }

    // 如果是驳回状态，检查备注是否填写
    if (auditForm.coupon2sype === 2 && !auditForm.coupon2shbz.trim()) {
      uni.showToast({ title: '驳回时审核备注必填', icon: 'none' })
      return
    }

    submitLoading.value = true
    overlayShow.value = true

    try {
      // 准备提交参数
      const submitParams = {
        coupon2sid: coupon2sid.value,
        coupon2sype: auditForm.coupon2sype,
        coupon2shbz: auditForm.coupon2shbz.trim(),
      }

      console.log('提交审核参数:', submitParams)

      // 调用审核接口
      const result = await couponStore.submitCoupon2Audit(submitParams)

      console.log('审核结果:', result)

      submitLoading.value = false
      overlayShow.value = false

      message
        .confirm({
          msg: '审核提交成功！',
          title: '提示',
          confirmButtonText: '确定',
          showCancelButton: false,
        })
        .then(() => {
          // 跳转回审核列表页面
          uni.navigateBack()
        })
    } catch (error) {
      console.error('提交审核失败:', error)
      submitLoading.value = false
      overlayShow.value = false

      message.alert({
        title: '提示',
        msg: '提交失败，请稍后重试',
      })
    }
  } catch (error) {
    console.error('审核表单验证失败:', error)
  }
}

onLoad(async (query: any) => {
  coupon2sid.value = query.coupon2sid || ''

  // 检查审核权限
  if (!userStore.audit_auth) {
    message
      .alert({
        title: '提示',
        msg: '您没有审核权限',
      })
      .then(() => {
        uni.navigateBack()
      })
    return
  }

  if (coupon2sid.value) {
    try {
      overlayShow.value = true

      // 获取优惠券详情
      const couponDetailResult = await couponStore.getCoupon2AuditDetail({
        coupon2sid: coupon2sid.value,
      })

      if (couponDetailResult) {
        couponDetail.value = couponDetailResult

        // 注意：所有状态的优惠券都可以查看详情

        // 获取并显示图片信息
        await loadImageFiles()
      }
    } catch (error) {
      console.error('获取优惠券详情失败:', error)
      message
        .alert({
          title: '提示',
          msg: '获取优惠券信息失败，请稍后重试',
        })
        .then(() => {
          uni.navigateBack()
        })
    } finally {
      overlayShow.value = false
    }
  }
})
</script>

<style lang="scss" scoped>
.fixed-bottom {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 100;
}

// 针对 wd-cell 内的自定义样式
:deep(.custom-cell .wd-cell__value) {
  flex: 1;
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
</style>
