<!--
 * @Page: 问卷调查
 * @Author: Fengyu
 * @Date: 2025-12-12 10:12:59
 * @LastEditors: Fengyu
 * @LastEditTime: 2025-12-17 11:12:47
-->
<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="parkSelectShow" :list="parkList" @confirm="confirm"></u-select>
              <span @click="parkSelectShow = true">{{ parkName || '请选择' }}&nbsp;﹥</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 + 2 }}. {{ 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 + 2 }}. 您认为途经最好的高速是？</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 + 3 }}. 您认为途经最好的服务区是？</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">您的手机号：</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">
          提 交
        </view>
      </view>
    </view>
  </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 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 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
  })

  // 根据页面参数获取问卷详情
  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
        // 如果questionnaireInfo.value.type == 2,不显示‘车辆维修站’
        if (questionnaireInfo.value.type == 2) {
          dataFilledIn.value = dataList.value.filter(item => item.id != 6)
        } else {
          dataFilledIn.value = dataList.value
        }
      } else {
        uni.showToast({
          title: res.message || '获取问卷详情失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('获取问卷详情失败:', err);
      uni.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
    });
  });
  
    // 提交表单
    const submitForm = () => {
      // 检查是否所有项都有选择
      const isComplete = dataFilledIn.value.every(item => item.value !== '');
      if (!isComplete) {
        uni.showToast({
          title: '请完成所有项',
          icon: 'none'
        });
        return;
      }

      if (!parkId.value) {
        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,
        ...scoreData
      };

      console.log('提交参数:', params);
      
      // 调用API提交表单
      submitQuestionnaireApi(params).then(res => {
        if (res.code === 200) {
          uni.showToast({
            title: '感谢您的反馈！',
            icon: 'success'
          });
          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'
        });
      });
    }
</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;

    .grid-content {

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

    // 提交按钮
    .submit-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;
      // 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;
  }
</style>