<template>
  <view class="resume-container">
    <!-- 导航栏 -->
    <navBar title="近期工作经验" color="#000" />

    <view class="resume-content">
      <!-- 头像上传区域 -->
      <view class="form-label">头像</view>
      <view class="avatar-section">
        <view class="avatar-upload" @click="chooseAvatar">
          <view class="avatar-preview">
            <image v-if="formData.avatar" :src="formData.avatar" class="avatar-image" mode="aspectFill"></image>
            <image v-else src="@/static/images/jobApplicant/touxiang.svg" mode="scaleToFill" class="user-img" />
          </view>
          <view class="upload-view">上传头像</view>
        </view>
      </view>

      <!-- 基本信息表单 -->
      <view class="form-section">
        <!-- 姓名 -->
        <view class="form-item required">
          <view class="form-label">姓名</view>
          <u-input placeholder="请输入姓名" v-model="formData.name" :border="false" class="form-input"></u-input>
        </view>

        <!-- 性别 -->
        <view class="form-item required">
          <view class="form-label">性别</view>
          <view class="gender-select">
            <view class="gender-option" @click="formData.gender = 1">
              <image v-if="formData.gender === 1" src="/static/images/jobApplicant/radio-check.svg"
                mode="scaleToFill" />
              <image v-else src="/static/images/jobApplicant/radio.svg" mode="scaleToFill" />
              男
            </view>
            <view class="gender-option" @click="formData.gender = 2">
              <image v-if="formData.gender === 2" src="/static/images/jobApplicant/radio-check.svg"
                mode="scaleToFill" />
              <image v-else src="/static/images/jobApplicant/radio.svg" mode="scaleToFill" />
              女
            </view>
          </view>
        </view>

        <!-- 联系方式 -->
        <view class="form-item required">
          <view class="form-label">联系方式</view>
          <u-input placeholder="请输入联系方式" v-model="formData.phone" :border="false" class="form-input"></u-input>
        </view>

        <!-- 出生年月 -->
        <view class="form-item required">
          <view class="form-label">出生年月</view>
          <view @click="pickerShow" class="form-input-time">
            <text>{{
              formData.birthDate ? formData.birthDate : "请选择出生年月日"
            }}</text>
            <image src="@/static/images/jobApplicant/rili.svg" mode="scaleToFill" />
          </view>
        </view>

        <!-- 求职状态 -->
        <view class="form-item required">
          <view class="form-label">求职状态</view>
          <view @click.stop="showJobStatus" class="form-input-time">
            <text>{{ statusList[formData.jobStatus].text }}</text>
            <image src="@/static/images/jobApplicant/icon-next.svg" mode="scaleToFill" />
          </view>
        </view>
      </view>

      <!-- 工作经历 -->
      <view class="section">
        <view class="section-header">
          <view class="form-item required">
            <view class="job-title">
              <view class="job-title-txt">工作经历 <text class="job-txt">请填写专属聘用行业的工作经验</text></view>
              <image @click="goWorkProgress" class="job-image" src="@/static/images/jobApplicant/edit.svg"
                mode="scaleToFill" />
            </view>
          </view>
        </view>

        <view class="experience-item" v-for="(exp, index) in workExperiences" :key="index" @click.stop="goToWorkExperience(exp.workExpId)">
          <view class="job-content">
            <view class="job-icon">
              <image src="/static/images/jobApplicant/xuexiao.svg" mode="scaleToFill" />
            </view>
            <view class="right-content">
              <view class="job-content-txt" v-for="it in exp.workExpDetails">
                <view class="exp-header">
                  <view class="exp-position">
                    <view class="position">{{ it.position }}</view>
                    <view class="department">{{ it.department }}</view>
                  </view>
                  <!-- <u-icon
                  name="close"
                  size="18"
                  color="#999"
                  @click="removeWorkExperience(index)"
                ></u-icon> -->
                </view>
                <view class="exp-company">
                  <view class="company">{{ exp.companyName }}</view>
                  <view class="yuan">·</view>
                  <view class="duration">{{ it.startTime }} - {{ it.endTime }}</view>
                </view>
                <!-- <view class="exp-content">
                  <view class="content-label">{{ it.workContent }}</view>
                </view> -->
				<view style="margin-bottom: 10rpx;font-size: 22rpx;">工作内容</view>
				<view class="content-label">
					{{ it.workContent }}
				</view>
				<view style="margin: 12rpx 0;font-size: 22rpx;">工作业绩</view>
				<view class="content-label">
					{{it.workPerformance}}
				</view>
                <view class="exp-content">
                  <view class="skill-tags">
                    <view class="tag" v-for="skill in it.skills">{{ skill }}</view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 教育经历 -->
      <view class="section">
        <view class="section-header">
          <view class="form-item required">
            <view class="job-title">
              <view class="job-title-txt">教育经历</view>
              <image @click="goEducationalBackground('')" class="job-image" src="@/static/images/jobApplicant/edit.svg"
                mode="scaleToFill" />
            </view>
          </view>
        </view>

        <view class="experience-item" v-for="(item, index) in eduList" :key="index" @click.stop="goEducationalBackground(item.eduId)">
          <view class="job-content">
            <view class="job-icon">
              <image src="/static/images/jobApplicant/bumen.svg" mode="scaleToFill" />
            </view>
            <view class="job-content-txt">
              <view class="exp-header">
                <view class="exp-position">
                  <view class="position">{{ item.school }}</view>
                </view>
              </view>
              <view class="exp-company">
                <view class="company">{{ item.degree }}</view>
                <view class="yuan">·</view>
                <view class="duration">{{ item.profession }}</view>
                <view class="yuan">·</view>
                <view class="duration">{{ new Date(item.startTime).getFullYear() }} - {{ new
                  Date(item.endTime).getFullYear()}}</view>
              </view>
              <view class="exp-content">
                <view class="content-label">{{ item.detail }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 个人优势 -->
      <view class="section">
        <view class="section-header">
          <view class="form-item required">
            <view class="job-title">
              <view class="job-title-txt">个人优势</view>
              <!-- <image
                class="job-image"
                src="@/static/images/jobApplicant/edit.svg"
                mode="scaleToFill"
              /> -->
            </view>
          </view>
        </view>
        <view class="advantage-content">
          <view type="textarea" class="advantage-textarea">
            <textarea placeholder="请输入个人优势" v-model="formData.advantages" class=""></textarea>
          </view>
        </view>
      </view>

      <!-- 底部按钮 -->
      <view class="footer">
        <u-button type="primary" @click="submitResume" :customStyle="{
          height: '90rpx',
          fontSize: '32rpx',
          borderRadius: '45rpx',
          margin: '40rpx 0',
        }">开启求职之旅</u-button>
      </view>
    </view>
    <u-picker v-model="showBirthDatePicker" :columns="dateColumns" keyName="label" @confirm="confirmBirthDate"
      @cancel="showBirthDatePicker = false"></u-picker>
    <u-action-sheet :list="statusList" v-model="showStatus" @click="confirmStatus"></u-action-sheet>
    <!-- 权限说明弹窗 -->
    <u-popup mode="top" ref="permission">
      <view class="popup-content">
        <view class="popup-text-permission">选择/拍摄照片需要相机/相册权限，用于上传用户头像</view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import navBar from "@/components/nav-bar/index.vue";
export default {
  data() {
    // 生成日期选择器数据
    const currentYear = new Date().getFullYear();
    const years = [];
    const months = [];
    const days = [];

    for (let i = currentYear - 50; i <= currentYear; i++) {
      years.push({ label: i + "年", value: i });
    }

    for (let i = 1; i <= 12; i++) {
      months.push({ label: i + "月", value: i });
    }

    for (let i = 1; i <= 31; i++) {
      days.push({ label: i + "日", value: i });
    }

    return {
      show: false,
      showBirthDatePicker: false,
      dateColumns: [years, months, days],
      statusList: [
        {
          value: '0',
          text: '离职-随时到岗'
        },
        {
          value: '1',
          text: '在职-月内到岗',

        },
        {
          value: '2',
          text: '在职-考虑机会',

        },
        {
          value: '3',
          text: '在职-暂不考虑',
        },
		// {
		// 	value: '4',
		// 	text: '实习',
		// }
      ],
      showStatus: false,
      formData: {
        avatar: "",
        name: "",
        gender: 1,
        jobStatus: 0,
        phone: '',
        birthDate: "",
        advantages: "",
        ifExp: 0
      },
      workExperiences: [
        {
          companyName: "公司名称",
          workExpDetails: [{
            department: "部门",
            position: "职位名称",
            startTime: "就职时间",
            endTime: "离职时间",
            workContent: "请填写简历工作内容",
            skills: ["请填写面试技能要求"],
          }
          ]
        },
      ],
	  hasEcommerceExperience: false,
      eduList: [{
        school: "学校时间",
        profession: "专业",
        startTime: "2012-09-1",
        endTime: "2016-6-10",
        detail: "请填写您的教育经历",
        degree: "学历",
      }
      ]
    };
  },
  components: {
    navBar,
  },
  onLoad() {
    this.getData()
    var that = this
    uni.$on('updateResume', () => {
      that.getData()
    })
  },
  methods: {
    getData() {
      var that = this
      this.$Request.getT("/app/userFirst/getUserResumes", {}).then((res) => {
        if (res.code == 0) {
			that.hasEcommerceExperience = res.data.resumeList && res.data.resumeList.ifExp ? true :
				false
          res.data.workExps.forEach(function (item) {
            item.type = JSON.parse(item.type)
            item.workExpDetails = []
            res.data.workExpList.forEach(function (it) {
              it.skills = JSON.parse(it.skills)
              it.startTime = it.startTime.slice(0, 7);
              if (that.$queue.isCurrentMonth(new Date(it.endTime)))
                it.endTime = '至今'
              else
                it.endTime = it.endTime.slice(0, 7);
              if (it.workExpId == item.workExpId)
                item.workExpDetails.push(it)
            })
          })
          if (res.data.workExps.length > 0)
            that.workExperiences = res.data.workExps
          if (res.data.eduList.length > 0)
            that.eduList = res.data.eduList
          that.formData.ifExp = res.data.resumeList.ifExp
        } else {
          uni.showToast({
            title: res.msg,
            icon: "none",
          });
        }
      });
    },
    showJobStatus() {
      this.showStatus = true;
    },
    pickerShow() {
      this.showBirthDatePicker = true;
    },
    confirmStatus(e) {
      this.showStatus = false;
      this.formData.jobStatus = e
    },
    goWorkProgress() {
      uni.navigateTo({ url: '/pages/my/workExperience' })
    },
    goEducationalBackground(id = '') {
      uni.navigateTo({
      	url: `/pages/my/educationExperience?id=${id}`
      })
    },
    // 选择头像
    async chooseAvatar() {
      var that = this
      // 1. 检查权限状态
      const hasPermission = await this.$queue.checkPermission(
        'camera',
        '选择/拍摄照片需要相机/相册权限，用于上传用户头像',
        this
      );

      // 2. 如果未授权或者用户拒绝，显示提示
      if (!hasPermission) {
        return;
      }
      uni.chooseImage({
        count: 1,
        sizeType: ["compressed"],
        sourceType: ["album", "camera"],
        success: (res) => {
          that.$queue.uploadFile(res.tempFilePaths[0], function (path) {
            if (path)
              that.formData.avatar = path;
          })
        },
      });
    },

    // 确认出生日期
    confirmBirthDate(e) {
      const { year, month, day } = e;
      this.formData.birthDate = `${year}-${month}-${day}`;
      this.showBirthDatePicker = false;
    },

    // 添加工作经历
    addWorkExperience() {
      this.workExperiences.push({
        position: "职位",
        department: "部门",
        company: "公司名称",
        duration: "就职时间",
        content: "请填写简历工作内容",
        skills: "请填写面试技能要求",
      });
    },
	goToWorkExperience(id = '') {
		// 获取业务类型数据
		const businessTypes = this.getBusinessTypes()
		uni.navigateTo({
			url: `/pages/my/workExperience?id=${id}&businessTypes=${encodeURIComponent(JSON.stringify(businessTypes))}`
		})
	},
	getBusinessTypes() {
		// 根据是否有跨境电商经验返回业务类型
		if (this.hasEcommerceExperience) {
			return ['0']
		} else {
			return []
		}
	},
    // 删除工作经历
    removeWorkExperience(index) {
      if (this.workExperiences.length > 1) {
        this.workExperiences.splice(index, 1);
      } else {
        uni.showToast({
          title: "至少保留一条工作经历",
          icon: "none",
        });
      }
    },

    // 提交简历
    submitResume() {
      var that = this
      if (!this.formData.name) {
        uni.showToast({ title: "请输入姓名", icon: "none" });
        return;
      }
      if (!this.formData.gender) {
        uni.showToast({ title: "请选择性别", icon: "none" });
        return;
      }
      if (!this.formData.birthDate) {
        uni.showToast({ title: "请输入出生年月", icon: "none" });
        return;
      }
      let age = this.$queue.calculateAgeFromBirthday(this.formData.birthDate) || 0
      let data = {
        avatar: this.formData.avatar,
        userName: this.formData.name,
        age,
        sex: this.formData.gender,
        phone: this.formData.phone
      }
      uni.showLoading({ title: "提交中..." });
      this.$Request.postJson("/app/user/updateUser", data).then((res) => {
        uni.hideLoading();
        if (res.code == 0) {
          that.setResume()
        } else {
          uni.showToast({
            title: res.msg,
            icon: "none",
          });
        }
      });
    },
    setResume() {
      let data = {
        birthday: this.formData.birthDate,
        resumesStatus: this.formData.jobStatus,
        adv: this.formData.advantages,
        ifExp: this.formData.ifExp,
      }
      this.$Request.postJson("/app/userFirst/regist", data).then((res) => {
        if (res.code == 0) {
          // 实际开发中可以在这里添加跳转逻辑
          uni.showToast({ title: "提交成功", icon: "none" });
          uni.setStorageSync("firstLogin", true);
          // 实际开发中可以在这里添加跳转逻辑
          setTimeout(() => {
            uni.switchTab({ url: '/pages/index/index' })
          }, 1000);
        } else {
          uni.showToast({
            title: res.msg,
            icon: "none",
          });
        }
      });
    }
  },
};
</script>

<style lang="scss" scoped>
.resume-container {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

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

.job-image {
  width: 48rpx;
  height: 48rpx;
}

.nav-bar {
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #000;
}

.resume-content {
  padding: 32rpx;
  box-sizing: border-box;
  overflow: hidden;
  overflow-y: auto;
}

/* 头像区域 */
.avatar-section {
  display: flex;
}

.avatar-upload {
  display: flex;
  align-items: center;
}

.avatar-preview {
  width: 48rpx;
  height: 48rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
}

.avatar-image {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.upload-view {
  color: #016bf6;
  font-family: DM Sans;
  font-size: 20rpx;
  font-weight: 500;
  line-height: 48rpx;
}

.form-item {
  padding-bottom: 24rpx;
  box-sizing: border-box;

  .job-txt {
    color: #016bf6;
    font-family: DM Sans;
    font-size: 20rpx;
    margin-left: 16rpx;
  }
}

.form-item:last-child {
  border-bottom: none;
}

.form-label {
  color: #1f2c37;
  font-family: DM Sans;
  font-size: 28rpx;
  font-weight: 500;
  line-height: 44rpx;
  padding-top: 30rpx;
  padding-bottom: 27rpx;
  box-sizing: border-box;
}

.form-input {
  flex: 1;
  box-sizing: border-box;
  border: 2rpx solid #9ea1a8;
  border-radius: 100rpx;
  background: rgba(255, 255, 255, 1);
  padding: 0rpx 24rpx !important;
}

.form-input-time {
  flex: 1;
  box-sizing: border-box;
  border: 2rpx solid #e3e7ec;
  border-radius: 100rpx;
  background: rgba(255, 255, 255, 1);
  padding: 10rpx 24rpx;
  color: rgba(153, 153, 153, 1);
  font-family: DM Sans;
  font-size: 24rpx;
  font-weight: 500;
  display: flex;
  justify-content: space-between;
  align-items: center;

  image {
    width: 48rpx;
    height: 48rpx;
  }
}

::v-deep .input-placeholder {
  color: rgba(153, 153, 153, 1) !important;
  font-family: DM Sans;
  font-size: 24rpx !important;
  font-weight: 500;
}

.user-img {
  width: 48rpx;
  height: 48rpx;
}

.required .form-label::before {
  content: "*";
  color: #fa3534;
  margin-right: 8rpx;
}

/* 性别选择 */
.gender-select {
  display: flex;
  flex: 1;
  gap: 40rpx;
}

.gender-option {
  display: flex;
  align-items: center;
  color: #171725;
  font-family: DM Sans;
  font-size: 24rpx;
  font-weight: 400;
  line-height: 48rpx;
  text-align: left;

  image {
    width: 32rpx;
    height: 32rpx;
    margin-right: 8rpx;
  }
}

.phone-view,
.job-status {
  flex: 1;
  font-size: 32rpx;
  color: #333;
}

.section {
  box-sizing: border-box;
  border: 2rpx solid #016bf6;
  border-radius: 24rpx;
  background: #fff;
  padding: 32rpx;
  box-sizing: border-box;
  margin-bottom: 30rpx;
}

.section-header {
  margin-bottom: 24rpx;
}

/* 经历项目 */
.experience-item {
  border-radius: 12rpx;
  padding: 24rpx;
  box-sizing: border-box;
}

.job-content {
  display: flex;
  gap: 42rpx;

  .job-icon {
    width: 96rpx;
    height: 96rpx;
    border-radius: 16rpx;
    background: rgba(246, 246, 246, 1);
    display: flex;
    justify-content: center;
    align-items: center;
    flex-shrink: 0;

    image {
      width: 64rpx;
      height: 64rpx;
    }
  }

  .right-content {
    width: 100%;
  }

  .job-content-txt {
    margin-bottom: 20rpx;
  }
}

.exp-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.exp-position {
  display: flex;
  align-items: center;
}

.position {
  color: #171725;
  font-family: DM Sans;
  font-size: 28rpx;
  font-weight: 400;
  line-height: 44rpx;
  text-align: left;
}

.department {
  font-size: 24rpx;
  color: #999;
  margin-left: 16rpx;
}

.exp-company {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
  color: #78828a;
  font-family: DM Sans;
  font-size: 16rpx;
  font-weight: 400;
  line-height: 40rpx;
  text-align: left;

  .yuan {
    padding: 0 16rpx;
    box-sizing: border-box;
    font-size: 40rpx;
  }
}

.exp-content {
  margin-bottom: 12rpx;
}

.exp-content:last-child {
  margin-bottom: 0;
}

.content-label {
  color: rgba(120, 130, 138, 1);
  font-family: DM Sans;
  font-size: 16rpx;
  font-weight: 400;
  line-height: 20rpx;
  text-align: left;
  margin-bottom: 10rpx;
  white-space: pre-wrap;
}

.skill-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8rpx;
  margin-top: 12rpx;

  .tag {
    background: rgba(153, 153, 153, 0.1);
    border-radius: 12rpx;
    padding: 6rpx;
    color: rgba(102, 102, 102, 1);
    font-family: DM Sans;
    font-size: 16rpx;
    font-weight: 400;
    letter-spacing: 0%;
    text-align: left;
  }
}

.content-view {
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
}

/* 教育经历 */
.education-item {
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;
}

.edu-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.edu-school {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.edu-info {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
}

.edu-degree,
.edu-major,
.edu-duration {
  font-size: 28rpx;
  color: #666;
  margin-right: 20rpx;
}

.edu-content {
  margin-top: 12rpx;
}

.add-view {
  font-size: 28rpx;
  margin-left: 12rpx;
}

.advantage-textarea {
  color: rgba(120, 130, 138, 1);
  font-family: DM Sans;
  font-size: 24rpx;
  font-weight: 400;
  line-height: 32rpx;
  padding: 32rpx;
  padding-top: 0;
  box-sizing: border-box;
}

.footer {
  padding-bottom: 40rpx;
}

::v-deep .u-input {
  text-align: left !important;
}
</style>
