<template>
  <!-- 模考报名页面 -->
  <view class="exam_apply">
    <nav-bar title="模考报名" class="navbar"></nav-bar>
    <!-- background="{ background: '#498AFE' }" -->
    <image class="mock_bg" :src="$method.splitImgHost('oss/images/file/20240424/1713920366161.png')"></image>
    <!-- <u-navbar :is-back="false" title="模考报名" :border-bottom="false"  title-color="#fff" back-icon-color="#ffffff" background="{ background: '#498AFE' }">
		</u-navbar> -->

    <!-- <u-line color="#D6D6DB" /> -->
    <view class="mains">
      <u-form :model="examform" ref="uForm" :rules="rules" label-width="74">
        <view class="items">
          <view class="item_title">
            <text class="star_red">*</text>
            <text class="number">01</text>
            <text class="category">姓名</text>
          </view>
          <u-form-item
            label=" "
            label-width="74"
            prop="userName"
            :border-bottom="false"
          >
            <view class="inputs">
              <input
                v-model.trim="examform.userName"
                class="uni-input"
                placeholder="请输入"
              />
            </view>
          </u-form-item>
        </view>

        <view class="items">
          <view class="item_title">
            <text class="star_red">*</text>
            <text class="number">02</text>
            <text class="category">性别</text>
          </view>
          <u-form-item
            label=" "
            label-width="74"
            prop="userSex"
            :border-bottom="false"
          >
            <u-radio-group
              v-model="examform.userSex"
              :wrap="true"
              @change="radioGroupChange"
            >
              <u-radio value="1" name="1">男</u-radio>
              <u-radio value="2" name="2">女</u-radio>
            </u-radio-group>
          </u-form-item>
        </view>

        <view class="items">
          <view class="item_title">
            <!-- <text class="star_red">*</text> -->
            <text class="number">03</text>
            <text class="category">企业名称</text>
          </view>
          <u-form-item
            label=" "
            label-width="74"
            prop="companyName"
            :border-bottom="false"
          >
            <view class="inputs">
              <input
                v-model.trim="examform.companyName"
                class="uni-input"
                placeholder="请输入"
              />
            </view>
          </u-form-item>
        </view>

        <!-- <view class="items">
                    <view class="item_title">
                        <text class="star_red">*</text>
                        <text class="number">04</text>
                        <text class="category">身份证号</text>
                    </view>
                    <u-form-item label=" " label-width="74" prop="userIdCard" :border-bottom='false'>
                        <view class="inputs">
                            <input v-model.trim="examform.userIdCard" class="uni-input" placeholder="请输入" />
                        </view>
                    </u-form-item>
                </view> -->

        <!-- <view class="items">
                    <view class="item_title">
                        <text class="star_red">*</text>
                        <text class="number">04</text>
                        <text class="category">手机号码</text>
                    </view>
                    <u-form-item label=" " label-width="74" prop="userPhone" :border-bottom='false'>
                        <view class="inputs">
                            <input v-model.trim="examform.userPhone" class="uni-input" placeholder="请输入" />
                        </view>
                    </u-form-item>
                </view> -->
        <view class="items">
          <view class="item_title">
            <text class="star_red">*</text>
            <text class="number">04</text>
            <text class="category">报考业务</text>
          </view>
          <u-form-item
            label=" "
            label-width="74"
            prop="majorId"
            :border-bottom="false"
          >
            <view class="inputs">
              <view class="item_box">
                <picker
                  class="picker"
                  mode="selector"
                  :range="majorList"
                  range-key="majorName"
                  :value="examform.majorId"
                  @change="majorChange"
                >
                  <view class="pick_con" style="fontsize: 40rpx">{{
                    majorName
                  }}</view>
                </picker>
                <u-icon class="icon" name="arrow-down"></u-icon>
              </view>
            </view>
          </u-form-item>
        </view>
        <view class="items">
          <view class="item_title">
            <text class="star_red">*</text>
            <text class="number">05</text>
            <text class="category">报考科目</text>
          </view>
          <u-form-item
            label=" "
            label-width="74"
            prop="userMajors"
            :border-bottom="false"
          >
            <template v-if="subjectLists.length">
              <u-checkbox-group :wrap="true" @change="checkboxGroupChange">
                <u-checkbox
                  v-model="item.checked"
                  v-for="(item, index) in subjectLists"
                  :key="index"
                  :name="item.subjectId"
                >
                  {{ item.name }}
                </u-checkbox>
              </u-checkbox-group>
            </template>
            <template v-else>
              <view class="grays">请先选择报考专业</view>
            </template>
          </u-form-item>
        </view>
      </u-form>
      <!-- 提交按钮 -->
      <view class="btns">
        <view v-if="endTime <= sysTime" class="submits disable">提交</view>
        <view v-else class="submits" @click="submit()"> 提交 </view>
      </view>
    </view>
  </view>
</template>

<script>
import { tenantId, BASE_URL } from "@/common/request.js";
export default {
  name: "examApply",

  data() {
    var validatorMajor = (rule, value, callback) => {
      if (value.length) {
        callback();
      } else {
        callback(new Error("请选择报考科目"));
      }
    };
    var validatorMajorId = (rule, value, callback) => {
      if (value) {
        callback();
      } else {
        callback(new Error("请选择专业"));
      }
    };
    return {
      examform: {
        userName: "",
        userSex: "",
        companyName: "",
        // userIdCard: '',
        // userPhone: '',
        userMajors: [],
        majorId: "",
      },
      rules: {
        userName: [
          {
            required: true,
            message: "请输入姓名",
            trigger: ["blur", "change"],
          },
        ],
        userSex: [
          {
            required: true,
            message: "请选择性别",
            trigger: ["blur", "change"],
          },
        ],
        // companyName: [
        //   {
        //     required: true,
        //     message: "请输入企业名称",
        //     trigger: ["blur", "change"],
        //   },
        // ],
        // userIdCard: [{ required: true, message: '请输入身份证号', trigger: ['blur', 'change']}],
        majorId: [{ validator: validatorMajorId, trigger: ["change", "blur"] }],
        userMajors: [
          { validator: validatorMajor, trigger: ["blur", "change"] },
        ],
      },
      checkboxList: [],
      activityId: "", // 活动id
      subLoading: true,
      majorList: [], // 专业
      subjectLists: [], // 科目
      majorName: "",
      startTime: "",
      endTime: "",
      sysTime: "", // 当前时间
    };
  },
  onLoad(option) {
    this.sysTime = +this.$method.timest();
    // console.log('option--: ', option)
    if (option.scene) {
      let tid = decodeURIComponent(option.scene);
      this.activityId = tid.split("=")[1];
      // this.getActivity()
    } else {
      this.activityId = option.tid;
      // this.getActivity()
    }
  },
  onShow() {
    console.log("activityId: ", this.activityId);
    if (!uni.getStorageSync("user_account")) {
      // 未登录
      console.log("未登录");
      uni.navigateTo({
        url: "/pages4/login/login?isBack=true",
      });
      return;
    } else {
      // 已登录
      console.log("已登录");
      this.getActivity1();
    }
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  methods: {
    // 获取活动信息（专业和科目）
    getActivity() {
      this.$http({
        url: `/apply/activity/detail/${this.activityId}`,
        method: "get",
      }).then((res) => {
        if (res.data.code == 200) {
          this.hadCheck();
          let data = res.data.data || {};
          const { majorList, subjectList, endTime, startTime } = data;
          this.majorList = majorList || [];
          this.startTime = startTime;
          this.endTime = endTime;
          if (subjectList) {
            this.checkboxList = subjectList.map((item) => {
              return {
                name: "《" + item.subjectName + "》",
                checked: false,
                ...item,
              };
            });
            console.log("checkboxList:", this.checkboxList);
          }
        }
      });
    },
    getActivity1() {
      let token = uni.getStorageSync("token");
      token &&
        uni.request({
          url: BASE_URL + `/apply/activity/detail/${this.activityId}`,
          method: "get",
          data: {},
          header: {
            AuthorizationToken: "WX " + token,
            TenantId: tenantId,
          },
          success: (res) => {
            if (res.data.code == 200) {
              this.hadCheck();
              let data = res.data.data || {};
              const { majorList, subjectList, endTime, startTime } = data;
              this.majorList = majorList || [];
              this.startTime = startTime;
              this.endTime = endTime;
              if (subjectList) {
                this.checkboxList = subjectList.map((item) => {
                  return {
                    name: "《" + item.subjectName + "》",
                    checked: false,
                    ...item,
                  };
                });
                console.log("checkboxList:", this.checkboxList);
              }
            } else if (res.data.code == 401) {
              uni.navigateTo({
                url: "/pages4/login/login?isBack=true",
              });
            }
          },
          fail: (err) => {
            uni.showToast({
              title: "请求接口失败",
              icon: "none",
            });
          },
        });
    },
    // 校验用户是否已报名
    hadCheck() {
      this.$http({
        url: `/apply/activity/check/${this.activityId}`,
        method: "get",
      }).then((res) => {
        if (res.data.data) {
          // 已经报名
          uni.navigateTo({
            url:
              "/pages5/mockExam/registrationSuccess?endTime=" +
              this.endTime +
              "&startTime=" +
              this.startTime +
              "&activityId=" +
              this.activityId,
          });
        }
      });
    },
    checkboxGroupChange(e) {
      this.examform.userMajors = e;
    },
    radioGroupChange(e) {
      console.log(e, this.examform.userSex);
    },
    majorChange(e) {
      let index = e.detail.value;
      const { majorName, majorId, mockMajorId } = this.majorList[index];
      this.majorName = majorName;
      this.examform.majorId = majorId;
      // console.log('1111majorId', this.examform.majorId)
      this.subjectLists = this.checkboxList.filter(
        (e) => e.mockMajorId == mockMajorId
      );
      this.examform.userMajors = [];
      this.subjectLists = this.subjectLists.map((item) => {
        return {
          name: "《" + item.subjectName + "》",
          checked: false,
          ...item,
        };
      });
    },
    submit() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          if (!this.subLoading) {
            return;
          }
          this.subLoading = false;
          const { userName, userSex, companyName, majorId, userMajors } =
            this.examform;
          let arrs = [];
          userMajors.forEach((item, index) => {
            let findItem = this.subjectLists.find((e) => e.subjectId == item);
            if (findItem) {
              arrs.push(findItem);
            }
          });
          let mockSubjectIds = arrs.map((e) => e.subjectId).join(",");
          let mockMajorSubjectIds = arrs
            .map((e) => e.mockMajorSubjectId)
            .join(",");
          let params = {
            activityId: this.activityId,
            userName: userName,
            userSex: userSex,
            companyName: companyName,
            mockMajorId: majorId,
            mockSubjectIds: mockSubjectIds,
            mockMajorSubjectIds: mockMajorSubjectIds,
          };
          // console.log('eret', params)
          this.$http({
            url: "/apply/activity/launch",
            method: "post",
            data: params,
            // noToken: true,
          })
            .then((res) => {
              this.subLoading = true;
              if (res.data.code == 200) {
                let data = res.data.data;
                uni.navigateTo({
                  url:
                    "/pages5/mockExam/registrationSuccess?endTime=" +
                    data.endTime +
                    "&startTime=" +
                    data.startTime +
                    "&activityId=" +
                    this.activityId,
                });
              }
            })
            .catch((err) => {
              this.subLoading = true;
            });
        } else {
          console.log("验证失败");
        }
      });
    },
  },
};
</script>

<style>
page {
  background: linear-gradient(90deg, #edf1ff 0%, #d9f0ff 100%);
}
</style>
<style lang="scss" scoped>
.exam_apply {
  width: 100%;
  height: 100%;
  .mock_bg {
    width: 100%;
    height: 760rpx;
    // z-index: -999;
    top: 0;
  }
  .navbar {
    background-color: #498afe;
  }
  .mains {
    padding: 16rpx;
    position: relative;
    top: -270rpx;
  }
  .items {
    padding: 40rpx 0rpx 40rpx 24rpx;
    background-color: #fff;
    border-radius: 16rpx;
    margin-bottom: 16rpx;
    .star_red {
      color: #f84b39;
    }
    .number {
      font-size: 32rpx;
      font-weight: 800;
      color: #222222;
      margin: 0rpx 20rpx 0rpx 4rpx;
    }
    .category {
      font-size: 32rpx;
      font-weight: 400;
      color: #222222;
    }
    .inputs {
      width: 580rpx;
      height: 88rpx;
      background: #ffffff;
      border-radius: 8rpx;
      border: 2rpx solid #c2c2c2;
      display: flex;
      align-items: center;
      padding-left: 24rpx;
    }
    .item_box {
      height: 86rpx;
      display: flex;
      align-items: center;
      .pick_con {
        width: 500rpx;
        height: 86rpx;
        // font-size: 32rpx;
      }
      .text {
        flex: 1;
        display: flex;
        align-items: center;
      }
    }
    .grays {
      color: #999;
      font-size: 28rpx;
    }
  }
  .btns {
    width: 100%;
    // display: flex;
    // align-items: center;
    // justify-items: center;
    view {
      margin: 60rpx auto 0;
    }
  }
  .submits {
    width: 686rpx;
    height: 96rpx;
    line-height: 96rpx;
    text-align: center;
    background: #3f8dfd;
    border-radius: 16rpx;
    font-size: 32rpx;
    font-weight: 500;
    color: #ffffff;
  }
  .disable {
    background: #498afe;
    opacity: 0.5;
  }
}
</style>
