<template>
  <view
    class="subscribe"
    :style="{
      backgroundImage: `url(${baseUrl}/farqbxzczytcami/images/bg-5.png)`,
    }"
  >
    <view class="record" @click="goToRecord">
      <text>预约记录</text>
      <image
        src="@/assets/reservation-images/icon-right.svg"
        mode="widthFix"
        style="width: 30rpx; height: 30rpx"
      />
    </view>
    <view class="card">
      <view class="card-title">参观园区</view>
      <swiper
        circular
        class="card-swiper"
        :current="swiperIndex"
        @change="handleSwiperChange"
        :disable-touch="true"
      >
        <swiper-item
          class="swiper-item"
          v-for="(item, index) in cardList"
          :key="index"
          catch:touchmove="return false"
        >
          <view class="card-image">
            <image :src="item.image" mode="widthFix" />
          </view>
        </swiper-item>
      </swiper>
      <view class="name">
        {{ currentGround.title }}
        <!-- <view class="swiper-left" @click="handleSwiperLeft">
			<image
			  src="@/assets/reservation-images/icon-right-y.svg"
			  mode="widthFix"
			/>
		  </view>
		  <view class="swiper-right" @click="handleSwiperRight">
			<image
			  src="@/assets/reservation-images/icon-right-y.svg"
			  mode="widthFix"
			/>
		  </view>  -->
      </view>
      <view class="desc">
        {{ currentGround.detail }}
      </view>
      <!-- 分割线 -->
      <view class="line"></view>
      <!-- 到访时间 -->
      <view class="time">
        <view class="form-item" style="margin-bottom: 0rpx">
          <view class="form-item__label">到访时间</view>
          <view class="form-item__value" @click="handleDate">
            <view class="form-item__value-text">
              <text
                v-if="formData.reservation_date && formData.reservation_time"
              >
                {{ formData.reservation_date }} {{ formData.reservation_time }}
              </text>
              <text v-else class="form-item__value-text-placeholder">
                请选择到访日期及时间
              </text>
            </view>
            <image
              src="@/assets/reservation-images/icon-right-y.svg"
              mode="widthFix"
            />
          </view>
        </view>
      </view>
    </view>
    <view class="card" style="padding-top: 60rpx">
      <view class="form-item">
        <view class="form-item__label">预约人姓名</view>
        <view class="form-item__value">
          <input
            type="text"
            v-model="formData.realname"
            placeholder="请填写访客姓名"
            placeholder-style="color: #fff;opacity: 0.5"
          />
        </view>
      </view>
      <!-- <view class="form-item">
        <view class="form-item__label">预约人手机</view>
        <view class="form-item__value">
          <view class="area">
            <view>+86</view>
            <image src="@/assets/reservation-images/icon-right-y.svg" mode="widthFix" />
          </view>
          <view class="area-line"></view>
          <input
            type="text"
            maxlength="11"
            v-model="formData.telephone"
            placeholder="请输入手机号"
            placeholder-style="color: #fff;opacity: 0.5"
          />
        </view>
      </view> -->
      <!-- 验证码 -->
      <view class="phone-code">
        <view class="form-item" style="flex: 1">
          <view class="form-item__label">预约人手机</view>
          <view class="form-item__value">
            <input
              type="number"
              maxlength="11"
              v-model="formData.telephone"
              placeholder="请填写手机号"
              placeholder-style="color: #fff;opacity: 0.5"
            />
          </view>
        </view>
        <button
          class="phone-code-btn"
          open-type="getPhoneNumber"
          @getphonenumber="decryptPhoneNumber"
        >
          获取手机号
        </button>
      </view>
      <!-- 访客人数 -->
      <view class="form-item">
        <view class="form-item__label">访客人数</view>
        <view class="form-item__value">
          <input
            type="number"
            v-model="formData.visitor_number"
            placeholder="请填写访客人数"
            placeholder-style="color: #fff;opacity: 0.5"
          />
        </view>
      </view>
      <!-- 访客类型 -->
      <view class="form-item" style="margin-bottom: 0rpx">
        <view class="form-item__label">访客类型</view>
        <view class="form-item__value" @click="handleType">
          <input
            type="text"
            v-model="formData.typeStr"
            readonly
            placeholder="请选择访客类型"
            placeholder-style="color: #fff;opacity: 0.5"
          />
          <image
            src="@/assets/reservation-images/icon-right-y.svg"
            mode="widthFix"
          />
        </view>
      </view>
    </view>
    <!-- 提交按钮 -->
    <view class="submit-btn" @click="handleSubmit">
      <fh-button>确认预约</fh-button>
    </view>

    <!-- 到访日期弹窗 -->
    <uni-popup ref="datePanelRef" :safe-area="false">
      <view class="popup-box" style="max-height: 85vh">
        <view class="popup-header">
          <view class="title">到访时间</view>
          <view class="close" @click="datePanelRef.close()">
            <image
              src="@/assets/reservation-images/close.png"
              mode="widthFix"
            />
          </view>
        </view>
        <view class="popup-content">
          <view class="date-card">
            <view
              class="date-item"
              v-for="(item, index) in dateList"
              :key="index"
              @click="handleDateItemClick(item)"
              :class="{
                'date-item-active': item.is_selected,
                'date-item-disabled': item.isOpen == 0,
              }"
            >
              <view class="date-item-week">{{ item.week }}</view>
              <view class="date-item-day">{{ item.dayStr }}</view>
            </view>
          </view>
          <view class="date-line"></view>
          <view class="time-card">
            <view
              class="time-item"
              v-for="(item, index) in timeList"
              :key="index"
              @click="handleTimeItemClick(item)"
              :class="{
                'time-item-active': item.is_selected,
                'time-item-disabled': item.isOpen == 0,
              }"
            >
              <view class="time-item-day" style="text-align: center">
                <view>{{ item.time }}</view>
                <view v-if="item.isOpen == 0">{{ item.status }}</view>
              </view>
            </view>
          </view>
        </view>
        <view class="popup-footer" @click="handleDateConfirm">
          <fh-button>确认选择</fh-button>
        </view>
      </view>
    </uni-popup>
    <!-- 访客类型下拉框 -->
    <uni-popup ref="typePanelRef" :safe-area="false">
      <view class="popup-box" style="max-height: 85vh">
        <view class="popup-header">
          <view class="title">访客类型</view>
          <view class="close" @click="typePanelRef.close()">
            <image
              src="@/assets/reservation-images/close.png"
              mode="widthFix"
            />
          </view>
        </view>
        <view class="popup-content">
          <picker-view
            :indicator-style="indicatorStyle"
            :indicator-class="indicatorClass"
            :value="typeValue"
            :mask-style="maskStyle"
            :immediate-change="true"
            @change="bindTypeChange"
            class="picker-view"
          >
            <picker-view-column>
              <view
                class="item"
                v-for="(item, index) in typeList"
                :class="{ active: activeIndex == index }"
                :key="index"
                >{{ item.name }}</view
              >
            </picker-view-column>
          </picker-view>
        </view>
        <view class="popup-footer" @click="handleTypeConfirm">
          <fh-button>确认选择</fh-button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { fetchUserInfo, fetchAutoPhone, autoLoginByCode } from '@/api/user.js'
import { baseUrl } from '@/reservation/config'
import { ref, onMounted } from 'vue'
import CryptoJS from 'crypto-js'
import {
  getDateConfig,
  getTimeConfig,
  reservation,
  getGround,
} from '@/api/reservation'
import { useGlobalStore } from '@/stores/global.js'
import fhButton from '../components/fh-button.vue'
const globalStore = useGlobalStore()

defineOptions({
  name: 'subscribe',
})
const swiperIndex = ref(0)
// 工厂数据
const cardList = ref([])
// 当前选中的工厂信息
const currentGround = ref({
  ground: '',
  title: '',
  detail: '',
  image: '',
})
// 到访日期Ref
const datePanelRef = ref(null)
// 到访日期数据
const dateList = ref([])
// 到访时间数据
const timeList = ref([])
// 访客类型下拉框 配置
const typePanelRef = ref(null)
const indicatorStyle = ref('height: 50px')
const indicatorClass = ref('indicatorClass')
const maskStyle = ref('background: transparent !important;')
const typeValue = ref([0])
const activeIndex = ref(0)
// 访客类型数据
const typeList = ref([
  {
    type: 1,
    name: '内部学习/培训',
  },
  {
    type: 2,
    name: '产品/品牌体验',
  },
  {
    type: 3,
    name: '公众参观|科普教育',
  },
  {
    type: 4,
    name: '商业邀约/参观',
  },
  {
    type: 5,
    name: '社会团体/学术交流',
  },
  {
    type: 6,
    name: '政府考察/调研',
  },
  {
    type: 7,
    name: 'VIP/定向邀约',
  },
  {
    type: 8,
    name: '媒体/机构',
  },
  {
    type: 9,
    name: '其他',
  },
])

const formData = ref({
  reservation_date: '', // 到访日期
  reservation_time: '', // 到访时间
  realname: '', // 姓名
  telephone: '', // 电话
  visitor_number: '', // 参观人数
  ground: '', // 工厂
  type: '', // 参观类型
  typeStr: '', // 参观类型名称
})

onMounted(async () => {
  // 获取工厂数据
  await getGround({}).then((res) => {
    console.log(res, 'res')
    cardList.value = res.data
    // 设置当前选中的工厂
    currentGround.value = cardList.value[0] || {}
  })
  // 获取到访日期
  getDateConfig({}).then((res) => {
    dateList.value = res.data.map((item, index) => ({
      ...item,
      dayStr: formatDate(item.day),
      // 如果日期是今天，则设置为选中
      is_selected: item.day == formatDateCompare(),
    }))
    // 设置默认选中日期
    dateList.value.forEach((item) => {
      if (item.day == formatDateCompare()) {
        formData.value.reservation_date = item.day
      }
    })
    // 如果dateList 有值，则默认查询第一条数据的timeList
    if (dateList.value.length > 0) {
      getTimeList(dateList.value[0].day)
    }
  })
})
/**
 * 时间格式化
 * @param date 默认当前时间
 */
const formatDateCompare = (date = new Date()) => {
  const y = date.getFullYear()
  const m =
    date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  const d = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  return `${y}-${m}-${d}`
}

/**
 * 获取到访时间
 * @param day 到访日期 2025-07-11
 */
const getTimeList = (day) => {
  getTimeConfig({
    day: day,
    ground: cardList.value[swiperIndex.value].ground || '',
  }).then((res) => {
    timeList.value = res.data
    console.log(timeList.value, 'timeList')
  })
}
/**
 * 获取手机号
 */
const decryptPhoneNumber = async (e) => {
  if (e.detail.errMsg !== 'getPhoneNumber:ok') {
    uni.showToast({
      title: '请授权使用手机号',
      icon: 'none',
    })
    return
  }
  uni.showLoading({
    title: '加载中...',
  })
  uni.login({
    provider: 'weixin',
    success: async (res) => {
      if (res.errMsg === 'login:ok') {
        let data = e.detail
        getMobileByAuth(data, res)
      } else {
        uni.showToast({
          title: res.errMsg,
          icon: 'error',
        })
      }
    },
  })
}
/**
 * 解析手机号
 */
const getMobileByAuth = (data, res) => {
  fetchAutoPhone({
    phoneEncryptedData: data.encryptedData,
    phoneIv: data.iv,
    code: data.code,
    codeLogin: res.code,
  }).then((res) => {
    // 如果接口调用成功，则通过获取用户信息接口获取手机号
    console.log('解析手机号=>', res)
    // 再次登录
    uni.login({
      provider: 'weixin',
      success: (res) => {
        console.log('wxAutoLogin', res)
        if (res.errMsg === 'login:ok') {
          autoLoginByCodeFun(res.code)
        } else {
          uni.showToast({
            title: res.errMsg,
            icon: 'error',
          })
        }
      },
    })
    uni.hideLoading()
  })
}

const autoLoginByCodeFun = (code) => {
  autoLoginByCode(code).then((res) => {
    console.log('再次登录=>', res)
    if (res.data && res.data.cuk) {
      globalStore.setCuk(res.data.cuk)
      getUserInfo()
    }
  })
}

/**
 * 获取用户信息
 */
const getUserInfo = () => {
  fetchUserInfo({}).then((res) => {
    console.log('获取用户信息=>', res)
    let data = res.data
    if (data?.memberId !== 'not_login') {
      formData.value.telephone = data.mobile
      // 缓存用户memberId
      uni.setStorageSync('memberId', data?.memberId)
    }
  })
}

/**
 * 访客类型下拉框 选择事件
 */
const handleType = () => {
  typePanelRef.value.open('bottom')
}
/**
 * 访客类型下拉框 确认选择事件
 */
const handleTypeConfirm = () => {
  formData.value.typeStr = typeList.value[activeIndex.value].name
  formData.value.type = typeList.value[activeIndex.value].type
  typePanelRef.value.close()
}

/**
 * 轮播图 左滑事件
 */
const handleSwiperLeft = () => {
  swiperIndex.value--
  if (swiperIndex.value < 0) {
    swiperIndex.value = cardList.value.length - 1
  }
}
/**
 * 轮播图 右滑事件
 */
const handleSwiperRight = () => {
  swiperIndex.value++
  if (swiperIndex.value >= cardList.value.length) {
    swiperIndex.value = 0
  }
}
/**
 * 访客类型下拉框 选择事件
 * @param e 事件对象
 */
const bindTypeChange = (e) => {
  console.log(e, 'e')
  activeIndex.value = e.detail.value[0]
  formData.value.type = typeList.value[activeIndex.value].type
}

/**
 * 轮播图切换事件
 * @param e 事件对象
 */
const handleSwiperChange = (e) => {
  swiperIndex.value = e.detail.current
  formData.value.ground = cardList.value[swiperIndex.value].ground || ''
  currentGround.value = cardList.value[swiperIndex.value] || {}
  console.log(currentGround.value, 'currentGround')
  getTimeList(dateList.value[0].day)
}

const handleDate = () => {
  datePanelRef.value.open('bottom')
}

// 自定义时间处理函数，后续可以替换 将 2025-07-11 转成 07-11
const formatDate = (date) => {
  // 保留月和日
  return date.split('-').slice(1).join('-')
}
/**
 * 到访日期点击事件
 * @param item 到访日期对象
 */
const handleDateItemClick = (item) => {
  if (item.is_selected || item.isOpen == 0) return
  dateList.value.forEach((item) => {
    item.is_selected = false
  })
  item.is_selected = true
  // 设置formData.reservation_date
  formData.value.reservation_date = item.day
  getTimeList(item.day)
}
/**
 * 到访时间点击事件
 * @param item 到访时间对象
 */
const handleTimeItemClick = (item) => {
  if (item.is_selected || item.isOpen == 0) return
  timeList.value.forEach((item) => {
    item.is_selected = false
  })
  item.is_selected = true
  // 设置formData.reservation_time
  formData.value.reservation_time = item.time
}
/**
 * 日期和时间确认选择
 */
const handleDateConfirm = () => {
  // 判断日期是否选择
  if (!formData.value.reservation_date) {
    uni.showToast({
      title: '请选择日期',
      icon: 'none',
    })
    return
  }
  // 判断时间是否选择
  if (!formData.value.reservation_time) {
    uni.showToast({
      title: '请选择时间',
      icon: 'none',
    })
    return
  }
  datePanelRef.value.close()
}
// 校验表单,返回promise
const validateForm = () => {
  return new Promise((resolve, reject) => {
    if (!formData.value.reservation_date) {
      reject('请选择日期')
    }
    if (!formData.value.reservation_time) {
      reject('请选择时间')
    }
    if (!formData.value.realname) {
      reject('请填写姓名')
    }
    if (!formData.value.telephone) {
      reject('请填写手机号')
    }
    if (!formData.value.visitor_number) {
      reject('请填写访客人数')
    }
    // 判断访客人数是否为正整数
    if (
      !/^\d+$/.test(formData.value.visitor_number) ||
      formData.value.visitor_number <= 0
    ) {
      reject('访客人数请输入正整数')
    }
    if (!formData.value.type) {
      reject('请选择访客类型')
    }
    resolve()
  })
}
const handleSubmit = () => {
  // 校验表单
  validateForm()
    .then(() => {
      let o = {
        ...formData.value,
        ground: currentGround.value?.ground || '',
      }
      delete o.typeStr

      o.memberId = uni.getStorageSync('memberId')
      let requestBody
      const key = 'feihe2024reservation123456789012'
      const keyBytes = CryptoJS.enc.Utf8.parse(key)
      const jsonString = JSON.stringify(o)
      const encrypted = CryptoJS.AES.encrypt(jsonString, keyBytes, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7,
      }).toString()
      requestBody = {
        encrypted: encrypted,
      }
      reservation(requestBody).then((res) => {
        console.log(res, 'res')
        console.log('444')
        if (res.code == 0) {
          uni.showToast({
            title: '预约成功',
            icon: 'success',
          })
          uni.redirectTo({
            url: '/reservation/status/index?id=' + res.data.id,
          })
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'none',
          })
        }
      })
    })
    .catch((err) => {
      console.log(err, 'err')
      uni.showToast({
        title: err,
        icon: 'none',
      })
    })
}

const goToRecord = () => {
  uni.navigateTo({
    url: '/reservation/record/index',
  })
}
</script>

<style lang="less" scoped>
@import './index.less';
</style>
