<script lang="ts" setup>

import { Refresh, ShoppingCart } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { inject, onMounted, ref } from 'vue';
import { LoggerKey } from '../ts/class/Logger';

const logger = inject(LoggerKey);

type TableData = {
  player: string,
  amount: string,
  each: string,
  totalPrice: string,
  id: string,
  onBuying: boolean,
  afterBought: boolean,
};
const tableData = ref<TableData[]>([]);
const fetchingList = ref(false);
const buy = async (tableRowData: TableData): Promise<void> => {
  tableRowData.onBuying = true;
  let res: string;
  let resJson: { color: 'red' | 'green', msg: string };
  try {
    res = await (await fetch(window.addRFC("https://www.torn.com/pmarket.php"), {
      "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/pmarket.php",
      "referrerPolicy": "strict-origin-when-cross-origin",
      "body": "ajax_action=buy1&ID=" + tableRowData.id,
      "method": "POST",
      "mode": "cors",
      "credentials": "include"
    })).text();
    resJson = JSON.parse(res);
  } catch (error) {
    tableRowData.onBuying = false;
    ElMessage.error('购买失败 ' + error.message);
    logger.error(error.stack);
    throw error;
  }
  if (resJson.color === 'green') {
    ElMessage.success('成功 ' + resJson.msg);
    tableRowData.afterBought = true;
  } else {
    ElMessage.error('失败 ' + resJson.msg);
  }
  tableRowData.onBuying = false;
};
const fetchList = async (): Promise<void> => {
  tableData.value = [];
  fetchingList.value = true;
  let fetchRes: string;
  try {
    fetchRes = await (await fetch(window.addRFC("https://www.torn.com/pmarket.php?ajax_action=refresh"), {
      "headers": {
        "accept": "text/plain, */*; q=0.01",
        "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/pmarket.php",
      "referrerPolicy": "strict-origin-when-cross-origin",
      "body": null,
      "method": "GET",
      "mode": "cors",
      "credentials": "include"
    })).text();
  } catch (e) {
    fetchingList.value = false;
    logger.error('PT出售列表获取错误', e.stack);
    throw e;
  }
  let tmpNode = document.createElement('div');
  tmpNode.innerHTML = fetchRes;
  let itemNodeList = tmpNode.querySelectorAll('li .expander');
  if (!itemNodeList.length) {
    tmpNode = null;
    itemNodeList = null;
    fetchingList.value = false;
    logger.error('无法获取PT出售列表数据, 状态是否为Torn OK?');
    ElMessage.error('无法获取PT出售列表数据, 状态是否为Torn OK?');
    throw new Error('无法获取PT出售列表数据, 状态是否为Torn OK?');
  }
  for (let i = 0; i < itemNodeList.length; i++) {
    const node = itemNodeList[i];
    const tableRowData: TableData = {
      player: '',
      amount: '',
      each: '',
      totalPrice: '',
      id: '',
      onBuying: false,
      afterBought: false
    };
    let href = node.getAttribute('href').trim();
    tableRowData.amount = href.split('points=')[1];
    tableRowData.player = node.querySelector('.user-info span[title]').getAttribute('title').trim().replaceAll(' ', '');
    tableRowData.each = node.querySelector('.cost-each').innerText?.split('Cost each')[1].trim();
    tableRowData.totalPrice = node.querySelector('.total-price').innerText?.split('Total price')[1].trim();
    let hrefSplit = href.split('&');
    for (let index = 0; index < hrefSplit.length; index++) {
      const element = hrefSplit[index];
      if (element.startsWith('ID=')) {
        tableRowData.id = element.replace('ID=', '');
        break;
      }
    }
    tableData.value.push(tableRowData);
  }
  fetchingList.value = false;
  itemNodeList = null;
  tmpNode = null;
};

onMounted(() => {
  fetchList();
});
</script>

<template>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column label="玩家" prop="player"/>
    <el-table-column label="数量" prop="amount"/>
    <el-table-column label="单价" prop="each"/>
    <el-table-column label="共计" prop="totalPrice"/>
    <el-table-column>
      <template #default="scope">
        <el-button :disabled="scope.row.afterBought" :icon="ShoppingCart" :loading="scope.row.onBuying"
                   @click="buy(scope.row)"/>
      </template>
      <template #header>
        <el-button :icon="Refresh" :loading="fetchingList" circle @click="fetchList"/>
      </template>
    </el-table-column>
  </el-table>
</template>

<style scoped></style>