<script setup>
import { ref, onMounted } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import Container from "@/components/Container.vue";
import ScreenHint2 from "@/components/ScreenHint2.vue";
import SButton from "@/components/SButton.vue";
import BowTargetEdit from "@/components/BowTargetEdit.vue";
import { savePointBookAPI } from "@/apis";

const showTip = ref(false);
const groups = ref(0);
const amount = ref(0);
const currentGroup = ref(1);
const currentArrow = ref(0);
const arrowGroups = ref({});
const bowtarget = ref({});
const ringTypes = ref([
  { ring: "X", color: "#FADB80" },
  { ring: "10", color: "#FADB80" },
  { ring: "9", color: "#FADB80" },
  { ring: "8", color: "#F97E81" },
  { ring: "7", color: "#F97E81" },
  { ring: "6", color: "#7AC7FF" },
  { ring: "5", color: "#7AC7FF" },
  { ring: "4", color: "#9B9B9B" },
  { ring: "3", color: "#9B9B9B" },
  { ring: "2", color: "#d8d8d8" },
  { ring: "1", color: "#d8d8d8" },
]);

const onBack = () => {
  uni.navigateBack();
};
const onSubmit = async () => {
  const isComplete = arrowGroups.value[currentGroup.value].every(
    (item) => !!item.ring
  );
  if (!isComplete) {
    return uni.showToast({
      title: "请完善信息",
      icon: "none",
    });
  }
  if (currentGroup.value < groups.value) {
    currentGroup.value++;
    currentArrow.value = 0;
  } else {
    const pointBook = uni.getStorageSync("last-point-book");
    const res = await savePointBookAPI(
      pointBook.bowType.id,
      pointBook.distance,
      pointBook.bowtargetType.id,
      groups.value,
      amount.value,
      Object.values(arrowGroups.value)
    );
    if (res.record_id) {
      uni.removeStorageSync("last-point-record");
      uni.redirectTo({
        url: `/pages/point-book-detail?id=${res.record_id}`,
      });
    }
  }
};
const onClickRing = (ring) => {
  if (arrowGroups.value[currentGroup.value]) {
    arrowGroups.value[currentGroup.value][currentArrow.value] = { ring };
    if (currentArrow.value < amount.value - 1) currentArrow.value++;
    uni.setStorageSync("last-point-record", arrowGroups.value);
  }
};
const deleteArrow = () => {
  const arrow = arrowGroups.value[currentGroup.value][currentArrow.value];
  if (JSON.stringify(arrow) === "{}") {
    currentArrow.value -= 1;
  } else {
    arrowGroups.value[currentGroup.value][currentArrow.value] = {};
  }
  uni.$emit("set-edit-arrow", null);
  uni.setStorageSync("last-point-record", arrowGroups.value);
};
const onEditDone = (arrow) => {
  arrowGroups.value[currentGroup.value][currentArrow.value] = arrow;
  if (currentArrow.value < amount.value - 1) currentArrow.value++;
  uni.setStorageSync("last-point-record", arrowGroups.value);
};
const onSelectArrow = (index) => {
  currentArrow.value = index;
  const arrow = arrowGroups.value[currentGroup.value][currentArrow.value];
  if (arrow && arrow.x && arrow.y) {
    uni.$emit("set-edit-arrow", index);
  } else {
    uni.$emit("set-edit-arrow", null);
  }
};

onLoad((options) => {
  const pointBook = uni.getStorageSync("last-point-book");
  if (pointBook.bowtargetType) {
    bowtarget.value = pointBook.bowtargetType;
    if (bowtarget.value.id > 3) {
      ringTypes.value = ringTypes.value.slice(0, 6);
      if (bowtarget.value.id > 8) {
        ringTypes.value = ringTypes.value.slice(1);
      }
    }
  }
  if (pointBook.amountGroup) {
    groups.value = Number(pointBook.amountGroup.split("/")[0]);
    amount.value = Number(pointBook.amountGroup.split("/")[1]);
    for (let i = 1; i <= groups.value; i++) {
      arrowGroups.value[i] = new Array(amount.value).fill({});
    }
  }
  if (options.withDraft) {
    const draft = uni.getStorageSync("last-point-record");
    if (draft) {
      Object.values(draft).some((arrows, index1) =>
        arrows.some((arrow, index2) => {
          currentArrow.value = index2;
          currentGroup.value = index1 + 1;
          return JSON.stringify(arrow) === "{}";
        })
      );
      arrowGroups.value = draft;
    }
  }
  // uni.enableAlertBeforeUnload({
  //   message: "现在离开会导致未提交的数据丢失，是否继续？",
  // });
});
</script>

<template>
  <Container :bgType="2" bgColor="#F5F5F5" :whiteBackArrow="false">
    <view class="container">
      <BowTargetEdit
        :onChange="onEditDone"
        :arrows="arrowGroups[currentGroup]"
        :id="bowtarget.id"
        :src="bowtarget.icon"
      />
      <view class="title-bar">
        <view>
          <view />
          <text>第 {{ currentGroup }} 组</text>
        </view>
        <view @click="deleteArrow">
          <image src="../static/delete.png" />
          <text>删除</text>
        </view>
      </view>
      <view class="bow-arrows">
        <view
          v-if="arrowGroups[currentGroup]"
          v-for="(arrow, index) in arrowGroups[currentGroup]"
          :key="index"
          @click="onSelectArrow(index)"
          :style="{
            borderColor: currentArrow === index ? '#FED847' : '#eeeeee',
            borderWidth: currentArrow === index ? '2px' : '1px',
          }"
          >{{
            isNaN(arrow.ring)
              ? arrow.ring
              : arrow.ring
              ? arrow.ring + " 环"
              : ""
          }}
        </view>
      </view>
      <text>推荐在靶纸上落点计分，这样可获得稳定性分析</text>
      <view class="bow-rings">
        <view
          v-for="(item, index) in ringTypes"
          :key="index"
          @click="() => onClickRing(item.ring)"
          :style="{ backgroundColor: item.color }"
          >{{ item.ring }}</view
        >
        <view
          :style="{ backgroundColor: '#d8d8d8' }"
          @click="() => onClickRing('M')"
          >M</view
        >
      </view>
      <ScreenHint2 :show="showTip">
        <view class="tip-content">
          <text>现在离开会导致</text>
          <text>未提交的数据丢失，是否继续？</text>
          <view>
            <button hover-class="none" @click="onBack">退出</button>
            <button hover-class="none" @click="showTip = false">
              继续记录
            </button>
          </view>
        </view>
      </ScreenHint2>
    </view>
    <template #bottom>
      <SButton :rounded="50" :onClick="() => $clickSound(onSubmit)">
        {{ currentGroup === groups ? "保存并查看分析" : "下一组" }}
      </SButton>
    </template>
  </Container>
</template>

<style scoped>
.container {
  width: 100%;
}
.container > text {
  margin: 15px;
  color: #999;
  font-size: 13px;
  font-weight: 200;
}
.bow-arrows,
.bow-rings {
  margin: 15px;
  display: grid;
  column-gap: 1vw;
  grid-template-columns: repeat(6, 1fr);
  position: relative;
}
.bow-arrows > view,
.bow-rings > view {
  background: #ffffff;
  border-radius: 6px;
  border: 1px solid #eeeeee;
  box-sizing: border-box;
  font-size: 12px;
  color: #333;
  text-align: center;
  padding: 5px 0;
  height: 32px;
  line-height: 20px;
  margin-bottom: 5px;
}
.bow-rings > view {
  font-size: 13px;
  height: 36px;
  line-height: 24px;
  color: #fff;
  background-color: #d8d8d8;
}
.tip-content {
  width: 100%;
  padding: 25px;
  display: flex;
  flex-direction: column;
  color: #000;
}
.tip-content > text {
  width: 100%;
  text-align: center;
  font-size: 14px;
  margin-top: 5px;
}
.tip-content > view {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}
.tip-content > view > button {
  width: 48%;
  background: linear-gradient(180deg, #fbfbfb 0%, #f5f5f5 100%);
  border-radius: 22px;
  border: 1px solid #eeeeee;
  padding: 12px 0;
  font-size: 14px;
  color: #000;
}
.tip-content > view > button:last-child {
  background: #fed847;
}
.title-bar {
  width: calc(100% - 30px);
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 13px;
  margin: 0 15px;
  position: relative;
}
.title-bar > view:first-child {
  display: flex;
  align-items: center;
  color: #333;
  font-weight: 500;
}
.title-bar > view:first-child > view:first-child {
  width: 5px;
  height: 15px;
  border-radius: 10px;
  background-color: #fed847;
  margin-right: 7px;
}
.title-bar > view:nth-child(2) {
  color: #287fff;
  display: flex;
  align-items: center;
}
.title-bar > view:nth-child(2) image {
  width: 14px;
  height: 14px;
  margin-right: 5px;
}
</style>
