<script setup>
import { getCountDownTime } from "~/utils/day";
import { user } from "~/store/user";
import { child as childInfo, setChild } from "~/store/child";
import { showFailToast, showSuccessToast } from "vant";
const oss = window.GLOBAL_CONFIG.oss;
const props = defineProps({
  id: {
    type: String,
    required: true,
  },
});
let child = $ref(childInfo);
const children = JSON.parse(sessionStorage.getItem('children'))
let childrenCols = $ref([])
const router = useRouter();
function handleNavLeftClick() {
  router.replace("/stxk/jz");
}

// 报名状态
// 0: 未报名
// 1: 已报名未付款
// 2: 已报名已付款
// 当前学生是否可报名
let orderStatus = $ref(2);

let loading = $ref(true);
let detailInfo = $ref(0);
request({
  url: "/khfw/kcgl/detail",
  data: {
    token: child.token,
    kk_id: props.id,
  },
}).then((res) => {
  if (res.code === "1") {
    detailInfo = res.data.one_info;
    const grades = (detailInfo.kk_grade_id).split(',').filter(item => item !== '')
    console.log('grades :>> ', grades);
    childrenCols = children.map((item) => {
      return {
        text: `${item.first_cm_name} ${item.user_realname}`,
        value: item.user_id,
        self: item,
        disabled: grades.indexOf(item.cm_info[0].grade) === -1,
      };
    });

    detailInfo.$kk_kcfy = detailInfo.kk_kcfy * 100;

    if (detailInfo.khfw_kcbmxx.kkbm_id === "0") {
      orderStatus = 0;
    }
    else if (detailInfo.khfw_kcbmxx.kjf_zfzt === "1") {
      orderStatus = 1;
    } else if (detailInfo.khfw_kcbmxx.kjf_zfzt === "2") {
      orderStatus = 2;
    }
  } else {
  }
  loading = false;
});

function handleSubmitbarClick() {
  console.log("handleSubmitbarClick", orderStatus, child);
  const grades = (detailInfo.kk_grade_id).split(',').filter(item => item !== '')
  if (grades.indexOf(child.cm_info[0].grade) === -1) {
    showFailToast('该学生不在可报名年级范围内')
    return
  }
  request({
    url: "/khfw/kcbmxx/add",
    data: {
      token: child.token,
      khfw_kcbmxx: {
        kk_id: props.id,
        kk_name: detailInfo.kk_name,

        kkbm_p_user_id: user.user_id,
        kkbm_p_realname: user.user_realname,

        kkbm_s_user_id: child.user_id,
        kkbm_s_realname: child.user_realname,

        kkbm_s_grade_id: child.cm_info[0].grade,
        // kkbm_s_grade_name: '',
        kkbm_s_class_id: child.cm_info[0].cm_id,
        kkbm_s_class_name: child.cm_info[0].pre + child.cm_info[0].cm_name,
      },
    },
  }).then((res) => {
    if (res.code === "1") {
      const _href = encodeURIComponent(location.href);
      if (detailInfo.$kk_kcfy != "0") {
        location.replace(
          `http://wx.bozedu.net/get-weixin-code.html?appid=${window.GLOBAL_CONFIG.appid}&redirect_uri=${_href}&state=1`
        );
      }
    }
  });
}

function onBridgeReady(data) {
  return new Promise((resolve, reject) => {
    WeixinJSBridge.invoke(
      "getBrandWCPayRequest",
      {
        appId: data.appid,
        timeStamp: data.timestamp,
        nonceStr: data.noncestr,
        package: data.package,
        signType: data.signtype,
        paySign: data.paysign,
      },
      function (res) {
        // 使用以上方式判断前端返回,微信团队郑重提示：
        // res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
        switch (res.err_msg) {
          case "get_brand_wcpay_request:ok":
            showSuccessToast("支付成功");
            return resolve(true);
          case "get_brand_wcpay_request:cancel":
            showFailToast("取消支付,请稍后再试");
            return resolve(false);
          case "get_brand_wcpay_request:fail":
            showFailToast("支付失败,请稍后再试");
            return resolve(false);
          default:
            return resolve(false);
        }
      }
    );
  });
}

const searchObj = new URLSearchParams(location.search);
const code = searchObj.get("code");
// 微信支付跳转过来
if (code) {
  // location.search = "";
  request({
    url: "/khfw/jfgl/gotopay",
    data: {
      token: child.token,
      client: "wx",
      code,
      khfw_jfgl: {
        kkbm_s_user_id: child.user_id,
        kk_id: props.id,
      },
    },
  })
    .then((res) => {
      if (res.code === "1") {
        // orderStatus = false
        orderStatus = 1;
        if (typeof WeixinJSBridge == "undefined") {
          console.log("WeixinJSBridge is not ready");
          document.addEventListener(
            "WeixinJSBridgeReady",
            onBridgeReady(res.data),
            false
          );
        } else {
          return onBridgeReady(res.data);
        }
      }
    })
    .then((res) => {
      return new Promise((resolve, reject) => {

        if (res) {
          location.search = "";

          /* todo: 支付成功 */
          // router.replace('/stsk/jz/wd')
          const t1 = Date.now()

          let timer = setInterval(() => {
            if (Date.now() - t1 > 5000) {
              clearInterval(timer)
              timer = null
              resolve(0)
            } else {
              request({
                url: "/khfw/kcgl/detail",
                data: {
                  token: child.token,
                  kk_id: props.id,
                },
              }).then(res => {
                if (res.code === "1") {
                  const _detailInfo = res.data.one_info;

                  if (detailInfo.khfw_kcbmxx.kkbm_id === "0") {
                    orderStatus = 0;
                    resolve(0)
                  }
                  else if (_detailInfo.khfw_kcbmxx.kjf_zfzt === "2") {
                    orderStatus = 2;
                    resolve(2)
                  }
                }
              })
            }
          }, 1000)

        } else {
          resolve(0)
        }
      });
    })
  // .then(res => {
  //   if (res === 0) {
  //     orderStatus = 0;
  //   }
  // })
}

const orderStatusText = computed(() => {
  switch (orderStatus) {
    case 0:
      return "立即报名";
    case 1:
      return "申请中";
    case 2:
      return "已报名";
    default:
      return "立即报名";
  }
});

function handleClickSwitchChild() {

}
const showPicker = ref(false);
function handleConfirmSwitchChild({ selectedOptions }) {
  showPicker.value = false;
  console.log('selectedOptions :>> ', selectedOptions);
  setChild(child = selectedOptions[0].self);
  console.log('child', child)
};
</script>

<template>
  <van-sticky>
    <van-nav-bar title="课程详情" left-arrow @click-left="handleNavLeftClick">
    </van-nav-bar>
  </van-sticky>

  <div class="p-2 w-full">
    <van-skeleton title :row="10" :loading="loading">
      <van-image :src="detailInfo.kk_img" class="w-full"></van-image>

      <div class="text-sm">
        <div class="flex text-lg py-1">
          <div class="mr-4 font-bold">{{ detailInfo.kk_name }}</div>
          <van-tag type="primary">{{ detailInfo.ksgl_num }}课时</van-tag>
        </div>
        <div class="flex py-1">
          <div class="mr-4">
            <span>讲师：</span><span>{{ detailInfo.kk_teacher.name }}</span>
          </div>
          <div class="flex">
            <span>报名倒计时：</span>
            <van-count-down :time="getCountDownTime(detailInfo.kk_bmkssj)">
              <template #default="timeData">
                <span>
                  {{ paddingLeft(timeData.days * 24 + timeData.hours) }}小时{{
                    paddingLeft(timeData.minutes)
                  }}分钟{{ paddingLeft(timeData.seconds) }}秒
                </span>
              </template>
            </van-count-down>
          </div>
        </div>
        <div class="flex py-1">
          <div>开课时间：</div>
          <div>
            {{ detailInfo.kk_skqjkssj }} -
            {{ detailInfo.kk_skqjjwsj }}（请在开课前报名）
          </div>
        </div>
        <div class="flex py-1" v-show="detailInfo.kk_skdd != ''">
          <div>上课地点：</div>
          <div>{{ detailInfo.kk_skdd }}</div>
        </div>
      </div>
      <van-divider />

      <div class="mb-4">
        <div class="pre font-bold mb-2">课程简介</div>
        <div class="text-sm" v-html="detailInfo.kk_kcjj"></div>
      </div>

      <div class="mb-10">
        <div class="pre font-bold mb-2">教师简介</div>
        <div v-if="detailInfo.kk_teachers != ''">
          <div class="flex text-sm shadow-md p-2 mb-4" v-for="item in detailInfo.kk_teachers">
            <div class="w-1/3 flex-none flex flex-col items-center">
              <van-image :src="item.avatar" width="100" height="100" round fit="cover"></van-image>
              <div>
                <div>{{ item.name }}</div>
              </div>
            </div>
            <div>{{ item.intro }}</div>
            <!-- <ul class="list-disc list-inside">
                          <li>{{ detailInfo.kk_teacher.intro }}</li>
                        </ul> -->
          </div>
        </div>
        <div v-else>暂无数据</div>
      </div>

      <van-submit-bar :price="detailInfo.$kk_kcfy" :button-text="orderStatusText" :disabled="!!orderStatus"
        @submit="handleSubmitbarClick" placeholder>
        <template #tip>
          <div class="flex justify-between text-sm" @click="showPicker = true">
            <span>当前选中的小孩为 {{ child?.first_cm_name }} {{ child?.user_realname }}</span>
            <span class="text-blue-500">切换小孩</span>
          </div>
          <van-popup v-model:show="showPicker" round position="bottom">
            <van-picker :columns="childrenCols" @cancel="showPicker = false" @confirm="handleConfirmSwitchChild" />
          </van-popup>
        </template>
      </van-submit-bar>
    </van-skeleton>
  </div>
</template>
