<!--
 * @Page: 问卷调查
 * @Author: Fengyu
 * @Date: 2025-12-12 10:12:59
 * @LastEditors: Fengyu
 * @LastEditTime: 2025-12-18 17:47:41
-->
<template>
  <view class="questionnaire-container">
    <!-- 顶部导航栏 -->
    <!-- <view class="nav-bar">
      <view class="nav-left">
        <uni-icons type="left" size="32" color="#333" @click="goBack"></uni-icons>
      </view>
      <view class="nav-title">调查问卷</view>
      <view class="nav-right">
        <uni-icons type="ellipsis" size="32" color="#333"></uni-icons>
        <uni-icons type="eye" size="32" color="#333" class="ml10"></uni-icons>
      </view>
    </view> -->

    <!-- 问卷引导区域 -->
    <view class="guide-section">
      <view class="guide-content">
        <view class="guide-text">
          <view class="guide-title">问卷引导</view>
          <view class="guide-desc">欢迎您对我们服务区提出建议反馈，我们会对您的问题进行全程跟踪</view>
        </view>
        <view class="guide-image"></view>
      </view>
    </view>

    <!-- 网格选择区域 -->
    <view class="grid-section">
      <view class="grid-container">
        <view class="grid-item">
          <view class="grid-content flex j-sb a-center">
            <view class="grid-title">1.您的身份是：</view>
            <view class="grid-desc">
              <u-select v-model="userTypeShow" :list="userTypeList" @confirm="userTypeconfirm"></u-select>
              <span @click="userTypeShow = true">{{ userTypeName || '请选择' }}&nbsp;<span style="position: relative; top: -2px">⌵</span></span>
            </view>
          </view>
        </view>

        <view class="grid-item">
          <view class="grid-content flex j-sb a-center">
            <view class="grid-title">2.您所在的服务区</view>
            <view class="grid-desc">
              <u-select v-model="parkSelectShow" :list="parkList" @confirm="confirm"></u-select>
              <span @click="parkSelectShow = true">{{ parkName || '请选择' }}&nbsp;<span style="position: relative; top: -2px">⌵</span></span>
            </view>
          </view>
        </view>
        <view v-for="(item, index) in dataFilledIn" :key="item.id" class="grid-item">
          <view class="grid-content">
            <view class="grid-title">{{ index + 3 }}. {{ item.name }}</view>
            <view class="grid-desc">
              <u-radio-group v-model="item.value">
                <u-radio v-for="(t, i) in options" :key="i" :name="t.value" :disabled="t.disabled">
                  {{ t.name }}
                </u-radio>
              </u-radio-group>
            </view>
          </view>
        </view>
        <!-- 最好的高速 -->
        <view class="grid-item">
          <view class="grid-content">
            <view class="grid-title">{{ dataFilledIn.length + 3 }}. 您认为途经最好的高速是？</view>
            <view class="grid-desc">
              <u-input v-model="bestWay" type="textarea" :border="false" :height="100" :auto-height="true" placeholder="请输入您认为途经最好的高速" />
            </view>
          </view>
        </view>
        <!-- 最好的服务区 -->
        <view class="grid-item">
          <view class="grid-content">
            <view class="grid-title">{{ dataFilledIn.length + 4 }}. 您认为途经最好的服务区是？</view>
            <view class="grid-desc">
              <u-input
                v-model="bestService"
                type="textarea"
                :border="false"
                :height="100"
                :auto-height="true"
                placeholder="请输入您认为途经最好的服务区"
              />
            </view>
          </view>
        </view>

        <!-- 宝贵意见 -->
        <view class="grid-item">
          <view class="grid-content">
            <view class="grid-title">{{ dataFilledIn.length + 5 }}. 请留下您的宝贵意见</view>
            <view class="grid-desc">
              <u-input v-model="opinion" type="textarea" :border="false" :height="100" :auto-height="true" placeholder="请留下您的宝贵意见" />
            </view>
          </view>
        </view>

        <view class="grid-item">
          <view class="grid-content">
            <view class="grid-title">您的手机号：</view>
            <view class="grid-desc">
              <u-input
                v-model="phone"
                type="number"
                :border="false"
                :height="100"
                :maxlength="11"
                :auto-height="true"
                placeholder="请输入您的手机号"
              />
            </view>
          </view>
        </view>

        <view
          class="submit-btn"
          @click="submitForm"
          :class="{ disabled: !isFormAvailable || isSubmitting || submitCountdown > 0 }"
          :disabled="!isFormAvailable || isSubmitting || submitCountdown > 0"
        >
          <span v-if="!isSubmitting && submitCountdown === 0">提 交</span>
          <span v-else-if="isSubmitting">提交中...</span>
          <span v-else>稍后提交({{ submitCountdown }}s)</span>
        </view>
      </view>
    </view>
    <!-- 过了填报日期，弹窗提醒 -->
    <u-mask :show="!isFormAvailable" :mask-click-able="false">
      <view class="warp">
        <view class="rect" @tap.stop>
          <view class="rect-content">
            <view class="rect-title">提示</view>
            <view class="rect-desc">{{ msg || '当前时间已超过截止时间，无法填写' }}</view>
            <view class="rect-btn" @click="goHome">去首页</view>
          </view>
        </view>
      </view>
    </u-mask>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getQuestionnaireDetailApi, submitQuestionnaireApi, getParkList } from '@/api/investigation'

const dataList = ref([
  {
    id: 1,
    name: '公共卫生间',
    value: ''
  },
  {
    id: 2,
    name: '公共区域',
    value: ''
  },
  {
    id: 3,
    name: '餐饮',
    value: ''
  },
  {
    id: 4,
    name: '便利店',
    value: ''
  },
  {
    id: 5,
    name: '加油(加气、充电)站',
    value: ''
  },
  {
    id: 6,
    name: '车辆维修站',
    value: ''
  },
  {
    id: 7,
    name: '对本服务区总体评价',
    value: ''
  }
])

const options = ref([
  {
    name: '满意',
    value: 1
  },
  {
    name: '比较满意',
    value: 2
  },
  {
    name: '一般',
    value: 3
  },
  {
    name: '不满意',
    value: 4
  }
])

// 服务区选择框是否显示
const parkSelectShow = ref(false)

// 服务区列表
const parkList = ref([])

const parkId = ref('')
const parkName = ref('')

const phone = ref('')

const userTypeShow = ref(false)
const userTypeList = ref([
  {
    label: '大客司机',
    value: 1
  },
  {
    label: '大客乘客',
    value: 2
  },
  {
    label: '小客司乘人员',
    value: 3
  },
  {
    label: '货车司机',
    value: 4
  },
  {
    label: '其他',
    value: 5
  }
])
const userTypeName = ref('')
const userType = ref('')

const opinion = ref('')

// 获取服务区列表
const getParkListApi = () => {
  getParkList()
    .then((res) => {
      if (res.code === 200) {
        parkList.value = res.data.map((item) => ({
          label: item.name,
          value: item.id
        }))
      } else {
        uni.showToast({
          title: res.message || '获取服务区列表失败',
          icon: 'none'
        })
      }
    })
    .catch((err) => {
      console.error('获取服务区列表失败:', err)
      uni.showToast({
        title: err.data.msg || '网络错误，请重试',
        icon: 'none'
      })
    })
}

// 选择用户身份
const userTypeconfirm = (e) => {
  console.log(e[0].value, e[0].label)
  userTypeName.value = e[0].label
  userType.value = e[0].value
}

// 选择服务区
const confirm = (e) => {
  console.log(e[0].value, e[0].label)
  parkId.value = e[0].value
  parkName.value = e[0].label
}

// 最好的高速
const bestWay = ref('')

// 最好的服务区
const bestService = ref('')

// 动态的判断是否需要显示‘车辆维修站’
const dataFilledIn = ref([])

// 问卷信息
const questionnaireInfo = ref({
  // id: '',
  name: '',
  endAt: '',
  fileId: 0,
  type: 0
})

// 是否超时，超时显示弹窗
const isFormAvailable = ref(true)

// 提交按钮相关状态
const isSubmitting = ref(false) // 是否正在提交
const submitCountdown = ref(0) // 提交倒计时（秒）

/**
 * 验证问卷截止时间
 * @param {string} endAt 截止时间字符串，格式为"YYYY-MM-DD HH:MM:SS"
 */
const validateEndTime = (endAt) => {
  try {
    // 将字符串转换为日期对象（兼容不同浏览器）
    const endDate = new Date(endAt.replace(/-/g, '/'))
    const currentDate = new Date()

    // 比较当前时间与截止时间
    if (currentDate <= endDate) {
      isFormAvailable.value = true
    } else {
      isFormAvailable.value = false
    }
  } catch (error) {
    console.error('时间验证失败:', error)
    // 如果时间格式解析失败，默认允许填写
    isFormAvailable.value = true
  }
}

const goHome = () => {
  uni.switchTab({
    url: '/pages/index'
  })
}

const msg = ref('')

/**
 * 开始提交倒计时，限制5秒内只能提交一次
 */
const startSubmitCountdown = () => {
  const countdownTime = 5 // 倒计时时间（秒）
  submitCountdown.value = countdownTime

  // 创建倒计时定时器
  const timer = setInterval(() => {
    submitCountdown.value--

    // 倒计时结束
    if (submitCountdown.value <= 0) {
      clearInterval(timer)
      submitCountdown.value = 0
    }
  }, 1000)
}

// 根据页面参数获取问卷详情
onMounted(() => {
  getParkListApi()
  // 使用URLSearchParams正确解析URL参数
  const urlParams = new URLSearchParams(window.location.search)
  const questionnaireId = urlParams.get('id')

  if (!questionnaireId) {
    uni.showToast({
      title: '问卷ID参数缺失',
      icon: 'none'
    })
    return
  }

  getQuestionnaireDetailApi(questionnaireId)
    .then((res) => {
      if (res.code === 200) {
        questionnaireInfo.value = res.data
        validateEndTime(questionnaireInfo.value.endAt)
        // 如果questionnaireInfo.value.type == 2,不显示‘车辆维修站’
        if (questionnaireInfo.value.type == 2) {
          dataFilledIn.value = dataList.value.filter((item) => item.id != 6)
        } else {
          dataFilledIn.value = dataList.value
        }
      } else {
        msg.value = res.msg || '获取问卷详情失败'
        isFormAvailable.value = false
        // uni.showToast({
        //   title: res.message || '获取问卷详情失败',
        //   icon: 'none'
        // });
      }
    })
    .catch((err) => {
      // console.error('获取问卷详情失败:', err);
      uni.hideToast()
      msg.value = err.data.msg || '获取问卷详情失败'
      isFormAvailable.value = false
      // uni.showToast({
      //   title: '网络错误，请重试',
      //   icon: 'none'
      // });
    })
})

// 提交表单
const submitForm = () => {
  // 检查表单是否可用
  if (!isFormAvailable.value) {
    uni.showToast({
      title: '当前时间已超过截止时间，无法提交',
      icon: 'none'
    })
    return
  }

  // 检查是否正在提交或处于倒计时状态
  if (isSubmitting.value || submitCountdown.value > 0) {
    return
  }

  // 检查是否所有项都有选择
  const isComplete = dataFilledIn.value.every((item) => item.value !== '')

  if (!userType.value) {
    uni.showToast({
      title: '请选择身份',
      icon: 'none'
    })
    return
  }

  if (!parkId.value) {
    uni.showToast({
      title: '请选择服务区',
      icon: 'none'
    })
    return
  }

  if (!isComplete) {
    uni.showToast({
      title: '请完成所有项',
      icon: 'none'
    })
    return
  }

  if (!phone.value) {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none'
    })
    return
  }

  if (!bestWay.value) {
    uni.showToast({
      title: '请输入最好的高速',
      icon: 'none'
    })
    return
  }

  if (!bestService.value) {
    uni.showToast({
      title: '请输入最好的服务区',
      icon: 'none'
    })
    return
  }

  // 解析URL参数
  const urlParams = new URLSearchParams(window.location.search)
  const questionnaireId = questionnaireInfo.value.id || 0
  // const questionnaireId = '2000476937984221185' || 0;
  // const parkid = parseInt(urlParams.get('parkid')) || 0; // 与API参数名保持一致
  const mobile = urlParams.get('m') || ''

  // 验证必需参数
  if (!questionnaireId || !mobile) {
    uni.showToast({
      title: '参数错误，请重新进入页面',
      icon: 'none'
    })
    return
  }

  // 验证手机号格式
  // const mobileRegex = /^1[3-9]\d{9}$/;
  // if (!mobileRegex.test(mobile)) {
  //   uni.showToast({
  //     title: '手机号格式不正确',
  //     icon: 'none'
  //   });
  //   return;
  // }

  // 转换评分数据为targetA-G格式，确保为整数类型
  const scoreData = {
    targetA: parseInt(dataFilledIn.value.find((item) => item.id === 1)?.value) || 0, // 公共卫生间
    targetB: parseInt(dataFilledIn.value.find((item) => item.id === 2)?.value) || 0, // 公共区域
    targetC: parseInt(dataFilledIn.value.find((item) => item.id === 3)?.value) || 0, // 餐饮
    targetD: parseInt(dataFilledIn.value.find((item) => item.id === 4)?.value) || 0, // 便利店
    targetE: parseInt(dataFilledIn.value.find((item) => item.id === 5)?.value) || 0, // 加油(加气、充电)站
    targetF: parseInt(dataFilledIn.value.find((item) => item.id === 6)?.value) || 0, // 车辆维修站
    targetG: parseInt(dataFilledIn.value.find((item) => item.id === 7)?.value) || 0, // 总体评价
    bestWay: bestWay.value, // 最好的高速
    bestService: bestService.value, // 最好的服务区
    parkId: parkId.value
    // id: questionnaireId
  }

  // 构建完整参数对象，确保与API要求一致
  let params = {
    questionnaireId,
    // parkid, // 使用API要求的参数名
    mobile: phone.value,
    userType: userType.value,
    opinion: opinion.value,
    ...scoreData
  }

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

  // 设置提交状态
  isSubmitting.value = true

  // 调用API提交表单
  submitQuestionnaireApi(params)
    .then((res) => {
      if (res.code === 200) {
        uni.showToast({
          title: '感谢您的反馈！',
          icon: 'success'
        })
        // 提交成功后开始5秒倒计时
        startSubmitCountdown()
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/index'
          })
        }, 2000)
      } else {
        uni.showToast({
          title: res.message || '提交失败，请重试',
          icon: 'none'
        })
      }
    })
    .catch((err) => {
      console.error('提交失败:', err)
      uni.showToast({
        title: err.data.msg || '操作失败',
        icon: 'none'
      })
    })
    .finally(() => {
      // 无论成功失败，都恢复提交状态
      isSubmitting.value = false
    })
}
</script>

<style lang="scss" scoped>
.questionnaire-container {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #fff;
}

.nav-left,
.nav-right {
  display: flex;
  align-items: center;
}

.nav-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

/* 问卷引导区域 */
.guide-section {
  width: 100%;
  height: 100vh;
  /* 从上到下渐变样式 */
  background: linear-gradient(to bottom, #9ed9fc, #f0f8fb 40%);
  padding: 40rpx 30rpx;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
  margin-bottom: 40rpx;
}

.guide-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.guide-text {
  flex: 1;
  /* color: #fff; */
}

.guide-title {
  font-size: 32rpx;
  font-weight: 600;
  margin-bottom: 20rpx;
}

.guide-desc {
  font-size: 24rpx;
  line-height: 36rpx;
}

.guide-image {
  width: 300rpx;
  height: 300rpx;
  background: url('@/static/images/wenjuan.png') no-repeat center center;
  background-size: 100%;
}

.guide-image image {
  width: 100%;
  height: 100%;
}

/* 网格选择区域 */
.grid-section {
  width: 90%;
  /* height: 80vh; */
  margin: 0 auto;
  background-color: #fff;
  position: relative;
  top: 24vh;
  z-index: 3;
  border-radius: 20rpx;
}

.grid-container {
  /* display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 30rpx; */
  display: flex;
  flex-direction: column;
  margin-bottom: 40rpx;
  padding-bottom: 10px;

  .grid-content {
    .grid-title {
      font-size: 28rpx;
      font-weight: 600;
      margin-bottom: 20rpx;
    }
  }

  // 提交按钮
  .submit-btn {
    width: calc(100% - 20px);
    margin: auto;
    height: 2.5rem;
    line-height: 2.5rem;
    text-align: center;
    font-size: 1rem;
    font-weight: 600;
    color: #fff;
    background: linear-gradient(to bottom, #7ebbf5, #4b9ef6);
    border-radius: 0.3125rem;
    margin-top: 1.25rem;
    padding: 0 10px;
    // position: absolute;
    // bottom: 0;
    // left: 0;
    // z-index: 3;
  }
}

.grid-item {
  width: 100%;
  background-color: #fff;
  padding: 10px;
  /* border: 2rpx solid #e4e7ed; */
  border-radius: 10rpx;
  box-sizing: border-box;
  position: relative;
  transition: all 0.3s ease;
}

.grid-item-selected {
  background-color: #479bfa;
  border-color: #479bfa;
}

/* 换一换按钮 */
.refresh-btn {
  display: flex;
  justify-content: center;
}
.warp {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.rect {
  width: 60vw;
  max-width: 400px;
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx 30rpx;

  .rect-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 20rpx;
    text-align: center;
  }

  .rect-btn {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    font-size: 32rpx;
    font-weight: 600;
    color: #fff;
    background: linear-gradient(to bottom, #7ebbf5, #4b9ef6);
    border-radius: 10rpx;
    margin-top: 40rpx;
  }
}
</style>
