<script setup>
import { storeToRefs } from 'pinia'

import { useConfigStore } from '@/stores/config'
const config_store = useConfigStore()
const { conf } = storeToRefs(config_store)

import { folder_dialog } from '@/utils/dialog'

const mobile = inject('mobile')

const emulator_types = [
  { label: '夜神', value: '夜神' },
  { label: 'MuMu模拟器12', value: 'MuMu12' },
  { label: 'Waydroid', value: 'Waydroid' },
  { label: '雷电模拟器9', value: '雷电9' },
  { label: 'ReDroid', value: 'ReDroid' },
  { label: 'MuMu模拟器Pro', value: 'MuMuPro' },
  { label: 'Genymotion', value: 'Genymotion' },
  { label: '其它', value: '' }
]

const launch_options = [
  { label: '运行命令', value: 'command' },
  { label: '点击屏幕', value: 'tap' }
]

const stop_options = computed(() => {
  const result = [
    { label: '什么都不做', value: 'do_nothing' },
    { label: '退出游戏', value: 'exit_game' }
  ]
  if (!['adb_multiuser', 'scrcpy'].includes(conf.value.app_control_strategy)) {
    result.push({ label: '返回桌面', value: 'switch_to_home' })
  }
  if (conf.value.app_control_strategy != 'adb_multiuser' && conf.value.emulator.name != '') {
    result.push({ label: '退出模拟器', value: 'close_emulator' })
  }
  return result
})

async function select_emulator_folder() {
  const folder_path = await folder_dialog()
  if (folder_path) {
    conf.value.emulator.emulator_folder = folder_path
  }
}

import { file_dialog } from '@/utils/dialog'

async function select_maa_adb_path() {
  const file_path = await file_dialog()
  if (file_path) {
    conf.value.maa_adb_path = file_path
  }
}

const screencap_options = computed(() => {
  const result = [
    { label: 'DroidCast_raw（主动，无损，较快）', value: 'droidcast_raw' },
    { label: 'ADB+Gzip（主动，无损，很慢）', value: 'adb' },
    { label: 'DroidCast（主动，有损，较快）', value: 'droidcast' },
    { label: 'scrcpy（被动，有损，特殊）', value: 'scrcpy' },
    { label: '自定义（以下命令需要向STDOUT打印截图文件）', value: 'diy' }
  ]
  if (conf.value.emulator.name == 'MuMu12') {
    result.push({ label: 'MuMu模拟器12截图API（主动，无损，超快）', value: 'mumuipc' })
  }
  return result
})

const touch_options = computed(() => {
  const result = [{ label: 'scrcpy', value: 'scrcpy' }]
  if (conf.value.emulator.name == 'MuMu12') {
    result.push({ label: 'MuMu模拟器12触控API', value: 'mumuipc' })
  }
  return result
})

const app_control_options = computed(() => {
  const result = [{ label: 'ADB', value: 'adb' }]
  if (conf.value.emulator.name == 'MuMu12') {
    result.push({ label: 'MuMu模拟器12应用管理器', value: 'mumumanager' })
    if (conf.value.screencap_strategy == 'mumuipc' && conf.value.control_strategy == 'mumuipc') {
      result.push({ label: 'MuMu模拟器12应用分身', value: 'adb_multiuser' })
    }
  }
  if (conf.value.screencap_strategy == 'scrcpy' && conf.value.control_strategy == 'scrcpy') {
    result.push({ label: 'scrcpy virtual display', value: 'scrcpy' })
  }
  return result
})

const tested = ref(false)
const image = ref('')
const elapsed = ref(0)
const screenshot_success = ref(true)
const reason = ref('')
const loading = ref(false)
const axios = inject('axios')

async function test_screenshot() {
  loading.value = true
  tested.value = false
  try {
    const { data } = await axios.get(`${import.meta.env.VITE_HTTP_URL}/test-screenshot`)
    screenshot_success.value = data.success
    if (screenshot_success.value) {
      image.value = data.screenshot
      elapsed.value = data.elapsed
    } else {
      reason.value = data.reason
    }
  } finally {
    loading.value = false
    tested.value = true
  }
}

const screenshot_type = computed(() => {
  if (elapsed.value <= 50) {
    return 'success'
  } else if (elapsed.value <= 200) {
    return 'default'
  } else if (elapsed.value <= 500) {
    return 'warning'
  } else {
    return 'error'
  }
})

const auto_fill_enable = computed(() => {
  return ['夜神', 'MuMu12', '雷电9', 'ReDroid', 'Waydroid'].includes(conf.value.emulator.name)
})

const auto_fill_animation = ref(false)

async function auto_fill() {
  auto_fill_animation.value = true
  const [r1, r2] = await Promise.all([
    axios.get(`${import.meta.env.VITE_HTTP_URL}/auto-get-path`),
    axios.get(`${import.meta.env.VITE_HTTP_URL}/get-adb-serial`)
  ])
  auto_fill_animation.value = false
  if (r2.data != 'OK') {
    message.error('请填写正确的多开编号！')
  } else {
    message.success('自动填写成功！')
  }
}

const message = useMessage()

const preset = ref('custom')

watch(preset, () => {
  if (preset.value == 'mumu') {
    conf.value.emulator.name = 'MuMu12'
    conf.value.screencap_strategy = 'mumuipc'
    conf.value.control_strategy = 'mumuipc'
    conf.value.app_control_strategy = 'mumumanager'
    conf.value.kill_server_when_idle = true
  } else if (preset.value == 'mumultiuser') {
    conf.value.emulator.name = 'MuMu12'
    conf.value.screencap_strategy = 'mumuipc'
    conf.value.control_strategy = 'mumuipc'
    conf.value.app_control_strategy = 'adb_multiuser'
    conf.value.kill_server_when_idle = true
  } else if (preset.value == 'scrcpy') {
    conf.value.screencap_strategy = 'scrcpy'
    conf.value.control_strategy = 'scrcpy'
    conf.value.app_control_strategy = 'scrcpy'
    conf.value.kill_server_when_idle = true
    conf.value.strategy_when_idle = 'exit_game'
  }
})

const presets = [
  { label: 'MuMu全家桶', value: 'mumu' },
  { label: 'MuMu应用分身', value: 'mumultiuser' },
  { label: 'virtual display', value: 'scrcpy' },
  { label: '自定义', value: 'custom' }
]

onMounted(() => {
  if (
    conf.value.emulator.name == 'MuMu12' &&
    conf.value.screencap_strategy == 'mumuipc' &&
    conf.value.control_strategy == 'mumuipc' &&
    conf.value.app_control_strategy == 'mumumanager' &&
    conf.value.kill_server_when_idle == true
  ) {
    preset.value = 'mumu'
  } else if (
    conf.value.emulator.name == 'MuMu12' &&
    conf.value.screencap_strategy == 'mumuipc' &&
    conf.value.control_strategy == 'mumuipc' &&
    conf.value.app_control_strategy == 'adb_multiuser' &&
    conf.value.kill_server_when_idle == true
  ) {
    preset.value = 'mumultiuser'
  } else if (
    conf.value.screencap_strategy == 'scrcpy' &&
    conf.value.control_strategy == 'scrcpy' &&
    conf.value.app_control_strategy == 'scrcpy' &&
    conf.value.kill_server_when_idle == true &&
    conf.value.strategy_when_idle == 'exit_game'
  ) {
    preset.value = 'scrcpy'
  }
})

import SettingsAutomation from '@vicons/tabler/SettingsAutomation'
</script>

<template>
  <n-card>
    <template #header>
      <div class="card-title">设备与游戏</div>
      <n-select v-model:value="preset" :options="presets" />
      <n-button
        class="dialog-btn"
        v-if="auto_fill_enable"
        @click="auto_fill"
        :loading="auto_fill_animation"
      >
        <template #icon>
          <n-icon>
            <settings-automation />
          </n-icon>
        </template>
        <template v-if="!mobile">自动填写设置</template>
      </n-button>
    </template>
    <n-form
      :label-placement="mobile ? 'top' : 'left'"
      :show-feedback="false"
      label-width="120"
      label-align="left"
    >
      <n-form-item label="模拟器" v-if="!preset.startsWith('mumu')">
        <n-select v-model:value="conf.emulator.name" :options="emulator_types" />
      </n-form-item>
      <template v-if="conf.emulator.name">
        <n-form-item>
          <template #label>
            <span>多开编号</span>
            <help-text>
              <div>MuMu模拟器12的多开器中，第一个实例（锁形图标）的序号为0</div>
              <div>夜神模拟器单开请填写-1</div>
              <div>其它模拟器请填写多开器中的序号</div>
            </help-text>
          </template>
          <n-input v-model:value="conf.emulator.index" />
        </n-form-item>
        <n-form-item>
          <template #label>
            <span>模拟器文件夹</span>
            <help-text>
              <div>夜神：写到bin文件夹</div>
              <div>MuMu12: 写到shell文件夹</div>
            </help-text>
          </template>
          <n-input v-model:value="conf.emulator.emulator_folder" type="textarea" :autosize="true" />
          <n-button @click="select_emulator_folder" class="dialog-btn">...</n-button>
        </n-form-item>
        <n-form-item label="模拟器启动时间">
          <n-input-number v-model:value="conf.emulator.wait_time">
            <template #suffix>秒</template>
          </n-input-number>
        </n-form-item>
        <n-form-item>
          <template #label>
            <span>模拟器老板键</span>
            <help-text>
              <div>启动模拟器后按此快捷键</div>
              <div>若不需要此功能，请留空</div>
              <div>加号分隔按键，不要空格</div>
              <div>
                按键名参考
                <n-button
                  text
                  tag="a"
                  href="https://pyautogui.readthedocs.io/en/latest/keyboard.html#keyboard-keys"
                  target="_blank"
                  type="primary"
                >
                  KEYBOARD_KEYS
                </n-button>
              </div>
            </help-text>
          </template>
          <n-input v-model:value="conf.emulator.hotkey" placeholder="留空停用；组合键用加号分隔" />
        </n-form-item>
      </template>
      <template v-if="preset != 'mumu'">
        <n-divider />
        <n-form-item label="ADB路径">
          <n-input type="textarea" :autosize="true" v-model:value="conf.maa_adb_path" />
          <n-button @click="select_maa_adb_path" class="dialog-btn">...</n-button>
        </n-form-item>
        <n-form-item>
          <template #label>
            <span>ADB连接地址</span>
            <help-text>
              <div>不同模拟器adb地址不同。如不填，系统会自动去寻找adb device中的第一个。</div>
              <div>夜神：<code>127.0.0.1:62001</code></div>
            </help-text>
          </template>
          <n-input v-model:value="conf.adb" />
        </n-form-item>
      </template>
      <template v-if="preset == 'custom'">
        <n-divider />
        <n-form-item label="截图方案">
          <n-select v-model:value="conf.screencap_strategy" :options="screencap_options" />
        </n-form-item>
        <n-alert
          title="推荐使用MuMu模拟器12专属截图"
          style="margin: 8px 0"
          type="success"
          v-if="conf.emulator.name == 'MuMu12' && conf.screencap_strategy != 'mumuipc'"
        >
          通过共享内存的方式直接获取无损截图，避免了编码、解码、跨进程传输等环节的开销，截图速度远高于通用截图方案。
        </n-alert>
        <n-form-item label="触控方案">
          <n-select v-model:value="conf.control_strategy" :options="touch_options" />
        </n-form-item>
        <n-form-item label="应用控制方案">
          <n-select v-model:value="conf.app_control_strategy" :options="app_control_options" />
        </n-form-item>
        <n-form-item label="旋转截图" v-if="conf.screencap_strategy == 'droidcast'">
          <n-radio-group v-model:value="conf.droidcast.rotate">
            <n-flex>
              <n-radio :value="false">不旋转</n-radio>
              <n-radio :value="true">旋转180度</n-radio>
            </n-flex>
          </n-radio-group>
        </n-form-item>
        <template v-if="conf.screencap_strategy == 'droidcast_raw'">
          <n-form-item label="屏幕朝向">
            <n-radio-group v-model:value="conf.droidcast_raw.orientation">
              <n-flex>
                <n-radio value="portrait">竖屏</n-radio>
                <n-radio value="landscape">横屏</n-radio>
              </n-flex>
            </n-radio-group>
          </n-form-item>
          <n-form-item label="旋转截图" v-if="conf.screencap_strategy == 'droidcast_raw'">
            <n-radio-group v-model:value="conf.droidcast_raw.rotate">
              <n-flex>
                <n-radio :value="0">不旋转</n-radio>
                <n-radio :value="90">旋转90度</n-radio>
                <n-radio :value="180">旋转180度</n-radio>
                <n-radio :value="270">旋转270度</n-radio>
              </n-flex>
            </n-radio-group>
          </n-form-item>
        </template>
        <n-form-item label="截图命令" v-if="conf.screencap_strategy == 'diy'">
          <n-input
            v-model:value="conf.custom_screenshot.command"
            type="textarea"
            :autosize="true"
          />
        </n-form-item>
      </template>
      <n-divider />
      <n-form-item label="游戏服务器">
        <n-radio-group v-model:value="conf.package_type">
          <n-space>
            <n-radio value="official">官服</n-radio>
            <n-radio value="bilibili">BiliBili服</n-radio>
          </n-space>
        </n-radio-group>
      </n-form-item>
      <n-form-item v-if="conf.app_control_strategy == 'adb_multiuser'">
        <template #label>
          分身编号
          <help-text>
            <div>主应用的编号是0</div>
            <div>第一个分身的编号是1</div>
            <div>第二个分身的编号是2</div>
            <div>其余分身同理</div>
          </help-text>
        </template>
        <n-input-number v-model:value="conf.mumu_multi_app.app_index" />
      </n-form-item>
      <n-alert
        title="请开启MuMu模拟器12的后台保活！"
        style="margin: 8px 0"
        type="warning"
        v-if="conf.app_control_strategy == 'adb_multiuser'"
      />
      <n-form-item label="启动游戏" v-if="preset == 'custom'">
        <n-select v-model:value="conf.tap_to_launch_game.enable" :options="launch_options" />
      </n-form-item>
      <n-form-item v-if="conf.tap_to_launch_game.enable == 'tap'" label="点击坐标">
        <span class="coord-label">X:</span>
        <n-input-number v-model:value="conf.tap_to_launch_game.x" />
        <span class="coord-label">Y:</span>
        <n-input-number v-model:value="conf.tap_to_launch_game.y" />
      </n-form-item>
      <n-form-item label="任务结束">
        <n-select v-model:value="conf.strategy_when_idle" :options="stop_options" />
      </n-form-item>
      <n-form-item :show-label="false" v-if="preset == 'custom'">
        <n-checkbox v-model:checked="conf.kill_server_when_idle">
          <span>任务结束时关闭ADB Server</span>
          <help-text>建议开启，多开不受影响</help-text>
        </n-checkbox>
      </n-form-item>
      <n-divider />
      <n-form-item :show-label="false">
        <n-flex vertical style="gap: 12px">
          <n-flex align="center" style="gap: 12px">
            <n-button @click="test_screenshot" :loading="loading">测试截图设置</n-button>
            <template v-if="tested">
              <div v-if="screenshot_success">
                截图用时：<n-text strong :type="screenshot_type">{{ elapsed }}ms</n-text>
              </div>
              <template v-else>
                <n-text type="error">截图失败！</n-text>
                <div>{{ reason }}</div>
              </template>
            </template>
          </n-flex>
          <n-image
            v-if="tested && screenshot_success"
            :src="'data:image/jpeg;base64,' + image"
            width="100%"
          />
        </n-flex>
      </n-form-item>
    </n-form>
  </n-card>
</template>

<style scoped>
.coord-label {
  width: 40px;
  padding-left: 8px;
}

.card-title {
  margin-right: 8px;
}
</style>
