<script setup name="registration">
import Container from "../../components/Container/Container.vue";
import CustomerService from "../../components/CustomerService/CustomerService.vue";
import RadioBlock from "../../components/RadioBlock/RadioBlock.vue";
import Modal from "../../components/Modal/Modal.vue";
import { onShow } from "@dcloudio/uni-app";
import { request } from "../../utils/request";
import { getRoute, router } from "../../utils/router";
import { ref, getCurrentInstance } from "vue";
import ext from "../../ext.json";

const instance = getCurrentInstance();
const context = ref("");
const permissions = ref(false);
const formData = ref({
  contact_name: "",
  contact_information: "",
  pharmacist_type: 0,
});
const loading = ref(false);
const show = ref(false);
const price = ref("");
const rules = {
  contact_name: [
    {
      required: true,
      message: "请输入姓名",
    },
  ],
  contact_information: [
    {
      required: true,
      message: "请输入联系方式",
      type: "phone",
    },
  ],
  pharmacist_type: [
    {
      required: true,
      message: "请选择报考执业药师类型",
    },
  ],
};
onShow(() => {
  const { id } = getRoute().params;
  loading.value = false;
  request("api/question_bank/question_reception/recharge_package/detail", {
    id,
  }).then((res) => {
    context.value = res.data.instructions || "";
    price.value = res.data.package_preferential_price;
  });
});

const validate = ({ value, message, type = "text" }) =>
  new Promise((resolve, reject) => {
    if (!value) {
      uni.showToast({
        title: message,
        icon: "none",
      });
      loading.value = false;
      return reject(message);
    }
    if (type === "phone") {
      const phoneReg =
        /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/;
      if (!phoneReg.test(value)) {
        uni.showToast({
          title: "请输入正确的手机号码",
          icon: "none",
        });
        loading.value = false;
        return reject("请输入正确的手机号码");
      }
    }

    resolve();
  });

const onSubmit = async () => {
  loading.value = true;
  for (const key in formData.value) {
    await validate({
      value: formData.value[key],
      message: rules[key][0].message,
      type: rules[key][0].type,
    });
  }

  console.log(permissions.value);

  if (!permissions.value) {
    show.value = true;
    return;
  }
  const { id } = getRoute().params;
  uni.login({
    provider: instance.proxy.$mpPlatform.substring(3),
    success: async ({ code }) => {
      if (!code) {
        loading.value = false;
        return;
      }
      const order = await request(
        "api/question_bank/question_reception/challenge_registration_log/add",
        {
          package_id: id,
          ...formData.value,
        }
      );
      if (order.code !== "success") {
        loading.value = false;
        return;
      }
      const e = await request(
        "api/question_bank/question_reception/orders/wechat_pay",
        {
          code,
          order_id: order.data.order_id,
          app_id: ext.extAppid,
        }
      );
      if (e.code !== "success") {
        loading.value = false;
        return;
      }
      uni.requestPayment({
        provider: "wxpay",
        timeStamp: e.data.timeStamp, //时间戳
        nonceStr: e.data.nonceStr, //随机字符串
        package: e.data.package, //prepay_id
        signType: e.data.signType, //签名算法MD5
        paySign: e.data.paySign, //签名,
        success() {
          router.redirectTo({
            url: "/pages/challenge/addContant",
            params: {
              type: formData.value.pharmacist_type,
            },
          });
          uni.setStorageSync("pages/challenge/index", null);
        },
        fail(err) {
          router.push({
            url: "/pages/success/error",
          })
        },
        complete() {
          loading.value = false;
        },
      });
    },
    fail() {
      loading.value = false;
    },
  });
};

const onChange = (e) => {
  permissions.value = !!e.detail.value[0];
};
</script>
<template>
  <Container
    title="报名"
    :scrollStyle="{
      padding: 0,
    }"
    bgColor="#a8e0fd"
    bottomBgColor="#fff"
    headerColor="#fff"
    v-if="!show"
  >
    <view class="bg">
      <view class="bg-1">
        <form>
          <view class="uni-form-item">
            <view class="title required">姓名</view>
            <input
              class="uni-input"
              name="contact_name"
              placeholder="请输入真实姓名"
              v-model="formData.contact_name"
            />
          </view>
          <view class="uni-form-item">
            <view class="title required">联系方式</view>
            <input
              class="uni-input"
              name="contact_information"
              placeholder="请输入电话号码"
              v-model="formData.contact_information"
            />
          </view>
          <view class="uni-form-item">
            <view class="title required">报考执业药师类型（请选择）</view>
            <RadioBlock
              v-model="formData.pharmacist_type"
              name="pharmacist_type"
              :columns="[
                {
                  label: '西药',
                  value: 2,
                },
                {
                  label: '中药',
                  value: 1,
                },
              ]"
            />
          </view>
        </form>
      </view>
    </view>
    <div class="permissions">
      <checkbox-group @change="onChange">
        <label>
          <checkbox class="checkbox" :value="1" />
          阅读并确认
        </label>
      </checkbox-group>
      <span
        class="text-primary"
        @click="
          () => {
            router.push({
              url: '/pages/richpage/index',
              params: {
                title: '会员服务权益',
                content_code: 'service_rights',
              },
            });
          }
        "
        >《会员服务权益》</span
      >
      <span
        class="text-primary"
        @click="
          () => {
            router.push({
              url: '/pages/challenge/rule',
              params: {
                id: getRoute().params.id,
              },
            });
          }
        "
        >《活动规则》</span
      >
    </div>
    <view class="service">
      <CustomerService>联系客服</CustomerService>
    </view>
    <template #footer>
      <button
        :loading="loading"
        :disabled="loading"
        class="btn"
        @click="onSubmit"
      >
        ￥{{ price }} 立即开通
      </button>
    </template>
  </Container>
  <Modal
    v-model:open="show"
    title="温馨提示"
    :submitter="{
      closeText: '不同意',
      text: '同意并支付',
    }"
    :onClose="() => (show = false)"
    :onSubmit="
      () => {
        permissions = true;
        show = false;
        onSubmit();
      }
    "
  >
    <div class="text">
      <span> 阅读并确认 </span>
      <span
        class="text-primary"
        @click="
          () => {
            router.push({
              url: '/pages/richpage/index',
              params: {
                title: '会员服务权益',
                content_code: 'service_rights',
              },
            });
          }
        "
        >《会员服务权益》</span
      >
      <span
        class="text-primary"
        @click="
          () => {
            router.push({
              url: '/pages/challenge/rule',
              params: {
                id: getRoute().params.id,
              },
            });
          }
        "
        >《活动规则》</span
      >
    </div>
  </Modal>
</template>
<style scoped lang="scss">
.bg {
  width: 100%;
  background: url("https://openwork-oss.oss-cn-shenzhen.aliyuncs.com/uploads/question/2025/05/yz2eTeqIRv60IEe6kOQBOYlHr75wiFIpeFqrJmgZ.png")
    no-repeat;
  background-size: 100%;
  padding: 216rpx 10rpx 0;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  .bg-1 {
    width: 730.71rpx;
    height: 841rpx;
    background: url("https://openwork-oss.oss-cn-shenzhen.aliyuncs.com/uploads/question/2025/06/3P7CBvlUNmunkIM1PA5voYhrGpIIgeqgy30pLb1z.png")
      no-repeat;
    background-size: 100% 100%;
    position: relative;
    box-sizing: border-box;
    padding: 170rpx 50rpx;
    .uni-form-item .title {
      padding: 20rpx 0;
    }

    .uni-input {
      border-radius: 8rpx 8rpx 8rpx 8rpx;
      border: 1rpx solid #dddddd;
      padding: 14rpx 9rpx;
    }
  }
}
.text {
  font-size: 30rpx;
  margin: 20rpx 0;
}
.service {
  position: absolute;
  bottom: 20%;
  right: 5%;
  color: $uni-primary;
  font-size: 28rpx;
  margin-bottom: 40rpx;
  text-align: right;
}
.permissions {
  position: absolute;
  bottom: 15%;
  left: 32rpx;
  display: flex;
  align-items: center;
  font-weight: 500;
  font-size: 28rpx;
  color: #333333;
}
.btn {
  margin: 32rpx 0;
  font-weight: 400;
  font-size: 32rpx;
  color: #ffffff;
}
</style>
