<template>
  <div class="page">
    <h-navbar title="Missoes Dirias" />
    <div class="page-body">
      <van-tabs
        v-model:active="current"
        background="#20252a"
        color="#00E7BB"
        title-active-color="#00E7BB"
        title-inactive-color="#8d9e9a"
        @click-tab="changeCurrent"
      >
        <van-tab v-for="(item, index) in activityList" :key="index">
          <template #title
            ><span style="font-size: 0.4rem">{{ item.className }}</span>
          </template>
          <div class="content_body">
            <div class="body">
              <div class="title-btn">
                <div
                  v-for="(el, index2) in item.activity"
                  :key="index2"
                  :class="{ active: active === el.activityCode }"
                  @click="changeTitle(el)"
                >
                  {{ el.activityName }}
                </div>
              </div>
              <van-image
                :src="getImage(imgBanner)"
                style="max-height: 1.7rem"
              />
            </div>
            <div
              v-for="(data, index3) in sortData(rowsData.rows)"
              :key="index3"
              class="item-box"
            >
              <div class="left">
                <div class="title">
                  {{ data.taskName }}
                  <span>
                    ({{
                      Number(getProgress(data.ruleList[0].ruleCode, data._id)) >
                      Number(
                        getProgressTwo(data.ruleList[0].ruleCode, data.value)
                      )
                        ? getProgressTwo(data.ruleList[0].ruleCode, data.value)
                        : getProgress(data.ruleList[0].ruleCode, data._id)
                    }}
                    /
                    {{ getProgressTwo(data.ruleList[0].ruleCode, data.value) }})
                  </span>
                </div>
              </div>
              <div class="right">
                <div class="gezi">
                  <div
                    class="gezi-box"
                    v-for="(ele, index4) in data.propsList"
                    :key="index4"
                  >
                    <h-img src="perfil/gezi_01.png" width="1.5rem" />
                    <van-image
                      class="icon"
                      :src="getImage(fullImgUrl(ele.propId))"
                    />
                    <span>{{ ele.num / 10000 }}</span>
                  </div>
                </div>
                <div
                  class="btn btn0"
                  v-if="state(index3) == 0"
                  @click="taskGo(index3, state(index3))"
                >
                  Lr Para
                </div>
                <div
                  class="btn btn1"
                  v-else-if="state(index3) == 1"
                  @click="taskGo(index3, state(index3))"
                >
                  Receber
                </div>
                <div
                  class="btn btn2"
                  v-else-if="state(index3) == 2"
                  @click="taskGo(index3, state(index3))"
                >
                  Recebido
                </div>
              </div>
            </div>
          </div>
        </van-tab>
      </van-tabs>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, watch, computed } from "vue";
import { getImage } from "@/utils";
import socketApi from "@/socket/socketApi";
import { propsStore } from "@/stores/modules/props";
import { useRouter } from "vue-router";
import { useGameStore } from "@/stores/modules/game";
import { toast } from "@/utils/toast";
import { useUserStore } from "@/stores/modules/user";
import http from "@/https/index";
const userStore = useUserStore();
import storage, { actions } from "@/utils/storage";

const imgBanner = ref("");
const router = useRouter();
// const showIframeVisible = ref(false);
const gameStore = useGameStore();
const propsDataStore = propsStore();
const current = ref<number>(0);
const active = ref<any>(0);
enum TASK_RULE_CODE {
  /** 充值 */
  PAY = 0,
  /** 赢 */
  WIN = 1,
  /** 输 */
  LOSE = 2,
  /** 投入 */
  INVEST = 3,
  /** 金币数 */
  COINS = 4,
  /** 金额 */
  PRICE = 5,
  /** 次数 */
  COUNT = 6,
  /** 天数 */
  DAY = 7,
  /** 秒数 */
  SECOND = 8,
  /** 连续的 */
  CONTINUOUS = 9,
  /** 累计的 */
  TOTAL = 10,
  /** 在线时长 */
  ONLINE = 11,
  /** 签到 */
  CHECKIN = 12,
  /** 冷却 */
  COLD = 13,
  /**
   * 特殊行为
   * 值1：Slots免费摇奖，捕鱼鱼潮
   * 值2：Slots小游戏，捕鱼BOSS
   * 值3：Slots大赢
   */
  SPECIAL_ACTION = 14,
  /**
   * 特殊条件
   * 值N：捕鱼击杀N倍的鱼生效
   */
  SPECIAL_CONDITION = 15,
  /** 参与游戏 */
  PLAY = 16,
  /** 完成指定活动的任务 */
  TASK = 17,
  /** 游戏分类 */
  GAME_CLASS = 18,
  /** 游戏ID */
  GAME_ID = 19,
}
const state = computed(() => (index: number) => {
  // 1 可领取  2 已领奖  0  未完成
  let state: number = 0;
  let id = rowsData.value.rows[index]._id || 0;
  if (progressData.value[`${id}_award`]) {
    state = 2;
  } else if (progressData.value[id] >= rowsData.value.rows[index].value) {
    state = 1;
  }
  return state;
});
const sortData = computed(() => (list: Array<any>) => {
  if (list) {
    return list.sort(sortList());
  } else {
    return [];
  }
});
function sortList() {
  return function (a: any, b: any) {
    return b.sort - a.sort;
  };
}
// watch(gameStore, () => {
//   if (gameStore.gameUrl) {
//     showIframeVisible.value = true;
//   } else {
//     showIframeVisible.value = false;
//   }
// });

watch(active, async () => {
  getTaskList();
});

const progressData = ref<any>({});
const propsData = computed(() => {
  return JSON.parse(storage.getStorage(actions.PROPS_DATA) || "") || [];
});
const getProgress = computed(() => (ruleCode: any, key: any) => {
  if (ruleCode == TASK_RULE_CODE.COINS || ruleCode == TASK_RULE_CODE.PRICE) {
    return progressData.value[key]
      ? (progressData.value[key] / 10000).toFixed(2)
      : 0;
  } else {
    return progressData.value[key] ? progressData.value[key] : 0;
  }
});
const getProgressTwo = computed(() => (ruleCode: any, value: any) => {
  if (ruleCode == TASK_RULE_CODE.COINS || ruleCode == TASK_RULE_CODE.PRICE) {
    return (value / 10000).toFixed(2);
  } else {
    return value;
  }
});
const taskGo = async (index: number, state: number) => {
  const data = rowsData.value.rows[index];
  if (state == 2) {
    return toast("Recebido");
  } else if (state == 1) {
    const res = await http.getTaskAward({ ids: [data._id] });
    if (res.code != 0) {
      toast(res.txt);
      return;
    }
    toast("Recebido com sucesso");
    userStore.getUserInfo();
    await getTaskList();
    return;
  } else if (state == 0) {
    for (let i = 0; i < data.ruleList.length; i++) {
      let rule = data.ruleList[i];
      // 包含指定游戏
      if (rule.ruleCode == TASK_RULE_CODE.GAME_ID) {
        // 指定游戏 跳转打开游戏
        const res: ResultData = await http.getGameUrl({
          gameId: data.ruleList[i].value,
        });
        if (res.code != 0) {
          toast(res.txt);
          return;
        }
        gameStore.setStartGameInfo(res.data);
        break;
      }
      // 切换到游戏分类 search 页面
      else if (rule.ruleCode == TASK_RULE_CODE.GAME_CLASS) {
        // const p = JSON.stringify({ type: 2, value: rule.value });
        // storage.setSessionStorage(actions.SEARCH_DATA, p);
        const p = { type: 2, value: rule.value };
        gameStore.setSearchData(p);
        router.push("/search");
        break;
      }
      // 打开商店
      else if (rule.ruleCode == TASK_RULE_CODE.PAY) {
        router.push("/deposit");
        break;
      }
    }
  }
};
const fullImgUrl = (propId: any) => {
  let obj: any = propsData.value.find((item: any) => item._id == propId);
  return obj.iconUrl;
};
async function changeTitle(item: any) {
  active.value = item.activityCode;
  imgBanner.value = item.imgBanner;
}
const activityList = ref<Array<any>>([]);
onMounted(async () => {
  await getCustomClassList();
});
const changeCurrent = (e: any) => {
  active.value = activityList.value[e.name].activity[0].activityCode;
  imgBanner.value = activityList.value[e.name].activity[0].imgBanner;
};
const rowsData = ref<any>({});
const getTaskList = async () => {
  console.log('====================================');
  console.log(active.value);
  console.log('====================================');
  http.getTaskList({ activityCode: active.value }).then((res: any) => {
    if (res.code === 0) {
      rowsData.value = { ...res.data };
      progressData.value = res.data.progress ? res.data.progress : {};
      if (res.data.props) {
        for (let i = 0; i < res.data.props.length; i++) {
          propsDataStore.setPropsData(res.data.props[i]);
        }
      }
    }
  });
};
const getCustomClassList = async () => {
  const res = await http.getCustomClassList();
  if (res.code === 0) {
    activityList.value = res.data.filter(item=>{
      return item.activity.length !== 0;
    });
    active.value = activityList.value[current.value].activity[0].activityCode;
    imgBanner.value = activityList.value[current.value].activity[0].imgBanner;
  }
};
</script>
<style lang="scss" scoped>
.page-body {
  .content_body {
    .item-box {
      padding: 0 0.2rem;
      background-color: #511a7e;
      margin: 0.2rem 0;
      border-radius: $border-radius;
      display: flex;
      flex-direction: column;
      .right {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .btn {
          padding: 0.2rem;
          width: 2rem;
          border-radius: 0.1rem;
          font-size: 0.3rem;
          cursor: pointer;
        }
        .btn0 {
          background: #00ce81;
        }
        .btn1 {
          background-color: #a9792e;
        }
        .btn2 {
          background-color: #676e6e;
          color: #d3ddda;
        }
        .gezi {
          display: flex;
          align-items: center;
          justify-content: space-between;
          height: 1.7rem;
          &-box {
            position: relative;
            display: flex;
            align-items: center;
            justify-content: center;
            .icon {
              position: absolute;
              top: 40%;
              width: 1.3rem;
              left: 50%;
              transform: translate(-50%, -50%);
            }
            span {
              position: absolute;
              right: 10%;
              bottom: 10%;
              font-size: 0.3rem;
            }
          }
        }
      }
      .left {
        .title {
          text-align: left;
          background-image: url("https://cdn.18n.com/perfil/bg_02.png");
          background-size: 100% 100%;
          background-repeat: no-repeat;
          font-size: 0.3rem;
        }
      }
    }
    .body {
      padding: 0.2rem;
      background-color: #1b1b26;
      margin-top: 0.1rem;
      display: flex;
      flex-direction: column;
      .title-btn {
        display: flex;
        align-items: center;
        justify-content: left;
        cursor: pointer;
        .active {
          background-color: #008d70 !important;
        }
        div {
          padding: 0.2rem;
          background-color: #004644;
          margin-right: 0.2rem;
          margin: 0 0.2rem 0.2rem 0;
          width: 2.3rem;
          font-size: 0.3rem;
          height: 0.7rem;
          line-height: 0.4rem;
          border-radius: $border-radius;
        }
      }
    }
  }
}
</style>
