<template>
  <view class="job-detail-container">
    <!-- 顶部信息区域 -->
    <view class="job-header">
      <view class="job-title">{{ jobDetail.title }}</view>
      <view class="job-salary">{{ jobDetail.salary }}</view>
      <view class="job-department">{{ jobDetail.department }}</view>
      
      <view class="job-requirements">
        <view class="requirement-item">
          <view class="dot"></view>
          <text>{{ formatLocation(jobDetail.location) }}</text>
        </view>
        <view class="requirement-item">
          <view class="time-icon"></view>
          <text>{{ jobDetail.experience }}</text>
        </view>
      </view>
    </view>
    
    <!-- 工作地点区域 -->
    <view class="section">
      <view class="section-title">工作地点</view>
      <view class="map-container">
        <map
          id="jobLocationMap"
          class="map"
          :latitude="mapInfo.latitude"
          :longitude="mapInfo.longitude"
          :markers="mapInfo.markers"
          :scale="16"
          @tap="openLocation"
        ></map>
        <!-- <view class="location-text">{{ jobDetail.location }}</view> -->
      </view>
    </view>
    
    <!-- 福利待遇区域 -->
   <!--  <view class="section">
      <view class="section-title">福利待遇</view>
      <view class="benefits-list">
        <view class="benefit-tag" >暂无数据</view>
      </view>
    </view> -->
    
    <!-- 岗位介绍区域 -->
    <view class="section">
      <view class="section-title">岗位介绍</view>
      <view class="job-description">
      <!--   <view class="description-subtitle">{{ jobDetail.description[0].subtitle }}</view> -->
        <view class="description-content">
          <view class="description-item" v-for="(item, index) in jobDetail.description[0].items" :key="index">
            <view class="blue-dot"></view>
            <template v-if="hasHtmlTags(item)">
              <view class="description-text" v-html="item"></view>
            </template>
            <template v-else>
              <text style="color: #333;">{{ item }}</text>
            </template>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 右侧开始面试按钮 -->
    <view class="interview-button" @click="startInterview">
      <text>开始面试</text>
    </view>
  </view>
</template>

<script>
	import { apiBaseUrl } from '@/common/config.js';
	import { applyJob } from '@/api/user.js';
export default {
  data() {
    return {
      jobDetail: {
        title: '',
        salary: '',
        department: '',
        location: '',
        experience: '',
        benefits: [],
        description: [
          {
            subtitle: '岗位要求',
            items: []
          }
        ]
      },
      selectedJobId: null,
      jobId: null,
      mapInfo: {
        latitude: 0,
        longitude: 0,
        markers: []
      }
    }
  },
  onLoad(options) {
    this.jobId = options.id;
    this.getJobDetail(options.id);

    // 尝试从本地存储获取职位详情
    try {
      const jobDetailStr = uni.getStorageSync('currentJobDetail');
      if (jobDetailStr) {
        const jobData = JSON.parse(jobDetailStr);
        // 这里可以根据实际数据结构进行处理
        // 如果后端返回的数据结构与页面需要的不一致，可以在这里进行转换
        this.jobDetail = {
          ...this.jobDetail,
          title: jobData.title || this.jobDetail.title,
          salary: jobData.salary || this.jobDetail.salary,
          department: jobData.department || this.jobDetail.department,
          location: jobData.location || this.jobDetail.location,
          experience: jobData.experience || this.jobDetail.experience,
          benefits: jobData.benefits || this.jobDetail.benefits,
          description: jobData.description || this.jobDetail.description
        };
      }
    } catch (e) {
      console.error('获取职位详情失败:', e);
    }
  },
  methods: {
    async getJobDetail(jobId) {
      try {
        const { data } = await uni.request({
          url: `${apiBaseUrl}/api/mini/job/detail?id=${jobId}&tenant_id=1`,
          method: 'GET',
        });
        
        if (data.code === 2000) {
          // 处理富文本description
          let descriptionItems = [];
          if (data.data.description) {
            // 使用正则表达式提取<li>标签中的文本内容
            const liRegex = /<li[^>]*>(.*?)<\/li>/g;
            const stripTagsRegex = /<[^>]*>/g;
            
            let match;
            while ((match = liRegex.exec(data.data.description)) !== null) {
              // 移除剩余的HTML标签，并清理空白字符
              const text = match[1]
                .replace(stripTagsRegex, '')
                .replace(/&nbsp;/g, ' ')
                .trim();
              
              if (text) {
                descriptionItems.push(text);
              }
            }
          }

          // 如果requirements存在，添加到描述项前面
          if (data.data.requirements) {
            descriptionItems.unshift(data.data.requirements);
          }

          this.jobDetail = {
            id: data.data.id,
            title: data.data.title || '',
            salary: data.data.salary_range ? `${data.data.salary_range}/月` : '',
            department: `${data.data.department || ''} ${data.data.job_type === 1 ? '全职' : '兼职'}`,
            location: data.data.location || '',
            experience: data.data.work_experience_required || '不限',
            benefits: data.data.competency_tags || ['五险一金', '带薪年假', '定期体检'],
            description: [
              {
                subtitle: '岗位要求',
                items: descriptionItems
              }
            ]
          };

          // 获取职位详情后，更新地图信息
          this.updateMapLocation(data.data.location);
        } else {
          uni.showToast({
            title: '获取职位详情失败',
            icon: 'none'
          });
        }
      } catch (e) {
        console.error('获取职位详情失败:', e);
        uni.showToast({
          title: '获取职位详情失败',
          icon: 'none'
        });
      }
    },
    checkLogin() {
      const userInfo = uni.getStorageSync('userInfo');
      if (!userInfo) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return false;
      }
      return true;
    },
	// 获取当前职位配置
	getConfig(selectedJobId){
		uni.request({
			url: `${apiBaseUrl}/api/job/config/position/${this.jobId}`,
			method: 'GET',
			data: {
				openid: JSON.parse(uni.getStorageSync('userInfo')).openid
			},
			header: {
				'content-type': 'application/x-www-form-urlencoded'
			},
			success: (res) => {
				// 身份验证成功后，继续提交用户信息
				console.log(res);
				if (res.statusCode === 200) {
					if (res.data.code === 2000) {
						uni.setStorageSync('configData', JSON.stringify(res.data.data))
						uni.navigateTo({
							url: '/pages/Personal/Personal',
							fail: (err) => {
								console.error('页面跳转失败:', err);
								uni.showToast({
									title: '页面跳转失败',
									icon: 'none'
								});
							}
						});
					} else {
						
					}
				} else {
					uni.hideLoading();
					
				}
			},
			fail: (err) => {
				uni.hideLoading();
				uni.showToast({
					title: '网络错误，请稍后重试',
					icon: 'none'
				});
			}
		});
	},
    async startInterview() {
      if (!this.checkLogin()) {
        return;
      }

      try {
        // 保存所选职位信息
        uni.setStorageSync('selectedJob', JSON.stringify(this.jobDetail));
        
        const userInfo = JSON.parse(uni.getStorageSync('userInfo'));
        const response = await applyJob({
          job_id: this.jobId,
          tenant_id: 1,
          openid: userInfo.openid
        });

        if (response && response.id) {
          // 保存应用ID到本地
          uni.setStorageSync('appId', response.id);
          
          // 更新userInfo对象
          try {
            userInfo.appId = response.id;
            uni.setStorageSync('userInfo', JSON.stringify(userInfo));
          } catch (e) {
            console.error('更新用户信息失败:', e);
          }
		  this.getConfig(userInfo.appId)
          // 导航到摄像头页面
          // uni.navigateTo({
          //   url: '/pages/Personal/Personal',
          //   fail: (err) => {
          //     console.error('页面跳转失败:', err);
          //     uni.showToast({
          //       title: '页面跳转失败',
          //       icon: 'none'
          //     });
          //   }
          // });
        }
      } catch (err) {
        console.error('申请职位失败:', err);
        uni.showToast({
          title: '申请职位失败，请重试',
          icon: 'none'
        });
      }
    },
    hasHtmlTags(text) {
      // 检查文本是否包含HTML标签
      const htmlRegex = /<[^>]*>/;
      return htmlRegex.test(text);
    },
    formatLocation(location) {
      if (!location) return '';
      
      // 处理字符串形式的数组
      if (typeof location === 'string' && location.startsWith('[')) {
        try {
          const locationArray = JSON.parse(location.replace(/'/g, '"'));
          return locationArray.join(' ');
        } catch (e) {
          console.error('解析location失败:', e);
          return location;
        }
      }
      
      // 处理数组格式
      if (Array.isArray(location)) {
        return location.join(' ');
      }
      
      // 处理对象格式
      if (typeof location === 'object' && location !== null) {
        const { province, city, district } = location;
        if (province && city) {
          return province + ' ' + city + (district ? ' ' + district : '');
        }
      }
      
      // 处理普通字符串格式
      return location;
    },
    // 更新地图位置信息
    async updateMapLocation(location) {
      try {
        // 如果location是字符串数组，转换为地址字符串
        let addressStr = '';
        if (typeof location === 'string' && location.startsWith('[')) {
          try {
            const locationArray = JSON.parse(location.replace(/'/g, '"'));
            addressStr = locationArray.join('');
          } catch (e) {
            addressStr = location;
          }
        } else if (Array.isArray(location)) {
          addressStr = location.join('');
        } else if (typeof location === 'object' && location !== null) {
          const { province, city, district } = location;
          addressStr = `${province || ''}${city || ''}${district || ''}`;
        } else {
          addressStr = location;
        }

        // 使用微信小程序的地址解析接口WJLBZ-SMQYZ-3RNX5-7J4LI-XTZD6-7IBZR
        uni.request({
          url: `https://apis.map.qq.com/ws/geocoder/v1/?address=${encodeURIComponent(addressStr)}&key=ZS4BZ-NKAA7-4VLXR-PHVI4-HAGPH-Z4FJ3`, // 需要替换为实际的地图Key
          success: (res) => {
            if (res.data.status === 0) {
              const { lat, lng } = res.data.result.location;
              this.mapInfo.latitude = lat;
              this.mapInfo.longitude = lng;
              this.mapInfo.markers = [{
                id: 1,
                latitude: lat,
                longitude: lng,
                title: addressStr
              }];
            } else {
              console.error('地址解析失败:', res);
            }
          },
          fail: (err) => {
            console.error('地址解析请求失败:', err);
          }
        });
      } catch (error) {
        console.error('更新地图位置失败:', error);
      }
    },
    openLocation() {
      if (this.mapInfo.latitude && this.mapInfo.longitude) {
        uni.openLocation({
          latitude: this.mapInfo.latitude,
          longitude: this.mapInfo.longitude,
          name: this.jobDetail.title,
          address: this.formatLocation(this.jobDetail.location),
          success: function () {
            console.log('导航打开成功');
          },
          fail: function (err) {
            console.error('导航打开失败:', err);
            uni.showToast({
              title: '导航打开失败',
              icon: 'none'
            });
          }
        });
      } else {
        uni.showToast({
          title: '暂无位置信息',
          icon: 'none'
        });
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.job-detail-container {
  padding: 20rpx;
  position: relative;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.job-header {
  padding: 20rpx 0;
}

.job-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.job-salary {
  font-size: 32rpx;
  color: #ff6b00;
  margin-bottom: 10rpx;
}

.job-department {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 20rpx;
}

.job-requirements {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.requirement-item {
  display: flex;
  align-items: center;
  margin-right: 30rpx;
  font-size: 26rpx;
  color: #666;
}

.dot {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
  background-color: #0052d9;
  margin-right: 10rpx;
}

.time-icon {
  width: 26rpx;
  height: 26rpx;
  background-color: #999;
  border-radius: 50%;
  margin-right: 10rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18rpx;
  color: #fff;
}

.section {
  margin-bottom: 30rpx;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.map-container {
  position: relative;
  border-radius: 16rpx;
  overflow: hidden;
}

.map {
  width: 100%;
  height: 500rpx;
  border-radius: 16rpx;
}

.location-text {
  position: absolute;
  left: 20rpx;
  bottom: 20rpx;
  background-color: rgba(0, 0, 0, 0.6);
  color: #fff;
  font-size: 24rpx;
  padding: 6rpx 12rpx;
  border-radius: 6rpx;
}

.benefits-list {
  display: flex;
  flex-wrap: wrap;
}

.benefit-tag {
  background-color: #f5f5f5;
  color: #666;
  font-size: 26rpx;
  padding: 10rpx 20rpx;
  border-radius: 6rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
}

.description-subtitle {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
}

.description-content {
  padding-left: 10rpx;
}

.description-item {
  display: flex;
  margin-bottom: 20rpx;
  
 
/*   * {
    background-color: #fff !important;
    color: #333 !important;
  }

  strong {
    font-weight: bold;
  } */
}

.blue-dot {
  min-width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
  background-color: #0039b3 !important;
  margin-right: 10rpx;
  margin-top: 12rpx;
}

.description-item text {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
}

.interview-button {
  position: fixed;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  background-color: #0039b3;
  color: #fff;
  writing-mode: vertical-lr;
  padding: 30rpx 20rpx;
  font-size: 32rpx;
  border-top-left-radius: 16rpx;
  border-bottom-left-radius: 16rpx;
}

.description-text {
  font-size: 26rpx;
  color: #333;
  line-height: 1.6;
  flex: 1;

  :deep(p) {
    margin: 0;
  }
  
  :deep(a) {
    color: #0039b3;
    text-decoration: none;
  }
  
  :deep(strong) {
    font-weight: bold;
  }
}
</style> 