import Koa from 'koa';
import Router from '@koa/router';
import Msg from './msg'; // 确保路径是正确的
const winston = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');
const path = require('path');
const bodyParser = require('koa-bodyparser');
const CryptoJS = require("crypto-js");
const axios = require('axios');
const querystring = require('querystring');
const servers = require('./serverList.json')

const AppKey = "64ba80a7e327f3f334425d8a8d897117"
const AppId = "120"
// var Url =  'ws://43.198.254.107:8192' //服务器地址
const Account = "H1EqhbpA80jt0Jw6Q3T2"//ws请求密钥
const SdkUrl = "https://sdk.87game1.com/cp/user/check"
var orderList = []


const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  defaultMeta: { service: 'sdk-service' }
});

logger.add(new DailyRotateFile({
  dirname: path.join(__dirname, 'logs'),
  filename: '%DATE%.log',
  datePattern: 'YYYY-MM-DD-HH',
  zippedArchive: true,
  maxSize: '20m',
  maxFiles: '14d'
}));

logger.add(new winston.transports.Console({
  format: winston.format.simple(),
}));

const app = new Koa();
const router = new Router();

app.use(bodyParser());
// 将路由应用到 Koa 应用上
app.use(router.routes()).use(router.allowedMethods());

// 支付回调
router.post('/callback', async (ctx, next) => {
  let ret = "FAILURE"
  var result = await callPay(ctx)
  if(result){
      ret = "SUCCESS"
  }
  ctx.body = ret
})

//账号验证
router.post("/checkUserToken",async (ctx,next)=>{
  const result = await checkUserToken(ctx);
  let data = {"status":false,"sign":""}
  if(result != ""){
      data.status = true
      data.sign = result
  }

  ctx.body = data
})

// router.post('/testCallback', async (ctx, next) => {

//  //发货
//   // 使用 Msg 类的 connect 方法连接到 WebSocket 服务器
//   Msg.connect(Url, Account);
  
//   // 在适当的时机，调用 CG_ASK_LOGIN 方法
//   let params = `{"account":"23417","order":"123456","id":102,"cnt":100,"money":6}`

//   setTimeout(function() {
//     console.log("这个消息将在3秒后打印出来");
//      Msg.CG_ASK_LOGIN(Account, 0, "", 'cn', 'CN',Url, params);
//   }, 3000);

//   ctx.body = "ok"
// })

router.get('/serverList',async (ctx,next)=>{
  let id = ctx.query.id
  console.log(getServerList(id))
  ctx.body = servers

})


app.listen(3000);


//根据区服id获取地址
const getServerList = (serverId) => {
  for(let i=0;i<servers.length;i++){
      if(servers[i].id == serverId){
        return 'ws://'+servers[i].ip+':'+ servers[i].port
      }
  }
}

//支付回调逻辑
const callPay = async(ctx)=>{

  let data = ctx.request.body

  logger.info("pay callback params:",{"url":ctx.href,"params":data})
  let appId  = querystring.escape(data.app_id)
  let cpOrderId = querystring.escape(data.cp_order_id)
  let memId = querystring.escape(data.mem_id)
  let orderId = querystring.escape(data.order_id)
  let orderStatus = querystring.escape(data.order_status)
  let payTime = querystring.escape(data.pay_time)
  let productId = querystring.escape(data.product_id)
  let productName = querystring.escape(data.product_name)
  let productPrice = querystring.escape(data.product_price)
  let ext = querystring.escape(data.ext)
  let serverId = data.server_id

  let sign = data.sign
  let signStr = `app_id=${appId}&cp_order_id=${cpOrderId}&ext=${ext}&mem_id=${memId}&order_id=${orderId}&order_status=${orderStatus}&pay_time=${payTime}&product_id=${productId}&product_name=${productName}&product_price=${productPrice}&app_key=`
  signStr += AppKey
  let newSign = CryptoJS.MD5(signStr).toString();
  console.log("signStr:",signStr)
  console.log("newSign:",newSign)
  if(sign != newSign){
    console.log("签名错误:",signStr,newSign,sign)
    return false
  }
  console.log(111,orderList)
  if(orderList.includes(data.order_id)){
    logger.error("订单号无效",data.order_id)
    return false
  }
  let url = getServerList(serverId)
    if(!url){
     console.log("区服id错误")
    return false
  }
  //发货
  // 使用 Msg 类的 connect 方法连接到 WebSocket 服务器
  Msg.connect(url, Account);
  
  let orgMemId = data.mem_id
  let orgOderId = data.order_id
  let orgProductId = data.product_id
  let orgExt = data.ext
  let orgProductPrice = data.product_price
  // 在适当的时机，调用 CG_ASK_LOGIN 方法
  let params = `{"account":"${orgMemId}","order":"${orgOderId}","id":${orgProductId},"cnt":100,"money":${orgProductPrice}}`

  setTimeout(function() {
    console.log("这个消息将在3秒后打印出来");
     Msg.CG_ASK_LOGIN(Account, 0, "", 'cn', 'CN',ctx.request.ip, params);
  }, 3000);
  orderList.push(data.order_id)
  return true

}

//验证账号
const checkUserToken = async(ctx)=>{
  let id = AppId
  let key = AppKey
  let memId = ctx.request.body.mem_id
  let userToken = ctx.request.body.user_token
  let signStr = `app_id=${id}&mem_id=${memId}&user_token=${userToken}&app_key=${key}`
  console.log("signStr",signStr)
  let sign = CryptoJS.MD5(signStr).toString()
  let params = {
    "app_id": AppId,
    "mem_id":memId,
    "user_token":userToken,
    "sign":sign
  }
  logger.info("req params",{"url":SdkUrl,"params":params})
  var ret = axios.post(SdkUrl, params)

  .then(function (response) {
    // 处理成功的情况
    logger.info("sdk resp data",response.data)
    if(response.data.status ==1){
      return sign
    }
    return ""

  })
  .catch(function (error) {
    // 处理错误的情况
    logger.error("请求sdk服务器错误:"+error.response.statusText)
    return ""
  });
  return ret
}


















