<script lang="ts" setup>

import { inject, onMounted, ref } from "vue"
import { LoggerKey } from "../ts/class/Logger"
import { fetchCurrentMoney, fetchCurrentPropVaultAvailableMoney } from "../ts/func/utils/fetchCurrentMoney"
import { ElMessage } from "element-plus"
import toThousands from "../ts/func/utils/toThousands"

const logger = inject(LoggerKey)

const inputMoney = ref('')
const inputWithdrawMoney = ref('')
const formModel = ref({
  cash: 0, vault: 0,
})
const propId = ref(-1)

const updateCash = async () => {
  formModel.value.cash = await fetchCurrentMoney()
  return formModel.value.cash
}
const updateVault = async () => {
  formModel.value.vault = await fetchCurrentPropVaultAvailableMoney()
  return formModel.value.vault
}

/**
 * 存取钱通用
 * @param amount
 * @param action {'deposit' | 'withdraw'}
 */
const deposit = async (amount: number, action: 'deposit' | 'withdraw' = 'deposit') => {
  if (amount < 1) {
    ElMessage.error('数额不能小于1')
    logger.error('数额不能小于1')
    throw new Error('数额不能小于1')
  }
  if (propId.value === -1) {
    ElMessage.error('未获取到房产id')
    logger.error('未获取到房产id')
    throw new Error('未获取到房产id')
  }

  let response: string
  try {
    response = await (await fetch(window.addRFC("https://www.torn.com/properties.php"), {
      "headers": {
        "accept": "*/*",
        "accept-language": "zh-CN,zh;q=0.9",
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "x-requested-with": "XMLHttpRequest"
      },
      "referrer": "https://www.torn.com/properties.php",
      "referrerPolicy": "strict-origin-when-cross-origin",
      "body": "step=vaultProperty&" + action + "=" + amount + "&ID=" + propId.value,
      "method": "POST",
      "mode": "cors",
      "credentials": "include"
    })).text()
  } catch (e) {
    ElMessage.error('请求出错 ' + e.message)
    logger.error(e.stack)
    throw e
  }

  let error: string, text: string
  try {
    let json = JSON.parse(response)
    error = json.error
    text = json.text
  } catch (e) {
  }
  if (error) {
    ElMessage.error('$' + toThousands(amount) + ' 存取请求失败 ' + text)
    logger.error('存取请求失败 ' + text)
    throw new Error('存取请求失败 ' + text)
  } else {
    ElMessage.success('$' + toThousands(amount) + ' 存取请求完成')
  }

  if (action === 'deposit') {
    inputWithdrawMoney.value = ''
  } else {
    inputMoney.value = ''
  }
  updateVault().then()
  updateCash().then()
}

const getPropId = async () => {
  let response: string
  try {
    response = await (await fetch("https://www.torn.com/properties.php", {
      "headers": {
        "accept": "*/*",
        "accept-language": "zh-CN,zh;q=0.9",
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "x-requested-with": "XMLHttpRequest"
      },
      "referrer": "https://www.torn.com/properties.php",
      "referrerPolicy": "strict-origin-when-cross-origin",
      "body": "p=options&tab=vault&step=options",
      "method": "POST",
      "mode": "cors",
      "credentials": "include"
    })).text()
  } catch (e) {
    ElMessage.error('获取房产id失败，请重试')
    logger.error('获取房产id失败', e)
    throw e
  }
  const reg = /&ID=(\d+)"/
  const match = response.match(reg)
  if (match) {
    propId.value = Number(match[1])
  } else {
    ElMessage.error('获取房产id失败，报文未能成功匹配')
    logger.error('获取房产id失败，报文未能成功匹配')
    throw new Error('获取房产id失败，报文未能成功匹配')
  }
}

onMounted(async () => {
  await getPropId()
  await updateCash()
  await updateVault()
})

</script>

<template>
  <div class="gap4">
    <el-card shadow="never">当前默认房产id：{{ propId }}</el-card>
    <el-card shadow="never">
      <template #header>
        存钱：{{ toThousands(formModel.cash) }}
      </template>
      <el-row>
        <el-col :span="3">
          <el-button @click="async ()=>inputMoney=String(await updateCash())">$</el-button>
        </el-col>
        <el-col :span="18">
          <el-input v-model="inputMoney"/>
        </el-col>
        <el-col :span="3">
          <el-button @click="()=>{deposit(Number(inputMoney),'deposit');inputMoney=''}">确定</el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-card shadow="never">
      <template #header>
        取钱：{{ toThousands(formModel.vault) }}
      </template>
      <el-row>
        <el-button-group>
          <el-button type="primary" @click="()=>inputWithdrawMoney='1000000'">1m</el-button>
          <el-button type="primary" @click="()=>inputWithdrawMoney='2000000'">2m</el-button>
          <el-button type="primary" @click="()=>inputWithdrawMoney='5000000'">5m</el-button>
          <el-button type="primary" @click="()=>inputWithdrawMoney='10000000'">10m</el-button>
          <el-button type="primary" @click="()=>inputWithdrawMoney='20000000'">20m</el-button>
        </el-button-group>
      </el-row>
      <el-row>
        <el-col :span="3">
          <el-button @click="async ()=>inputWithdrawMoney=String(await updateVault())">$</el-button>
        </el-col>
        <el-col :span="18">
          <el-input v-model="inputWithdrawMoney"/>
        </el-col>
        <el-col :span="3">
          <el-button @click="()=>{deposit(Number(inputWithdrawMoney),'withdraw');inputWithdrawMoney=''}">确定
          </el-button>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<style scoped>
.gap4 .el-card {
  margin-bottom: 4px;
}
</style>