<script setup>
/**
 * name：
 * user：yytjsj
 * date：2024年9月25日 10:25:00
 */
import { ref, onBeforeUnmount } from "vue";
import { $api, $response, $image } from "@/api";
import { onShow } from "@dcloudio/uni-app";
import { useStore } from "@/store";
const $store = useStore();
const dqDate = ref("");
const doctor_name = ref("");

let date_list = ref(false);
let time_list = ref(false);
let currentDate = ref(0);
let currentTime = ref(0);
let currentXmmcObj = ref(false); //当前选中体检项目对象
let buyInfo = ref({}); // 购买信息
let yytjInfo = ref({}); // 购买信息
let groupInfo = ref({});
let comboInfo = ref({});
let itemsInfo = ref({});
let truePrice = ref(0); // 总价
let nmrIndex = ref(null); // 当前选中项目索引
let time = ref(""); // 时分
let timeIndex = ref(null); // 当前选中时间索引
let status = ref(0); // 1：点了确定 2：未点确定

const mountedAction = async () => {
  uni.showLoading({
    title: "加载中",
  });
  console.log($store.getYytjInfo(), "swsw");
  console.log($store.getBuyInfo(), "tyuiopiuytr");
  yytjInfo.value = $store.getYytjInfo();
  buyInfo.value = $store.getBuyInfo();
  await getnmrList();
};

onBeforeUnmount(() => {
  if (!status.value) {
    $store.setYytjInfo(uni.getStorageSync("yytjInfoS"));
  }
});

const getnmrList = async () => {
  const response = await $api("BuyInfo", buyInfo.value);
  $response(response, () => {
    if (buyInfo.value.group_id && response.data.group_info.length) {
      // 团检
      groupInfo.value = response.data.group_info[0];
    }
    comboInfo.value = response.data.combo_info;
    itemsInfo.value = response.data.items_info;
    truePrice.value = response.data.true_price;
    currentDate.value = getToday(); //huo获取今天的日期

    if (!yytjInfo.value?.nmr_list?.length) {
      yytjInfo.value.nmr_list = response.data.nmr_list.map((val) => {
        return {
          ...val,
          time: "",
          id: "",
        };
      });
      yytjInfo.value.nmr_list.push({
        item_id: -1,
        name: "体检时间",
        time: "",
        id: "",
      });
    }
    uni.hideLoading();
  });
};
const getToday = () => {
  // 获取当前日期
  var today = new Date();

  // 获取年、月、日
  var year = today.getFullYear(); // 年
  var month = (today.getMonth() + 1).toString().padStart(2, "0"); // 月，月份是从0开始的，所以要+1，并使用padStart补零
  var day = today.getDate().toString().padStart(2, "0"); // 日，使用padStart补零

  // 拼接日期字符串
  return year + "-" + month + "-" + day;
};
const getTjTimeList = async (val) => {
  console.log($store.getCheckupTypeId());
  console.log(val);
  // 获取 体检号源
  let obj = {};
  let apiText = "";
  if (val.item_id == -1) {
    obj = {
      hospital: buyInfo.value.hospital,
      person_id: buyInfo.value.person_id,
      date: currentDate.value, //currentDate.value
      use_type: buyInfo.value.group_id ? 2 : 1,
      checkup_type_id: buyInfo.value.group_id
        ? $store.getGroupInfo()?.checkup_type_id
        : $store.getCheckupTypeId()?.id,
      amount: truePrice.value,
    };
    apiText = "GetDayPlanList";
  } else {
    obj = {
      hospital_id: buyInfo.value.hospital,
      date: currentDate.value,
    };
    apiText = "NMRGetDayPlanList";
  }
  const response = await $api(apiText, obj);
  $response(response, () => {
    console.log(response, "response");
    // currentXmmcObj.value["sj"] = ""; //每次请求新的时间时间置空
    currentTime.value = "";
    date_list.value = response.data.weeklist;
    time_list.value = response.data.list;

    time_list.value.forEach((item) => {
      console.log(item.date);
      item.newTime = item.time.slice(0, 5);
      item.date = currentDate.value;
    });
    date_list.value.forEach((item) => {
      console.log(item);
      item.item_id = val.item_id;
      const [year, month, day] = item.date.split("-");
      item.newMonthDate = `${month}/${day}`; //月份日期
      item.newWeek = item.xingqi.replace("星期", "周");
    });
    if (val.time) {
      timeIndex.value = time_list.value.findIndex(
        (item) => item.newTime == val.time.split(" ")[1]
      );
    }
    uni.hideLoading();
  });
};

const getCurrentClick = (item, i) => {
  console.log(item, i); //当前日期和星期
  if (item.count < 0) {
    uni.$lu.toast("该日期已满，请选择其他日期");
    return;
  }
  time.value = "";
  timeIndex.value = null;
  yytjInfo.value.nmr_list[nmrIndex.value].time = "";
  yytjInfo.value.nmr_list[nmrIndex.value].id = "";
  console.log(
    yytjInfo.value.nmr_list[yytjInfo.value.nmr_list.length - 1].time,
    "xxsxsx"
  );
  if (!yytjInfo.value.nmr_list[yytjInfo.value.nmr_list.length - 1].time) {
    yytjInfo.value.doctor_name = "";
  }
  $store.setYytjInfo(yytjInfo.value);
  status.value = 0;
  currentDate.value = item.date;
  getTjTimeList(item); //带着选中的日期重新选择
};
const getCurrentTime = (item, index) => {
  // 选择时分
  if (item.status == 2) {
    uni.$lu.toast("该号源已被其他人预约");
    return;
  }
  console.log(item);
  timeIndex.value = index;
  yytjInfo.value.nmr_list[nmrIndex.value].time = item.date + " " + item.newTime;
  yytjInfo.value.nmr_list[nmrIndex.value].id = item.id;
  status.value = 0;
  $store.setYytjInfo(yytjInfo.value);
};
const xmmcClick = (val, index) => {
  // 选择项目
  nmrIndex.value = index;
  time.value = "";
  timeIndex.value = null;
  if (val.time) {
    currentDate.value = val.time.split(" ")[0];
  } else {
    currentDate.value = getToday();
  }
  // 体检号源
  getTjTimeList(val);
};

const clickDoctor = () => {
  //选择医生列表
  if (yytjInfo.value.nmr_list[yytjInfo.value.nmr_list.length - 1].time == "") {
    uni.$lu.toast("请先选择体检时间");
    return;
  }
  status.value = 0;
  uni.navigateTo({
    url: `/pages/main/selectDoctor/selectDoctor?date=${currentDate.value}`,
  });
};

const comfrimyy = () => {
  status.value = 1;
  uni.navigateBack({
    delta: 1,
  });
};

const config_ref = ref(null);
const configRef = (e) => {
  if (!config_ref.value) {
    config_ref.value = e;
    mountedAction();
  }
};

onShow(() => {
  if (!!config_ref.value) {
    mountedAction();
  }
});
</script>
<template>
  <view>
    <view v-if="!!$store.config">
      <view :ref="configRef"></view>
    </view>
    <view class="h-38rpx bg-#239EA3 pl-20rpx pr-20rpx box-border">
      <view
        style="box-shadow: 0rpx 0rpx 10rpx 0rpx rgba(0, 0, 0, 0.04)"
        class="p-16rpx pb-20rpx pt-30rpx rounded-15rpx bg-#fff"
      >
        <view
          class="flex w-full b-0 b-solid b-b-1 b-#E1ECEE pb-25rpx mb-7rpx"
          v-if="!buyInfo.group_id && comboInfo?.items?.length"
        >
          <!-- 1 个检套餐 显示套餐信息 -->
          <image
            v-if="comboInfo.img"
            :src="$image(comboInfo.img)"
            class="w-190rpx h-190rpx mr-37rpx"
            mode="widthFix"
          />
          <view class="flex flex-col grow">
            <text>{{ comboInfo.combo_name }}</text>
            <view class="mt-13rpx mb-18rpx">
              <uni-tag
                v-for="(val, i) in comboInfo.tags"
                :key="i"
                size="small"
                :inverted="true"
                :text="val.text"
                class="mr-8rpx"
                :custom-style="
                  'background-color:' +
                  val.color +
                  ';border-color:' +
                  val.color +
                  '; color:' +
                  val.text_color +
                  ';'
                "
              />
            </view>
            <view v-if="comboInfo.tags2?.length">
              <text
                v-for="(val, i) in comboInfo.tags2"
                :key="i"
                class="text-#8B8B8B text-20rpx line-height-[1] px-5rpx b-0 b-solid b-#8B8B8B"
                :class="i == comboInfo.tags2?.length - 1 ? 'b-r-0' : 'b-r-2'"
                >{{ val }}</text
              >
            </view>
            <view class="mt-20rpx w-full flex items-end">
              <text class="text-18rpx text-#EC3D15">¥</text>
              <text class="text-38rpx text-#EC3D15 mx-10rpx -mb-8rpx">{{
                comboInfo.price
              }}</text>
              <text class="text-18rpx text-#878787 line-through">{{
                comboInfo.original_price
              }}</text>
              <text class="text-18rpx text-#878787 ml-auto mr-55rpx"
                >已售{{ comboInfo.sale_count }}</text
              >
            </view>
          </view>
        </view>
        <view
          v-if="buyInfo.group_id"
          class="b-0 b-solid b-#E1ECEE pb-25rpx mb-7rpx"
          :class="{
            'b-b-1': itemsInfo?.items?.length,
          }"
        >
          <!-- 3团检套餐 4团检自选 都要显示头像和名字 -->
          <view class="flex items-center">
            <image
              src="@/static/assets/userm.png"
              class="w-70rpx h-70rpx mr-35rpx"
            />
            <view class="flex items-center grow">
              <text class="text-#707070 text-24rpx">您好，</text>
              <text class="text-#0E0E0E text-32rpx">{{ groupInfo.name }}</text>
            </view>
          </view>
          <view class="text-24rpx mt-40rpx">
            <!-- 3团检套餐 4团检自选 都要显示单位部门等信息 -->
            <view class="pb-30rpx">
              <text class="text-#8B8B8B">单位名称：</text>
              <text>{{ groupInfo.group_name }}</text>
            </view>
            <view class="pb-30rpx">
              <text class="text-#8B8B8B">部门名称：</text>
              <text>{{ groupInfo.bumen_name }}</text>
            </view>
            <view
              class="pb-30rpx"
              v-if="groupInfo.combo_name || comboInfo?.combo_name"
            >
              <text class="text-#8B8B8B">套餐名称：</text>
              <text>{{ groupInfo?.combo_name || comboInfo?.combo_name }}</text>
            </view>
            <view>
              <text class="text-#8B8B8B">体检额度：</text>
              <text>{{ groupInfo.tongshou_xiane }}</text>
            </view>
          </view>
        </view>
        <view class="pt-15rpx" v-if="itemsInfo?.items?.length">
          <view class="text-30rpx text-#0E0E0E pb-30rpx"> 自选项目 </view>
          <view class="text-#8B8B8B text-24rpx">
            <view
              class="flex mb-20rpx"
              v-for="(val, index) in itemsInfo?.items.length > 3
                ? 3
                : itemsInfo?.items"
              :key="index"
            >
              <text class="whitespace-nowrap"
                >{{ itemsInfo?.items[index]?.keshi_name }} -
              </text>
              <view class="line-clamp-2">
                <text
                  class="ml-10rpx text-#0E0E0E"
                  v-for="(v, i) in itemsInfo?.items[index]?.children"
                  :key="i"
                  >{{ v.name }}</text
                >
              </view>
            </view>
          </view>
        </view>
        <view class="center mt-20rpx text-#8B8B8B text-24rpx">
          <text>体检医生 - </text>
          <text
            class="ml-10rpx text-#0E0E0E center mr-auto"
            @click="clickDoctor"
          >
            {{ yytjInfo?.doctor_name || "请选择" }}
            <uni-icons type="right" size="14"></uni-icons>
          </text>
        </view>
      </view>
      <view
        style="box-shadow: 0rpx 0rpx 10rpx 0rpx rgba(0, 0, 0, 0.04)"
        class="p-16rpx pb-20rpx pt-30rpx rounded-15rpx bg-#fff mt-15rpx"
        v-if="date_list"
      >
        <view class="">
          <view
            class="text-30rpx text-#0E0E0E pb-34rpx font-500"
            v-if="currentXmmcObj.name"
          >
            {{ currentXmmcObj.name || "" }}
          </view>
          <view class="flex">
            <view
              class="w-15% text-center text-18rpx"
              v-for="(item, index) in date_list"
              :key="index"
            >
              <view
                @click="getCurrentClick(item, index)"
                :style="
                  item.count < 0 ? 'background-color:#EFEFEF;color:#aaa8a8' : ''
                "
                :class="3 == index ? 'activeTime' : ''"
                class="rounded-12rpx pt-10rpx pb-10rpx ml-10rpx mr-10rpx mb-6rpx"
              >
                <view> {{ item.newMonthDate }} </view>
                <view class="text-26rpx font-500"> {{ item.newWeek }} </view>
              </view>
              <view class="ma" v-if="item.count > -1">
                <text class="bg-#EFEFEF rounded-10rpx h-28rpx pl-10rpx pr-10rpx"
                  >余{{ item.count }}</text
                >
              </view>
            </view>
            <!-- <view  class="w-1rpx m-20rpx bg-#E6E9E9 ml-15rpx"   />
						<view class="flex text-#239EA3 text-20rpx">
							更多
						</view> -->
          </view>
          <!-- <view class="w-100% h-1rpx bg-#E6E9E9 mt-18rpx" /> -->
          <view
            class="flex flex-wrap pt-30rpx pb-30rpx b-0 b-t-1 b-solid b-#E1ECEE"
            v-if="time_list.length"
          >
            <view
              class="w-20% text-center box-border p-20rpx"
              v-for="(item, index) in time_list"
              :key="index"
              :class="{
                'text-red': item.status == 2,
              }"
              @click="getCurrentTime(item, index)"
            >
              <view
                class="text-24rpx rounded-12rpx h-54rpx flex flex-items-center flex-justify-center"
                :class="timeIndex == index ? 'activeTime' : ''"
              >
                {{ item.newTime }}
              </view>
            </view>
          </view>
        </view>
      </view>
      <view
        style="box-shadow: 0rpx 0rpx 10rpx 0rpx rgba(0, 0, 0, 0.04)"
        class="p-30rpx pl-10rpx pr-10rpx rounded-15rpx bg-#fff mt-15rpx text-#101010 text-28rpx"
      >
        <view class="bg-#F7F7F7 pl-20rpx pr-20rpx pt-23rpx pb-25rpx">
          <text>{{
            buyInfo.group_id
              ? $store.getGroupInfo()?.name
              : $store.getUser()?.name
          }}</text>
          <view
            class="bg-#EFEFEF rounded-15rpx p-10rpx pb-15rpx pt-15rpx mt-20rpx"
          >
            <view
              v-for="(item, index) in yytjInfo.nmr_list"
              :key="index"
              @click="xmmcClick(item, index)"
              :class="nmrIndex == index ? 'acitvetc' : ''"
              class="flex flex-justify-around p-20rpx pl-10rpx pr-10rpx rounded-15rpx"
            >
              <view class="flex-1 line-clamp-1">
                {{ item.name }}
              </view>
              <view>
                {{ item.time }}
              </view>
            </view>
          </view>
        </view>
      </view>

      <view class="pb-100rpx">
        <view
          @click="comfrimyy"
          class="text-#fff text-32rpx rounded-45rpx bg-#239EA3 mt-40rpx ma w-520rpx h-90rpx flex flex-items-center flex-justify-center"
        >
          确定
        </view>
      </view>
    </view>
  </view>
</template>
<style scoped>
.activeTime {
  background-color: #239ea3;
  color: #fff;
}

.acitvetc {
  background-color: #e0f1f2;
}
</style>
