<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-3">
        <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="rules-text text-sm text-gray-600 space-y-1">
        <view>1. 请根据审核反馈，修改相关信息；</view>
        <view>2. 修改完成后，系统将重新进行审核；</view>
        <view>3. 审核通过后，您可以使用优惠券进行下单。</view>
        <view class="text-orange-600">
          4. 系统将自动回显您的手机号，其他信息按审核反馈修改，请重新填写。
        </view>
      </view>
    </view>

    <!-- 表单区域 -->
    <view class="bg-white px-4 py-4 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>
      <wd-form ref="formRef" :model="formData">
        <wd-cell-group border>
          <!-- 用户类型 -->
          <wd-cell
            title="用户类型"
            title-width="100px"
            prop="userstype"
            required
            custom-class="custom-cell"
          >
            <wd-radio-group
              v-model="formData.userstype"
              @change="handleUserTypeChange"
              inline
              shape="dot"
              :rules="[{ required: true, message: '请选择用户类型' }]"
            >
              <wd-radio value="个人">个人</wd-radio>
              <wd-radio value="企业">企业</wd-radio>
            </wd-radio-group>
          </wd-cell>

          <!-- 姓名/企业名称 -->
          <wd-input
            :label="usersnameLabel"
            label-width="100px"
            prop="usersname"
            required
            v-model="formData.usersname"
            :placeholder="`请输入${usersnameLabel}`"
            clearable
            no-border
            :rules="[{ required: true, message: `请输入${usersnameLabel}` }]"
          />

          <!-- 地址 -->
          <wd-input
            :label="addressLabel"
            label-width="100px"
            prop="usersaddress"
            required
            v-model="formData.usersaddress"
            :placeholder="`请输入${addressLabel}`"
            clearable
            no-border
            :rules="[{ required: true, message: `请输入${addressLabel}` }]"
          />

          <!-- 证件号 -->
          <wd-input
            :label="idNumberLabel"
            label-width="100px"
            prop="idNumber"
            required
            v-model="formData.idNumber"
            :placeholder="`请输入${idNumberLabel}`"
            clearable
            no-border
            :rules="[{ required: true, message: `请输入${idNumberLabel}` }]"
          />

          <!-- 证件照片上传 -->
          <wd-cell
            :title="idPhotoLabel"
            title-width="100px"
            prop="idPhotoIds"
            required
            custom-class="custom-cell"
          >
            <view class="flex-1">
              <!-- 个人身份证上传 -->
              <template v-if="formData.userstype === '个人'">
                <UploadComponent
                  v-model="formData.idCardFiles"
                  v-model:fileIds="formData.idCardIds"
                  :limit="1"
                  attmodel="coupon_identity"
                  attpath="/coupon_identity/"
                  modelStats="idCardIds"
                  message="请上传身份证照片"
                  tips="请上传身份证正面照片"
                />
              </template>

              <!-- 企业营业执照上传 -->
              <template v-else>
                <UploadComponent
                  v-model="formData.businessLicenseFiles"
                  v-model:fileIds="formData.businessLicenseIds"
                  :limit="1"
                  attmodel="coupon_identity"
                  attpath="/coupon_identity/"
                  modelStats="businessLicenseIds"
                  message="请上传营业执照照片"
                />
              </template>
            </view>
          </wd-cell>

          <!-- 购机者照片上传 (可选) -->
          <wd-cell title="购机者照片" title-width="100px" custom-class="custom-cell">
            <view class="flex-1">
              <UploadComponent
                v-model="formData.buyerPhoto"
                v-model:fileIds="formData.buyerPhotoIds"
                :limit="1"
                :required="false"
                attmodel="coupon_buyer"
                attpath="/coupon_buyer/"
                modelStats="buyerPhotoIds"
                message="请上传购机者照片"
                tips="用于确认购机者身份"
              />
            </view>
          </wd-cell>

          <!-- 手机号 -->
          <wd-input
            label="手机号"
            label-width="100px"
            prop="phone"
            required
            v-model="formData.phone"
            placeholder="请输入您的手机号码"
            clearable
            no-border
            :rules="[
              { required: true, message: '请输入手机号码' },
              { required: false, pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码' },
            ]"
            @blur="validatePhone"
          />
        </wd-cell-group>
      </wd-form>
    </view>

    <!-- 提交按钮 -->
    <view class="fixed-bottom bg-white p-4 border-t border-gray-100">
      <wd-button type="primary" block size="large" @click="handleSubmit" :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, onMounted } from 'vue'
import { useMessage } from 'wot-design-uni'
import { onLoad } from '@dcloudio/uni-app'
import UploadComponent from '@/components/UploadComponent.vue'
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 formRef = ref<any>()
const formData = reactive({
  userstype: '个人', // 用户类型，默认个人
  usersname: '', // 姓名或企业名称
  usersaddress: '', // 地址
  idNumber: '', // 证件号

  // 身份证照片（个人用户）
  idCardFiles: [], // 身份证照片文件列表
  idCardIds: [], // 身份证照片ID列表

  // 营业执照（企业用户）
  businessLicenseFiles: [], // 营业执照照片文件列表
  businessLicenseIds: [], // 营业执照照片ID列表

  // 购机者照片(可选)
  buyerPhoto: [], // 购机者照片文件列表
  buyerPhotoIds: [], // 购机者照片ID列表

  phone: '', // 手机号
})

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

const usersnameLabel = computed(() => (formData.userstype === '个人' ? '姓名' : '企业名称'))
const addressLabel = computed(() => (formData.userstype === '个人' ? '身份证地址' : '企业注册地址'))
const idNumberLabel = computed(() =>
  formData.userstype === '个人' ? '身份证号' : '统一社会信用代码',
)
const idPhotoLabel = computed(() => (formData.userstype === '个人' ? '身份证正面' : '营业执照'))

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

// 手机号验证相关
const isPhoneValid = ref(false)
const phoneReg = /^1[3-9]\d{9}$/

function validatePhone() {
  if (!formData.phone) {
    isPhoneValid.value = false
    return
  }
  isPhoneValid.value = phoneReg.test(formData.phone)
  if (!isPhoneValid.value && formData.phone) {
    uni.showToast({ title: '请输入正确的手机号码', icon: 'none' })
  }
}

// 用户类型切换
function handleUserTypeChange() {
  // 清空相关字段以便用户重新输入和校验
  formData.usersname = ''
  formData.usersaddress = ''
  formData.idNumber = ''

  // 清空证件照片上传
  if (formData.userstype === '个人') {
    formData.idCardFiles = []
    formData.idCardIds = []
    formData.businessLicenseFiles = []
    formData.businessLicenseIds = []
  } else {
    formData.idCardFiles = []
    formData.idCardIds = []
    formData.businessLicenseFiles = []
    formData.businessLicenseIds = []
  }

  // 清空购机者照片
  formData.buyerPhoto = []
  formData.buyerPhotoIds = []
}

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

    console.log('获取到的身份证/营业执照图片:', identityImages)

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

    console.log('获取到的购机者照片:', buyerImages)

    // 回显身份证/营业执照图片
    if (identityImages.length > 0) {
      if (formData.userstype === '个人') {
        // 个人用户回显身份证
        formData.idCardFiles = identityImages.map((img) => ({
          url: img.url,
          name: img.attorginname || '身份证照片',
        }))
        formData.idCardIds = identityImages.map((img) => ({
          url: img.url,
          id: img.attid,
        }))
      } else {
        // 企业用户回显营业执照
        formData.businessLicenseFiles = identityImages.map((img) => ({
          url: img.url,
          name: img.attorginname || '营业执照照片',
        }))
        formData.businessLicenseIds = identityImages.map((img) => ({
          url: img.url,
          id: img.attid,
        }))
      }
    }

    // 回显购机者照片
    if (buyerImages.length > 0) {
      formData.buyerPhoto = buyerImages.map((img) => ({
        url: img.url,
        name: img.attorginname || '购机者照片',
      }))
      formData.buyerPhotoIds = buyerImages.map((img) => ({
        url: img.url,
        id: img.attid,
      }))
    }

    console.log('回显的图片信息:', {
      identityImages,
      buyerImages,
      formData: {
        idCardFiles: formData.idCardFiles,
        idCardIds: formData.idCardIds,
        businessLicenseFiles: formData.businessLicenseFiles,
        businessLicenseIds: formData.businessLicenseIds,
        buyerPhoto: formData.buyerPhoto,
        buyerPhotoIds: formData.buyerPhotoIds,
      },
    })
  } catch (error) {
    console.error('获取图片信息失败:', error)
  }
}

// 提交表单
async function handleSubmit() {
  try {
    const valid = await formRef.value.validate()
    if (!valid) {
      return
    }

    validatePhone()
    if (!isPhoneValid.value) {
      uni.showToast({ title: '请输入正确的手机号码', icon: 'none' })
      return
    }

    // 验证证件照片上传
    const hasUploadedFiles =
      formData.userstype === '个人'
        ? formData.idCardIds.length > 0
        : formData.businessLicenseIds.length > 0

    if (!hasUploadedFiles) {
      uni.showToast({
        title: `请上传${formData.userstype === '个人' ? '身份证照片' : '营业执照照片'}`,
        icon: 'none',
      })
      return
    }

    submitLoading.value = true
    overlayShow.value = true

    try {
      // 准备提交参数
      const submitParams: any = {
        coupon2sid: coupon2sid.value, // 优惠券ID
        userstype: formData.userstype, // 用户类型
        usersname: formData.usersname, // 姓名或企业名称
        usersaddress: formData.usersaddress, // 地址
        coupon2phone: formData.phone, // 手机号
      }

      // 根据用户类型添加证件号
      if (formData.userstype === '个人') {
        submitParams.usersidcardnumber = formData.idNumber // 身份证号
      } else {
        submitParams.usersshtyxydm = formData.idNumber // 统一社会信用代码
      }

      // 添加文件ID
      const fileIds = []

      // 添加身份证/营业执照文件ID
      if (formData.userstype === '个人' && formData.idCardIds.length > 0) {
        fileIds.push(...formData.idCardIds.map((item) => item.id))
      } else if (formData.userstype === '企业' && formData.businessLicenseIds.length > 0) {
        fileIds.push(...formData.businessLicenseIds.map((item) => item.id))
      }

      // 添加购机者照片文件ID（可选）
      if (formData.buyerPhotoIds.length > 0) {
        fileIds.push(...formData.buyerPhotoIds.map((item) => item.id))
      }

      if (fileIds.length > 0) {
        submitParams.filesid = fileIds.join(',')
      }

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

      // 调用修改接口
      const result = await couponStore.getCoupon2Modify(submitParams)

      console.log('修改结果:', result)

      submitLoading.value = false
      overlayShow.value = false

      message
        .alert({
          msg: '信息修改成功！系统将重新审核您的优惠券。',
          title: '提示',
          confirmButtonText: '确定',
        })
        .then(() => {
          // 跳转回优惠券列表页面
          uni.navigateBack()
        })
    } catch (error) {
      console.error('提交修改失败:', error)
      submitLoading.value = false
      overlayShow.value = false

      message.alert({
        title: '提示',
        msg: '提交失败，请稍后重试',
      })
    }
  } catch (error) {
    console.error('修改信息出错：', error)
    submitLoading.value = false
    overlayShow.value = false
  }
}

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

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

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

      if (couponDetailResult) {
        couponDetail.value = couponDetailResult

        // 回显表单数据
        if (couponDetail.value.usersphone) {
          formData.phone = couponDetail.value.usersphone
        }

        // 回显用户类型
        if (couponDetail.value.userstype) {
          formData.userstype = couponDetail.value.userstype
        }

        // 回显姓名/企业名称
        if (couponDetail.value.usersname) {
          formData.usersname = couponDetail.value.usersname
        }

        // 回显地址
        if (couponDetail.value.usersaddress) {
          formData.usersaddress = couponDetail.value.usersaddress
        }

        // 回显证件号
        if (couponDetail.value.usersidcardnumber) {
          formData.idNumber = couponDetail.value.usersidcardnumber
        } else if (couponDetail.value.usersshtyxydm) {
          formData.idNumber = couponDetail.value.usersshtyxydm
        }

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

<style lang="scss" scoped>
.rules-text {
  line-height: 1.6;
}

.fixed-bottom {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 100;
}

// 针对 wd-field 内的 wd-input, wd-radio-group 等组件去除边框或调整样式
:deep(.wd-cell-group .wd-input) {
  // If they don't have a border by default or if no-border is not working as expected
  // Example:
  // border-bottom: 1px solid #eee;
}
:deep(.wd-cell-group .wd-input__inner) {
  // If no-border was intended to remove internal padding/borders of wd-input for wd-field
  // We might not need this if wd-input itself looks fine as a direct child of wd-cell-group.
  // The no-border prop on wd-input might be sufficient.
}

// For wd-cell containing radio group or other custom layouts
:deep(.custom-cell .wd-cell__value) {
  flex: 1; // Allow radio group or other content to take full width
}
:deep(.custom-cell .wd-radio-group) {
  // specific styles for radio group if needed
}

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