/*
 * @Author: YKH
 * @Date: 2022-04-12 15:14:01
 * @LastEditTime: 2022-05-11 17:08:46
 * @Description: 
 * @FilePath: \cool-admin\cool-admin-midway-master\src\app\modules\shuyou\controller\app\vx_api.ts
 */
import { Get, Inject, Provide, Query, ALL } from '@midwayjs/decorator';
import { ILogger } from '@midwayjs/logger';
import { CoolController, BaseController } from 'midwayjs-cool-core';
import * as _ from 'lodash';
import { Utils } from '../../../../comm/utils';
var md5 = require("md5");
import { ShuyouVXApiTypeEntity } from '../../entity/vx_api_type';
import { ShuyouVXApiTypeService } from '../../service/vx_api_type';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository } from 'typeorm';


// /**同一渠道身份证最大使用次数 **/
// const repeatTime = 20

@Provide()
@CoolController()
export class ShuyouAppVXApiController extends BaseController {
  @Inject()
  logger: ILogger;

  @Inject()
  utils: Utils;

  @Inject()
  ShuyouVXApiTypeService: ShuyouVXApiTypeService;

  @InjectEntityModel(ShuyouVXApiTypeEntity)
  ShuyouVXApiTypeEntity: Repository<ShuyouVXApiTypeEntity>;
  /**
   * http://127.0.0.1:8001/app/shuyou/vx_api/getVXApi?task_id=&account=&projectId=&qrCode=&orderId=1&orderType=hongdou
   * http://ykhvip.fun/api/app/shuyou/vx_api/getVXApi?task_id=&account=&projectId=&qrCode=&orderId=1&orderType=hongdou
   * @param {*} queryObject
   * @memberof ShuyouAppVXApiController
   */
  //各种微信扫码api
  @Get('/getVXApi')
  async getVXApi(@Query(ALL) queryObject) {
    //task_id: 任务id  account：账号  projectId:项目id  qrCode: qrCode orderId:订单号  orderType:订单类型
    // console.log('getVXApi')
    const { projectId, qrCode, orderId, orderType } = queryObject
    //task_id, account,
    let lc_projectId = ''
    let hd_projectId = ''
    let mx_projectId = ''
    if (projectId == '') {
      return { code: -1, data: '项目appid未填写' }
    }
    const arr = projectId.split('----')
    for (const value of arr) {
      if (value.split('||').length < 2) {
        return { code: -1, data: '项目appid未填写' }
      }
      if (value.split('||')[0] == 'langchao') {
        lc_projectId = value.split('||')[1]
      } else if (value.split('||')[0] == 'hongdou') {
        hd_projectId = value.split('||')[1]
      } else if (value.split('||')[0] == 'mengxiang') {
        mx_projectId = value.split('||')[1]
      }
    }
    if (lc_projectId == '' && hd_projectId == '' && mx_projectId == '') {
      return { code: -1, data: '项目appid未填写' }
    }
    ///////
    let lc_account0 = ''
    let lc_password0 = ''
    let hd_account0 = ''
    let hd_password0 = ''
    let mx_account0 = ''
    let mx_password0 = ''
    const info = await this.ShuyouVXApiTypeService.list()
    if (!_.isEmpty(info)) {
      await ykhForeach2(info, async (item) => {
        if (item.mark == 'langchao') {
          lc_account0 = item.account_text
          lc_password0 = item.password_text
        } else if (item.mark == 'hongdou') {
          hd_account0 = item.account_text
          hd_password0 = item.password_text
        } else if (item.mark == 'mengxiang') {
          mx_account0 = item.account_text
          mx_password0 = item.password_text
        }
      })
    }
    if (lc_account0 == '' && hd_account0 == '' && mx_account0 == '') {
      return { code: -1, data: '暂无平台支持或其它问题' }
    }
    // console.log(lc_projectId)
    // console.log(lc_account0)
    if (orderType == '') {
      //获取平台顺序
      let res
      let flag
      flag = false
      if (!_.isEmpty(info)) {
        await ykhForeach2(info, async (item) => {
          // console.log(item)
          if (item.mark == 'langchao') {
            res = await lc_api(lc_projectId, qrCode, orderId, lc_account0, lc_password0)
            // console.log(res)
            if (res.code == 1) {
              flag = true
              return 1
            }
          } else if (item.mark == 'hongdou') {
            res = await hd_api(hd_projectId, qrCode, orderId, hd_account0, hd_password0)
            // console.log(res)
            if (res.code == 1) {
              flag = true
              return 1
            }
          }
        })
      }
      //
      // console.log(flag)
      if (flag == true) {
        return res
      } else {
        return { code: -1, data: '暂无平台支持或其它问题' }
      }
    } else if (orderType == 'langchao') {
      const res1 = await lc_api(lc_projectId, qrCode, orderId, lc_account0, lc_password0)
      return res1
    } else if (orderType == 'hongdou') {
      const res2 = await hd_api(hd_projectId, qrCode, orderId, hd_account0, hd_password0)
      return res2
    } else if (orderType == 'mengxiang') {
      const res3 = await mx_api(mx_projectId, qrCode, orderId, mx_account0, mx_password0)
      return res3
    }
    return {
      code: -1,
      orderType: '',
      orderId: ''
    }

  }


}

//浪潮
let lc_api = async function (projectId, qrCode, orderId, lc_account0, lc_password0) {
  const lc_account = lc_account0;
  const lc_password = lc_password0;
  const lc_projectId = projectId;
  const qrCode2 = qrCode;
  const orderId2 = orderId;

  const messageUrl = 'http://202.189.7.240:8082/api/userInfo?username=' + lc_account + '&password=' + lc_password
  let param = {
    username: lc_account,
    password: lc_password
  }
  //个人信息
  let message
  message = await axiosGet(messageUrl, param)
  // console.log(message)
  if (!_.isEmpty(message)) {
    if (message.code == 20000) {
      if (parseFloat(message.data.balance) < 50 && parseFloat(message.data.balance) > 49) {
        //余额即将不足处理
        //return { code: 2, message: '余额不足50元,请充值' }
        //微信机器人
        await sendVx_Robot('王梳霖:浪潮授权平台余额低于50元,请及时充值,充值账号' + lc_account);
      }
    } else {
      return { code: -1 }
    }
  } else {
    return { code: -1 }
  }
  //扫码
  const authUrl = 'http://202.189.7.240:8082/api/auth/'
  const authParam = '?username=' + lc_account + '&password=' + lc_password + '&appId=' + lc_projectId + '&qrCode=' + qrCode2 + '&grade=3&type=1&model=2&orderId=' + orderId2
  let authMsg
  authMsg = await axiosGet(authUrl + authParam, {})
  // console.log(authMsg)
  let keyword
  if (authMsg.code == 20000) {
    if (!orderId2 || orderId2 == '') {
      keyword = {
        code: 1,
        orderType: 'langchao',
        orderId: authMsg.orderId
      }
    } else {
      keyword = {
        code: 1,
        orderType: 'langchao',
        orderId: orderId2
      }
    }

  } else {
    keyword = {
      code: -1,
      orderType: 'langchao',
      orderId: ''
    }
  }
  return keyword;
}
//红豆
let hd_api = async function (projectId, qrCode, orderId, hd_account0, hd_password0) {
  const hd_account = hd_account0;
  const hd_password = hd_password0;
  const hd_projectId = projectId;
  const qrCode2 = qrCode;
  const orderId2 = orderId;
  const hd_password_md5 = md5(hd_password + "xhadmin")

  const messageUrl = 'http://hongdou.erkaisi.cn:88/api/Member/login'
  let param = {
    member_user: hd_account,
    member_pwd: hd_password_md5
  }
  //个人信息
  let message
  message = await axiosPost(messageUrl, param, {})
  let token = ''
  // console.log(message)
  if (!_.isEmpty(message)) {
    if (message.status == 200) {
      if (parseFloat(message.data.member_balance) < 50 && parseFloat(message.data.member_balance) > 49) {
        // return { code: 2, message: '余额不足50元,请充值' }
        //微信机器人
        await sendVx_Robot('王梳霖:红豆授权平台余额低于50元,请及时充值,充值账号' + hd_account);
      }
    } else {
      return { code: -1 }
    }
    token = message.token
  } else {
    return { code: -1 }
  }
  //扫码
  let authUrl = ''
  let authParam = {}
  if (!orderId2 || orderId2 == '') {
    //新号扫
    authUrl = 'http://hongdou.erkaisi.cn:88/api/Order/CreateOrder'
    authParam = {
      type: 99,
      projectid: hd_projectId,
      url: qrCode2
    }
  } else {
    //复扫
    authUrl = 'http://hongdou.erkaisi.cn:88/api/Order/twoauth'
    authParam = {
      o_id: orderId2,
      url: qrCode2
    }
  }
  const config = {
    headers: {
      Authorization: token
    }
  }

  let authMsg
  authMsg = await axiosPost(authUrl, authParam, config)
  // console.log(authMsg)
  let keyword = {}
  if (authMsg.status == 200 || (authMsg.status == 205 && orderId2 != '')) {
    if (!orderId2 || orderId2 == '') {
      keyword = {
        code: 1,
        orderType: 'hongdou',
        orderId: authMsg.data.order.id
      }
    } else {
      keyword = {
        code: 1,
        orderType: 'hongdou',
        orderId: orderId2
      }
    }

  } else {
    keyword = {
      code: -1,
      orderType: 'hongdou',
      orderId: ''
    }
  }
  //console.log(keyword)
  return keyword;
}
//梦想
let mx_api = async function (projectId, qrCode, orderId, mx_account0, mx_password0) {
  const lc_account = mx_account0;
  const lc_password = mx_password0;
  const lc_projectId = projectId;
  const qrCode2 = qrCode;
  const orderId2 = orderId;
  //
  const messageUrl = 'http://hyljy.top:8082/api/userInfo?username=' + lc_account + '&password=' + lc_password
  let param = {
    username: lc_account,
    password: lc_password
  }
  //个人信息
  let message
  message = await axiosGet(messageUrl, param)
  if (!_.isEmpty(message)) {
    if (message.code == 20000) {
      if (parseFloat(message.data.balance) <= 50 && parseFloat(message.data.balance) >= 48) {
        //余额即将不足处理
        //return { code: 2, message: '余额不足50元,请充值' }
        //微信机器人
        await sendVx_Robot('王梳霖:梦想授权平台余额低于50元,请及时充值,充值账号' + lc_account);
      }
    } else {
      return { code: -1 }
    }
  } else {
    return { code: -1 }
  }
  //扫码
  const authUrl = 'http://hyljy.top:8082/api/code/'
  const authParam = '?username=' + lc_account + '&password=' + lc_password + '&appId=' + lc_projectId + '&qrCode=' + qrCode2 + '&grade=1&type=1&model=2&orderId=' + orderId2
  let authMsg
  authMsg = await axiosGet(authUrl + authParam, {})
  // console.log(authMsg)
  let keyword
  if (authMsg.code == 20000) {
    if (!orderId2 || orderId2 == '') {
      keyword = {
        code: 1,
        orderType: 'mengxiang',
        orderId: authMsg.orderId
      }
    } else {
      keyword = {
        code: 1,
        orderType: 'mengxiang',
        orderId: orderId2
      }
    }

  } else {
    keyword = {
      code: -1,
      orderType: 'mengxiang',
      orderId: ''
    }
  }
  return keyword;
}

//访问axiosPost
let axiosPost = function (url: string, params: object, config: object) {
  var apiUrl = url;
  const axios = require('axios')
  var pm = new Promise(function (resolve, reject) {
    axios.post(apiUrl, params, config)
      .then((res) => {
        // console.log(`statusCode: ${res.statusCode}`)
        // console.log(res.data)
        resolve(res.data);
      })
      .catch((error) => {
        // console.error(error)
        reject(error)
      })
  });
  return pm;
}
//axiosGet
let axiosGet = function (url: string, params: object) {
  var apiUrl = url;
  const axios = require('axios')
  var pm = new Promise(function (resolve, reject) {
    axios.get(apiUrl, params)
      .then((res) => {
        // console.log(`statusCode: ${res.statusCode}`)
        // console.log(res.data)
        resolve(res.data);
      })
      .catch((error) => {
        // console.error(error)
        reject(error)
      })
  });
  return pm;
}
// 微信机器人接口
let sendVx_Robot = function (content) {
  var url = 'http://148.70.251.170:19730/?liebie=1&mubiao=数据优化部门群&neirong=' + content
  var http = require('http');
  var pm = new Promise(function (resolve, reject) {
    http.get(url, function (res) {
      var html = '';
      res.on('data', function (d) {
        html += d.toString()
      });
      res.on('end', function () {
        resolve(html);
      });
    }).on('error', function (e) {
      reject(e)
    });
  });
  return pm;
}
// foreach加上async/await
const ykhForeach2 = async (arr, callback) => {
  const length = arr.length;
  const O = Object(arr);
  let k = 0;
  while (k < length) {
    if (k in O) {
      // console.log('doing foreach...');
      const kValue = O[k];
      let m = await callback(kValue, k, O);
      if (m == 1) {
        return
      }
    }
    k++;
  }
};