import CommonUtils from "../../class/utils/CommonUtils";
import Alert from "../../class/utils/Alert";
import ActionButtonUtils from "../../class/utils/ActionButtonUtils";
import FetchUtils from "../../class/utils/FetchUtils";
import DEPO_CSS from "../../../static/css/depo.module.css";
import TornStyleBlock from "../../class/utils/TornStyleBlock";
import { Container } from "../../container/Container";
import LocalConfigWrapper from "../../class/LocalConfigWrapper";
import Logger from "../../class/Logger";

const fetchUtils = Container.factory(FetchUtils);

export default function depoHelper() {
    let logger: Logger = Container.factory(Logger);
    let actionButtonUtils: ActionButtonUtils = Container.factory(ActionButtonUtils);
    let localConfigWrapper: LocalConfigWrapper = Container.factory(LocalConfigWrapper);
    let commonUtils: CommonUtils = Container.factory(CommonUtils);
    let href = window.location.href;
    let channel: 'CMPY' | 'FAC';
    const selector = { 'CMPY': "div#funds div.deposit", 'FAC': "div#armoury-donate div.cash" };
    // 公司
    if (href.includes('companies.php')) {
        channel = "CMPY";
        // 公司转跳存钱
        if (!href.includes('funds') && localConfigWrapper.config.companyRedirect) {
            const btn = document.getElementById('ui-id-9');
            if (btn) {
                btn.click();
                logger.info('已自动打开存钱页面');
            }
        }
        // 收起冰蛙表格
        if (localConfigWrapper.config.companyBWCollapse) {
            CommonUtils.elementReady('#effectiveness-wrap').then(BWTable_node => {
                document.body.classList.add('wh-bwtable-ctrl');
                CommonUtils.addStyle(`.wh-bwtable-ctrl #effectiveness-wrap {display:none !important;}`);
                const btn = document.createElement('button');
                btn.innerHTML = '展开冰蛙表格';
                btn.addEventListener('click', () => {
                    document.body.classList.toggle('wh-bwtable-ctrl');
                    btn.innerText = btn.innerText === '展开冰蛙表格' ? '收起冰蛙表格' : '展开冰蛙表格';
                });
                BWTable_node.before(btn);
            });
        }
        // 一键存钱按钮
        actionButtonUtils.add('一键存钱', companyDeposit);
    }
    // 帮派
    if (href.includes('factions.php')) {
        channel = "FAC";
        // 一键存钱按钮
        actionButtonUtils.add('一键存钱', factionDeposit);
    }
    // 存钱框浮动
    if (localConfigWrapper.config.floatDepo && channel) {
        document.body.classList.add('wh-depo-helper');
        commonUtils.styleInject(DEPO_CSS);
        CommonUtils.elementReady(selector[channel]).then(node => {
            const close_btn = document.createElement('button');
            close_btn.addEventListener('click', () => {
                document.body.classList.remove('wh-depo-helper');
                close_btn.remove();
            });
            close_btn.innerHTML = '恢复原位';
            close_btn.style.float = 'right';
            node.prepend(close_btn);
        });
    }
    // GT交易存钱
    if (location.pathname.startsWith('/trade.php')) {
        // GT助手
        let node_link = null;
        let handle = (id: string = null) => {
            let { addRFC } = window;
            // 不重复加载、已关闭的交易不加载
            if (node_link !== null || location.hash.toLowerCase().includes('logview')) {
                if (node_link) {
                    node_link.return();
                    node_link = null;
                }
                return;
            }
            logger.info('已添加GT助手');
            // 获取交易id
            let query_params = location.hash.slice(1);
            let traceId = id;
            if (!traceId) query_params.split('&').forEach(param =>
                (param.startsWith('ID=')) && (traceId = param.slice(3))
            );
            logger.info('交易id为', traceId);

            // 获取全部的钱数
            let getTraceMoney = async () => {
                if (typeof addRFC === 'function') {
                    let url = addRFC('/trade.php?step=getFullMoney&ID=' + traceId);
                    return (await fetchUtils.ajaxFetch({
                        url: url,
                        method: 'GET',
                        referrer: 'trade.php'
                    })).text();
                }
            };
            // 监听jquery ajax请求
            if (logger.debug()) $(document).ajaxComplete((_, xhr, settings) => logger.info({ xhr, settings }));
            // react 加载完成后将节点加入视图中
            CommonUtils.elementReady('#trade-container').then(() =>
                document.querySelector('#trade-container').before(_node.getBase())
            );
            // 构建dom节点
            // let node = document.createElement('div');
            let _node = new TornStyleBlock('GT助手');
            // node_link = node;
            node_link = _node;
            // let nodeTitle = document.createElement('div');
            // let nodeCont = document.createElement('div');
            let inputMoney = document.createElement('input');
            let buttonDepositAll = document.createElement('button');
            let buttonWithdraw = document.createElement('button');
            let buttonWithdrawAll = document.createElement('button');
            // let style = document.createElement('style');

            inputMoney.placeholder = '定额取钱';
            inputMoney.type = 'number';
            inputMoney.style.padding = '7px';
            inputMoney.style.paddingLeft = '14px';
            // inputMoney.classList.add('m-right10');
            buttonDepositAll.innerHTML = '全存';
            buttonDepositAll.style.color = 'green';
            buttonDepositAll.classList.add('torn-btn');
            buttonWithdraw.innerHTML = '定取';
            buttonWithdraw.classList.add('torn-btn');
            buttonWithdrawAll.innerHTML = '全取';
            buttonWithdrawAll.style.color = 'red';
            buttonWithdrawAll.classList.add('torn-btn');
            // nodeTitle.innerHTML = 'GT助手';
            // nodeTitle.classList.add('title-black', 'top-round');
            // style.innerHTML = '#WHGTHelper button{cursor:pointer;}#WHGTHelper button:hover{opacity:0.5;}';
            // nodeCont.append(inputMoney, buttonWithdraw, buttonDepositAll, buttonWithdrawAll);
            // nodeCont.classList.add('cont-gray', 'bottom-round');
            // nodeCont.style.padding = '10px';
            // node.id = 'WHGTHelper';
            // node.classList.add('m-bottom10');
            // node.append(nodeTitle, nodeCont, style);
            _node.append(inputMoney, buttonWithdraw, buttonDepositAll, buttonWithdrawAll);

            // 定取
            buttonWithdraw.addEventListener('click', async () => {
                if (parseInt(inputMoney.value) < 1) {
                    new Alert('无法定额取钱，原因：输入有误');
                    return;
                }
                let money = await getTraceMoney();
                let int = { 'input': parseInt(inputMoney.value), 'all': parseInt(money) };
                let diff = int.all - int.input;
                if (diff < 1) {
                    new Alert('无法定额取钱，原因：数不对');
                    return;
                }
                await fetchUtils.ajaxFetch({
                    url: addRFC('/trade.php'),
                    method: 'POST',
                    referrer: 'trade.php',
                    body: `step=view&sub_step=addmoney2&ID=${ traceId }&amount=${ diff }&ajax=true`,
                });
                new Alert(`已取 ${ int.input }`);
            });
            // 全存
            buttonDepositAll.addEventListener('click', async () => {
                let money = await getTraceMoney();
                if (money === '0') return;
                await fetchUtils.ajaxFetch({
                    url: addRFC('/trade.php'),
                    method: 'POST',
                    referrer: 'trade.php',
                    body: `step=view&sub_step=addmoney2&ID=${ traceId }&amount=${ money }&ajax=true`,
                });
                new Alert(`$${ money } 全部存入GT`);
            });
            // 全取
            buttonWithdrawAll.addEventListener('click', async () => {
                await fetchUtils.ajaxFetch({
                    url: addRFC('/trade.php'),
                    method: 'POST',
                    referrer: 'trade.php',
                    body: `step=view&sub_step=addmoney2&ID=${ traceId }&amount=0&ajax=true`,
                });
                new Alert('已全取');
            });
        };
        if (location.hash.includes('ID=')) handle();
        addEventListener('hashchange', () => {
            if (location.hash.includes('ID=')) handle();
            else if (location.hash.includes('initiateTrade')) {
                CommonUtils.elementReady('a[href*="trade.php#step=addmoney"]').then(node => {
                    handle(node.getAttribute('href').split('ID=')[1])
                });
            } else {
                if (node_link) node_link.remove();
                node_link = null;
                logger.info('已移除GT助手');
            }
        });
    }

    // 任何位置公司一键存钱
    if (localConfigWrapper.config.companyDepositAnywhere) {
        actionButtonUtils.add('公司存钱', () => companyDepositAnywhere());
    }
}

// 公司一键存钱
async function companyDeposit() {
    // let fetchUtils: FetchUtils = FetchUtils.getInstance();
    if (!location.href.contains('option=funds')) {
        new Alert('请先打开公司金库');
        return;
    }
    let { addRFC } = window;
    if (typeof addRFC !== 'function') return;
    let url = addRFC('https://www.torn.com/inputMoneyAction.php?step=generalAction');
    let money = await fetchUtils.ajax(url, 'GET');
    if (money === '0') return;
    let form = document.querySelector('#funds .deposit form');
    let funds_input = form.querySelectorAll('input.input-money');
    funds_input.forEach(input => {
        (input as HTMLInputElement).value = money;
        input.attributes['data-money'].value = money;
    });
    $(form).trigger('submit');
    new Alert('存钱成功');
}

// 帮派一键存钱
async function factionDeposit() {
    // let fetchUtils: FetchUtils = FetchUtils.getInstance();
    let form = document.querySelector('#armoury-donate form');
    if (!location.hash.includes('tab=armoury') || !form) {
        new Alert('请先打开金库');
        return;
    }
    if (typeof window.addRFC !== 'function') return;
    let url = window.addRFC('https://www.torn.com/inputMoneyAction.php?step=generalAction');
    let money = await fetchUtils.ajax(url, 'POST');
    if (money === '0') return;
    let funds_input = form.querySelectorAll('input.input-money');
    funds_input.forEach(input => {
        (input as HTMLInputElement).value = money;
        input.attributes['data-money'].value = money;
    });
    $(form).trigger('submit');
    let dataStr = `ajax=true&step=armouryDonate&type=cash&amount=${ money }`;
    let res = await (await window.fetch(window.addRFC('https://www.torn.com/factions.php'), {
        method: 'POST',
        body: dataStr,
        headers: { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded' }
    })).json();
    if (res.success === true) {
        new Alert('存钱成功');
        new Alert(`${ res.text }`);
    }
}

// 所有页面公司一键存钱
async function companyDepositAnywhere() {
    const logger: Logger = Container.factory(Logger);
    let { addRFC } = window;
    if (typeof addRFC !== 'function') return;
    let url = addRFC('https://www.torn.com/inputMoneyAction.php?step=generalAction');
    let money = await fetchUtils.ajax(url, 'GET');
    if (money === '0') return;
    let res = await (await window.fetch(addRFC('https://www.torn.com/companies.php?step=funds'), {
        method: 'POST',
        referrer: 'companies.php',
        body: 'deposit=' + money,
        headers: { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded' }
    })).text();
    logger.info(res);
    let node = document.createElement('div');
    node.innerHTML = res;
    let success = node.querySelector('.success-message');
    if (success) new Alert(success.innerHTML);
}
