import {ApiCall} from "tsrpc";
import {Reqopen, Resopen} from "../../monopoly/protocols/games/Ptlopen";
import {env} from "process";
import request from "sync-request";
import fs from "fs";
import {initStarupFun} from "../../starup";
const shell = require('shelljs');

export default async function (call: ApiCall<Reqopen, Resopen>) {
    // 设置开区时间
    let _opentine = call.req.opentime

    let _dateTime = new Date(_opentine);
    _dateTime = new Date(_dateTime.getTime());
    G.openTime = _dateTime.format('YYYY-MM-DD hh:mm:ss')

    await setConfig()

    call.succ({
        code: 0,
        message: G.openTime
    });

    await initStarupFun.initStart()

    if(call.req.utc){
        console.log('---------------开始修改时区shell脚本---------------')
        shell.exec(`sh /app/zoeninfo.sh ${call.req.utc}`)
    }else{
        console.log("o2s里收到开区命令 即将pm2 reload all");
        shell.exec(`pm2 reload all`)
    }
}

async function setConfig(){
    let type = env.SERVER_TYPE || 'game';
    let url = `http://server-tool:7456/server/getConfig?sid=${env.SERVER_ID}&type=${type}`
    console.log('拉取服务端启动配置文件', url);

    let res = await request('GET', url, {
        headers: {
            'content-type': 'application/json'
        }
    });

    const body = JSON.parse(res.body.toString());
    if (body) {
        await fs.writeFileSync('/app/config.json', JSON.stringify(body, null, 2));
        console.log('服务端配置: ', body);
    } else {
        console.log('拉取失败');
    }
}