<script lang="ts" setup>

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

const logger = inject(LoggerKey);

const inputMoney = ref('');
const inputWithdrawMoney = ref('');
const formModel = ref({
  cash: 0, company: 0,
});

const updateCash = async () => {
  formModel.value.cash = await fetchCurrentMoney();
  return formModel.value.cash;
};
const updateCompany = async () => {
  formModel.value.company = await fetchCurrentCompanyAvailableMoney();
  return formModel.value.company;
};

/**
 * 存取钱通用
 * @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');
  }

  let response: string;

  try {
    response = await (await fetch(window.addRFC("https://www.torn.com/companies.php?step=funds"), {
      "headers": {
        "accept": "*/*",
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "sec-ch-ua-mobile": "?0",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "x-requested-with": "XMLHttpRequest"
      },
      "referrer": "https://www.torn.com/companies.php",
      "referrerPolicy": "strict-origin-when-cross-origin",
      "body": action + "=" + amount,
      "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 = '';
  }
  updateCompany().then();
  updateCash().then();
};

onMounted(() => {
  updateCompany();
  updateCash();
});
</script>

<template>
  <el-form
      :model="formModel"
      label-position="top"
  >
    <el-form-item :label="'现金 $' + toThousands(formModel.cash)">
      <el-input
          v-model="inputWithdrawMoney"
          :formatter="toThousands" clearable
          :parser="(value) => value.replaceAll(',', '')"
      >
        <template #prepend>
          <el-button @click="async () => inputWithdrawMoney = toThousands(await updateCash())">$</el-button>
        </template>
        <template #append>
          <el-button @click="deposit(Number(inputWithdrawMoney.replaceAll(',', '')))">存入</el-button>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item :label="'公司可用余额 $' + toThousands(formModel.company)">
      <el-input
          v-model="inputMoney"
          :formatter="toThousands" clearable
          :parser="(value) => value.replaceAll(',', '')"
      >
        <template #prepend>
          <el-button @click="async () => inputMoney = toThousands(await updateCompany())">$</el-button>
        </template>
        <template #append>
          <el-button @click="deposit(Number(inputMoney.replaceAll(',', '')), 'withdraw')">取出</el-button>
        </template>
      </el-input>
    </el-form-item>
  </el-form>
</template>

<style scoped>
.el-input {
  max-width: 400px;
}
</style>
