<script setup lang="jsx">
import { storeToRefs } from 'pinia'

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

import { usePlanStore } from '@/stores/plan'
const plan_store = usePlanStore()
const { operators } = storeToRefs(plan_store)
const { left_side_facility } = plan_store

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

const mobile = inject('mobile')

const facility_with_empty = computed(() => {
  return [{ label: '（加速任意贸易站）', value: '' }].concat(left_side_facility)
})

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: '使用adb命令启动', value: 'adb' },
  { label: '点击屏幕启动', value: 'tap' }
]

const stop_options = [
  { label: '什么都不做', value: 'do_nothing' },
  { label: '返回桌面', value: 'switch_to_home' },
  { label: '退出游戏', value: 'exit_game' },
  { label: '退出模拟器', value: 'close_emulator' }
]

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

import { render_op_label } from '@/utils/op_select'

const scale_marks = {}
const display_marks = [0.5, 1.0, 1.5, 2.0, 3.0]
for (let i = 0.5; i <= 3.0; i += 0.25) {
  scale_marks[i] = display_marks.includes(i) ? `${i * 100}%` : ''
}

const new_scale = ref(conf.value.webview.scale)

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 == '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 scene_name = {
  CONNECTING: '正在提交反馈至神经',
  UNKNOWN: '未知',
  UNKNOWN_WITH_NAVBAR: '有导航栏的未知场景',
  LOADING: '场景跳转时的等待界面',
  LOGIN_LOADING: '登录中',
  LOGIN_MAIN_NOENTRY: '登录页面（无按钮入口）',
  OPERATOR_ONGOING: '代理作战'
}

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()
</script>

<template>
  <div class="grid-two">
    <div class="grid-left">
      <div>
        <n-card title="设备与游戏设置">
          <n-form
            :label-placement="mobile ? 'top' : 'left'"
            :show-feedback="false"
            label-width="120"
            label-align="left"
          >
            <n-form-item label="模拟器">
              <n-select v-model:value="conf.emulator.name" :options="emulator_types" />
            </n-form-item>
            <n-form-item v-if="conf.emulator.name">
              <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-button
                class="dialog-btn"
                v-if="auto_fill_enable"
                @click="auto_fill"
                :loading="auto_fill_animation"
              >
                自动填写设置
              </n-button>
            </n-form-item>
            <n-form-item v-if="conf.emulator.name">
              <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="模拟器启动时间" v-if="conf.emulator.name">
              <n-input-number v-model:value="conf.emulator.wait_time">
                <template #suffix>秒</template>
              </n-input-number>
            </n-form-item>
            <n-form-item v-if="conf.emulator.name">
              <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>
            <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>
            <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专属截图"
              closable
              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>
            <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-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 label="启动游戏">
              <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">
              <n-checkbox v-model:checked="conf.kill_server_when_idle">
                <span>任务结束时关闭ADB Server</span>
                <help-text>建议开启，多开不受影响</help-text>
              </n-checkbox>
            </n-form-item>
          </n-form>
        </n-card>
      </div>
      <div>
        <n-card title="基建设置">
          <n-form
            :label-placement="mobile ? 'top' : 'left'"
            :show-feedback="false"
            label-width="160"
            label-align="left"
          >
            <n-form-item label="宿舍黑名单（非主力）">
              <n-transfer
                v-if="mobile"
                virtual-scroll
                source-filterable
                target-filterable
                :options="operators"
                v-model:value="conf.free_blacklist"
                :render-source-label="(o) => render_op_label(o.option)"
                :render-target-label="(o) => render_op_label(o.option)"
                :filter="(p, o) => (p ? pinyin_match(o.label, p) : true)"
              />
              <slick-operator-select v-else v-model="conf.free_blacklist" />
            </n-form-item>
            <n-form-item>
              <template #label>
                <span>跑单前置延时</span>
                <help-text>
                  <div>推荐范围5-10</div>
                  <div>可填小数</div>
                </help-text>
              </template>
              <n-input-number v-model:value="conf.run_order_delay">
                <template #suffix>分钟</template>
              </n-input-number>
            </n-form-item>
            <n-form-item :show-label="false">
              <n-checkbox v-model:checked="conf.run_order_grandet_mode.enable"
                >葛朗台跑单</n-checkbox
              >
            </n-form-item>
            <n-form-item v-if="conf.run_order_grandet_mode.enable">
              <template #label>
                <span>葛朗台缓冲时间</span>
                <help-text>推荐范围：15-30</help-text>
              </template>
              <n-input-number v-model:value="conf.run_order_grandet_mode.buffer_time">
                <template #suffix>秒</template>
              </n-input-number>
            </n-form-item>
            <n-form-item v-if="conf.run_order_grandet_mode.enable" :show-label="false">
              <n-checkbox v-model:checked="conf.run_order_grandet_mode.back_to_index">
                跑单前返回主界面以保持登录状态
              </n-checkbox>
            </n-form-item>
            <n-form-item>
              <template #label>
                <span>无人机使用房间</span>
                <help-text>
                  <div>加速制造站为指定制造站加速</div>
                  <div>（加速任意贸易站）只会加速有跑单人员作备班的站</div>
                  <div>例：没填龙舌兰但书的卖玉站 （加速任意贸易站） 不会被加速</div>
                  <div>如需要加速特定某个贸易站请指定对应房间</div>
                </help-text>
              </template>
              <n-select :options="facility_with_empty" v-model:value="conf.drone_room" />
            </n-form-item>
            <n-form-item>
              <template #label>
                <span>无人机使用阈值</span>
                <help-text>
                  <div>如加速贸易，推荐大于 贸易站数*x + 92</div>
                  <div>如加速制造，推荐大于 贸易站数*x</div>
                  <div>葛朗台跑单模式下x=0,非葛朗台推荐x=10</div>
                </help-text>
              </template>
              <n-input-number v-model:value="conf.drone_count_limit" />
            </n-form-item>
            <n-form-item>
              <template #label>
                <span>无人机加速间隔</span>
                <help-text>
                  <div>可填小数</div>
                </help-text>
              </template>
              <n-input-number v-model:value="conf.drone_interval">
                <template #suffix>小时</template>
              </n-input-number>
            </n-form-item>
            <n-form-item label="搓玉补货房间">
              <n-select
                multiple
                filterable
                tag
                :options="left_side_facility"
                v-model:value="conf.reload_room"
              />
            </n-form-item>
            <n-form-item>
              <template #label>
                <span>心情阈值</span>
                <help-text>
                  <div>2电站推荐不低于65%</div>
                  <div>3电站推荐不低于50%</div>
                  <div>即将大更新推荐设置成80%</div>
                </help-text>
              </template>
              <div class="threshold">
                <n-slider
                  v-model:value="conf.resting_threshold"
                  :step="5"
                  :min="50"
                  :max="80"
                  :format-tooltip="(v) => `${v}%`"
                />
                <n-input-number
                  v-model:value="conf.resting_threshold"
                  :step="5"
                  :min="50"
                  :max="80"
                >
                  <template #suffix>%</template>
                </n-input-number>
              </div>
            </n-form-item>
            <n-form-item :show-label="false">
              <n-checkbox v-model:checked="conf.free_room">
                宿舍不养闲人
                <help-text>干员心情回满后，立即释放宿舍空位</help-text>
              </n-checkbox>
            </n-form-item>
          </n-form>
        </n-card>
      </div>
      <div><email /></div>
      <div><SKLand /></div>
      <div><auto-fight /></div>
      <div>
        <n-card title="外观、性能与其它设置">
          <n-form
            :label-placement="mobile ? 'top' : 'left'"
            :show-feedback="false"
            label-width="120"
            label-align="left"
          >
            <n-form-item label="界面缩放">
              <n-slider
                v-model:value="new_scale"
                :step="0.25"
                :min="0.5"
                :max="3.0"
                :marks="scale_marks"
                :format-tooltip="(x) => `${x * 100}%`"
              />
              <n-button
                class="scale-apply"
                :disabled="new_scale == conf.webview.scale"
                @click="conf.webview.scale = new_scale"
              >
                应用
              </n-button>
            </n-form-item>
            <n-form-item label="显示主题">
              <n-radio-group v-model:value="conf.theme">
                <n-space>
                  <n-radio value="light">亮色</n-radio>
                  <n-radio value="dark">暗色</n-radio>
                </n-space>
              </n-radio-group>
            </n-form-item>
            <n-form-item :show-label="false">
              <n-checkbox v-model:checked="conf.webview.tray">
                使用托盘图标
                <help-text>重启生效</help-text>
              </n-checkbox>
            </n-form-item>
            <n-divider />
            <n-form-item label="截图最短间隔">
              <n-input-number v-model:value="conf.screenshot_interval" :precision="0">
                <template #suffix>毫秒</template>
              </n-input-number>
            </n-form-item>
            <n-form-item>
              <template #label>
                <span>截图保存时间</span>
                <help-text>可填小数</help-text>
              </template>
              <n-input-number v-model:value="conf.screenshot">
                <template #suffix>小时</template>
              </n-input-number>
            </n-form-item>
            <n-form-item label="等待时间">
              <n-table size="small" class="waiting-table">
                <thead>
                  <tr>
                    <th>场景</th>
                    <th>截图间隔</th>
                    <th>超时时长</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(value, key) in conf.waiting_scene_v2">
                    <td>{{ scene_name[key] }}</td>
                    <td>
                      <n-input-number v-model:value="value[0]" :show-button="false" :precision="0">
                        <template #suffix>毫秒</template>
                      </n-input-number>
                    </td>
                    <td>
                      <n-input-number v-model:value="value[1]" :show-button="false" :precision="0">
                        <template #suffix>秒</template>
                      </n-input-number>
                    </td>
                  </tr>
                </tbody>
              </n-table>
            </n-form-item>
            <n-divider />
            <n-form-item :show-label="false">
              <n-checkbox v-model:checked="conf.start_automatically"
                >启动mower-ng后直接开始运行</n-checkbox
              >
            </n-form-item>
          </n-form>
        </n-card>
      </div>
    </div>

    <div class="grid-right">
      <div><DailyMission /></div>
      <div><recruit /></div>
      <div><Depotswitch /></div>
      <div>
        <n-card>
          <template #header>
            <n-checkbox v-model:checked="conf.maa_enable">
              <div class="card-title">日常任务</div>
            </n-checkbox>
            <help-text>
              <div>刷理智周计划、每日/每周任务、信用作战</div>
            </help-text>
          </template>
          <n-form
            :label-placement="mobile ? 'top' : 'left'"
            :show-feedback="false"
            label-width="100"
            label-align="left"
          >
            <n-form-item>
              <template #label>
                <span>任务间隔</span>
                <help-text>
                  <div>可填小数</div>
                  <div>清理智、日常/周常任务领取、借助战打OF-1</div>
                </help-text>
              </template>
              <n-input-number v-model:value="conf.maa_gap">
                <template #suffix>小时</template>
              </n-input-number>
            </n-form-item>
          </n-form>
        </n-card>
      </div>
      <div><clue /></div>
      <div><weekly-plan /></div>
      <div><long-tasks /></div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.threshold {
  display: flex;
  align-items: center;
  gap: 14px;
  width: 100%;
}

.mower-basic {
  width: 100%;

  td:nth-child(1) {
    width: 120px;
  }

  td:nth-child(3) {
    padding-left: 6px;
    width: 40px;
  }
}

.riic-conf {
  width: 100%;

  td {
    &:nth-child(1) {
      width: 130px;
    }
    &:nth-child(3) {
      padding-left: 12px;
      width: 120px;
    }
  }
}

.coord {
  td {
    width: 120px;

    &:nth-child(1),
    &:nth-child(3) {
      width: 30px;
    }

    &:nth-child(2) {
      padding-right: 30px;
    }
  }
}

.coord-label {
  width: 40px;
  padding-left: 8px;
}

p {
  margin: 0 0 8px 0;
}

h4 {
  margin: 12px 0 10px 0;
}

.time-table {
  width: 100%;
  margin-bottom: 12px;

  td:nth-child(1) {
    width: 40px;
  }
}

.scale {
  width: 60px;
  text-align: right;
}

.scale-apply {
  margin-left: 24px;
}

.waiting-table {
  th,
  td {
    padding: 4px;
    min-width: 70px;
    width: 100px;

    &:first-child {
      width: auto;
      padding: 4px 8px;
    }
  }
}
</style>

<style>
/*小于1400的内容！*/
@media (max-width: 1399px) {
  .grid-two {
    margin: 0 0 -10px 0;
    width: 100%;
    max-width: 600px;
  }
  .grid-left {
    display: grid;
    row-gap: 10px;
    grid-template-columns: 100%;
  }
  .grid-right {
    display: grid;
    row-gap: 10px;
    grid-template-columns: 100%;
    margin-top: 10px;
  }
}
/*双栏 大于1400的内容 */
@media (min-width: 1400px) {
  .grid-two {
    display: grid;
    grid-template-columns: minmax(0px, 1fr) minmax(0px, 1fr);
    align-items: flex-start;
    gap: 5px;
  }
  .grid-left {
    display: grid;
    gap: 5px;
    grid-template-columns: 100%;
    max-width: 600px;
  }
  .grid-right {
    display: grid;
    gap: 5px;
    grid-template-columns: 100%;
    max-width: 600px;
  }
}

.n-divider:not(.n-divider--vertical) {
  margin: 14px 0 8px;
}

/* .results {
  display: grid;
  grid-template-rows: masonry;
  grid-template-columns: repeat(2, 600px);
  gap: 10px 10px ;
  justify-content: center;
} */
/* 实验性瀑布流（firefox nightly） */
</style>
