<script setup>
import { useConfigStore } from '@/stores/config'
import { storeToRefs } from 'pinia'
const config = useConfigStore()
const { conf } = storeToRefs(config)

function weekday() {
  const day = new Date().getDay()
  return day == 0 ? 6 : day - 1
}
const weekday_display_name = ['一', '二', '三', '四', '五', '六', '日']

const general_important_stages = ['', 'Annihilation']
const general_unimportant_stages = [
  '1-7',
  'LS-6',
  'CE-6',
  'AP-5',
  'SK-5',
  'CA-5',
  'PR-A-2',
  'PR-A-1',
  'PR-B-2',
  'PR-B-1',
  'PR-C-2',
  'PR-C-1',
  'PR-D-2',
  'PR-D-1'
]
const time_table = {
  CE: [1, 3, 5, 6],
  AP: [0, 3, 5, 6],
  SK: [0, 2, 4, 5],
  CA: [1, 2, 4, 6],
  'PR-A': [0, 3, 4, 6],
  'PR-B': [0, 1, 4, 5],
  'PR-C': [2, 3, 5, 6],
  'PR-D': [1, 2, 5, 6]
}
function display_name(stage) {
  switch (stage) {
    case '':
      return '上次作战'
    case 'Annihilation':
      return '当期剿灭'
    case 'LS-6':
      return '经验书'
    case 'CE-6':
      return '龙门币'
    case 'AP-5':
      return '红票'
    case 'SK-5':
      return '碳本'
    case 'CA-5':
      return '技能书'
    case 'PR-A-1':
      return '医疗重装1'
    case 'PR-A-2':
      return '医疗重装2'
    case 'PR-B-1':
      return '狙击术师1'
    case 'PR-B-2':
      return '狙击术师2'
    case 'PR-C-1':
      return '先锋辅助1'
    case 'PR-C-2':
      return '先锋辅助2'
    case 'PR-D-1':
      return '近卫特种1'
    case 'PR-D-2':
      return '近卫特种2'
    default:
      return stage
  }
}

const plan = computed(() => {
  const result = []

  for (const stage of general_important_stages) {
    const week = []
    for (let j = 0; j < 7; ++j) {
      week.push({ available: true, enable: conf.value.weekly_plan[j].general.includes(stage) })
    }
    result.push({ stage, week })
  }

  for (const stage of conf.value.custom_stages) {
    const week = []
    for (let j = 0; j < 7; ++j) {
      week.push({ available: true, enable: conf.value.weekly_plan[j].custom.includes(stage) })
    }
    result.push({ stage, week })
  }

  for (const stage of general_unimportant_stages) {
    let available = [0, 1, 2, 3, 4, 5, 6]
    for (const [j, k] of Object.entries(time_table)) {
      if (stage.includes(j)) {
        available = k
        break
      }
    }
    const week = []
    for (let j = 0; j < 7; ++j) {
      week.push({
        available: available.includes(j),
        enable: conf.value.weekly_plan[j].general.includes(stage)
      })
    }
    result.push({ stage, week })
  }

  return result
})

function change_plan(new_plan) {
  const result = []
  for (let j = 0; j < 7; ++j) {
    const day_plan = { general: [], custom: [] }
    for (const { stage, week } of new_plan) {
      if (!week[j].enable) {
        continue
      }
      if (stage == null) {
        continue
      }
      if (conf.value.custom_stages.includes(stage)) {
        day_plan.custom.push(stage)
      } else {
        day_plan.general.push(stage)
      }
    }
    result.push(day_plan)
  }
  conf.value.weekly_plan = result
}

import { deepcopy } from '@/utils/deepcopy'

function select_all(index) {
  const new_plan = deepcopy(plan.value)
  let changed = false
  for (const i of new_plan[index].week) {
    if (i.enable != i.available) {
      changed = true
      i.enable = i.available
    }
  }
  if (!changed) {
    for (const i of new_plan[index].week) {
      i.enable = false
    }
  }
  change_plan(new_plan)
}

function toggle_plan(index, wi) {
  const new_plan = deepcopy(plan.value)
  new_plan[index].week[wi].enable = !new_plan[index].week[wi].enable
  change_plan(new_plan)
}

function create_tag(label) {
  label = label.toUpperCase()
  if (label == ' ' || label == '上次作战') {
    return {
      label: '上次作战',
      value: ''
    }
  } else if (label == '当期剿灭') {
    return {
      label: '当期剿灭',
      value: 'Annihilation'
    }
  } else if (label.endsWith('磨难') || label.endsWith('标准')) {
    label = label.slice(0, -2)
    return {
      label,
      value: label
    }
  } else {
    return {
      label,
      value: label
    }
  }
}

const mobile = inject('mobile')

const bg_off = computed(() => {
  return conf.value.theme == 'light' ? 'hsl(33, 30%, 91%)' : 'hsl(33, 15%, 50%)'
})
const bg_on = computed(() => {
  return conf.value.theme == 'light' ? 'hsl(200, 90%, 65%)' : 'hsl(200, 80%, 30%)'
})

const activity_url = `${import.meta.env.VITE_HTTP_URL}/activity`
const activity = ref([])

const axios = inject('axios')

async function get_activity() {
  const { data } = await axios.get(activity_url)
  activity.value = data.reverse()
}

onMounted(() => {
  get_activity()
})

import RefreshIcon from '@vicons/tabler/Refresh'

function drag(a, ev) {
  ev.dataTransfer.setData('text', a)
}

function drop(index, ev) {
  ev.preventDefault()
  const data = ev.dataTransfer.getData('text')
  conf.value.custom_stages[index - 2] = data
}

const disabled_color = computed(() => {
  return conf.value.theme == 'light' ? 'rgba(194, 194, 194, 1)' : 'rgba(255, 255, 255, 0.38)'
})
</script>

<template>
  <n-card>
    <template #header>
      <div class="card-title" :class="{ disabled: !conf.maa_enable }">刷理智周计划</div>
      <help-text>
        <div v-if="!conf.maa_enable">需开启日常任务</div>
        <template v-else>
          <div>支持所有主线关卡；</div>
          <div>含磨难的主线关卡仅需填写关卡名，会自动选择难度。</div>
        </template>
      </help-text>
    </template>

    <n-form
      :label-placement="mobile ? 'top' : 'left'"
      :show-feedback="false"
      label-width="72"
      label-align="left"
      style="margin-bottom: 16px"
    >
      <n-form-item class="form-item" :show-label="false">
        <n-checkbox v-model:checked="conf.use_all_medicine">自动使用全部理智药</n-checkbox>
      </n-form-item>
      <n-form-item class="form-item" :show-label="false">
        <n-flex>
          <n-checkbox
            v-model:checked="conf.maa_expiring_medicine"
            :disabled="conf.use_all_medicine"
          >
            自动使用将要过期（约3天）的理智药
          </n-checkbox>
          <n-checkbox
            v-model:checked="conf.exipring_medicine_on_weekend"
            :disabled="conf.use_all_medicine || !conf.maa_expiring_medicine"
          >
            仅在周末使用
          </n-checkbox>
        </n-flex>
      </n-form-item>
    </n-form>

    <n-flex class="activity">
      <template v-if="activity.length > 0">
        <n-tag v-for="a in activity" draggable="true" @dragstart="drag(a, $event)">{{ a }}</n-tag>
      </template>
      <div v-else>当前暂无活动开放</div>
      <n-button text type="primary" @click="get_activity">
        <template #icon>
          <n-icon>
            <refresh-icon />
          </n-icon>
        </template>
      </n-button>
    </n-flex>

    <div class="tasktable">
      <table>
        <thead>
          <tr>
            <th>全选</th>
            <th>关卡</th>
            <th v-for="j in 7" :key="j">
              {{ weekday_display_name[j - 1] }}
              <div v-if="weekday() == j - 1" class="today">今天</div>
            </th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="({ stage, week }, index) in plan" :key="index">
            <td>
              <n-button
                quaternary
                class="class1"
                @click="select_all(index)"
                style="width: 100%; height: 100%"
              >
              </n-button>
            </td>
            <td>
              <template v-if="2 <= index && index < 5">
                <n-select
                  v-if="stage == null"
                  placeholder="关卡"
                  v-model:value="conf.custom_stages[index - 2]"
                  filterable
                  multiple
                  tag
                  :show="false"
                  :show-arrow="false"
                  :on-create="create_tag"
                  @update:value="
                    (v) => {
                      conf.custom_stages[index - 2] = v[0]
                    }
                  "
                  @dragover.prevent
                  @drop="drop(index, $event)"
                />
                <n-tag
                  v-else
                  closable
                  class="custom-tag"
                  @close="
                    () => {
                      conf.custom_stages[index - 2] = null
                      change_plan(plan)
                    }
                  "
                  @dragover.prevent
                  @drop="drop(index, $event)"
                >
                  {{ stage }}
                </n-tag>
              </template>
              <span v-else>{{ display_name(stage) }}</span>
            </td>
            <td v-for="(w, wi) of week" :class="{ class2: w.enable, class1: w.available }">
              <n-button
                v-if="w.available"
                quaternary
                style="width: 100%; height: 100%"
                @click="toggle_plan(index, wi)"
              >
                <span><template v-if="w.enable">打</template></span>
              </n-button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </n-card>
</template>

<style scoped lang="scss">
.tasktable {
  margin-top: 4px;
  width: 100%;
  overflow: scroll;

  table {
    border-collapse: collapse;
    width: 100%;
  }
}

.btn-clear {
  margin: 4px;
}

@media screen and (max-width: 1399px) {
  .tasktable {
    max-height: 300px;

    td {
      width: calc(72% / 7);
      &:first-child {
        width: 10%;
      }
      &:nth-child(2) {
        width: 18%;
      }
    }
    thead {
      position: sticky;
      top: 0;
      background-color: hsl(196, 26%, 60%);
      z-index: 1;
    }
  }
}

@media screen and (min-width: 1400px) {
  .tasktable {
    td {
      width: calc(72% / 7);
      &:first-child {
        width: 10%;
      }
      &:nth-child(2) {
        width: 18%;
      }
    }
    thead {
      background-color: hsl(196, 26%, 60%);
    }
  }
}

.class1 {
  background-color: v-bind('bg_off');
  text-align: center;
  vertical-align: middle;
}

.class2 {
  background-color: v-bind('bg_on');
  text-align: center;
  vertical-align: middle;
}

.custom-tag {
  width: 100%;
  height: 100%;
  justify-content: space-between;
}

.today {
  font-weight: normal;
  font-size: 12px;
}

.activity {
  align-items: center;
  gap: 4px !important;
}

.card-title {
  transition: 0.3s;
}

.disabled {
  color: v-bind(disabled_color);
}

.form-item {
  margin: 0 0 4px 0;
}
</style>
