import { PinusWSClient } from 'pinus-robot-plugin';
import { expect } from 'chai';
import { checkSuccessResponse, checkRoleInfo } from './CheckPatten';
import { DEBUG_MAGIC_WORD, PUSH_ROUTE, STATUS } from '../app/consts';
import { genCode } from './pureUtil';
const request = require('request');
const crypto = require('crypto');

export class Client {
  private _client;
  private _roleInfo;
  private ENCRYPT_IV = 'f7182j5f04e377ux';
  private ENCRYPT_KEY = 'fiqaxijabbantusmprc234fj';
  private serverId = 1;

  constructor(tel: string = '13636354764') {
    const param = {tel, deviceId: genCode(10), code: '', platform: 'ios', pkgName: 'com.bantu.zyz', serverType: 'dev'};
    const paramStr = this.aesEncrypt(JSON.stringify(param), this.ENCRYPT_KEY, this.ENCRYPT_IV);
    request.post('http://127.0.0.1:7001/user/smslogin', {
      json: {
        data: paramStr
      }
    }, (err, res, body) => {
      const loginRes = JSON.parse(this.aesDecrypt(body.result, this.ENCRYPT_KEY, this.ENCRYPT_IV));
      checkSuccessResponse(loginRes);
      request.post('http://127.0.0.1:7001/user/checkrole', {
        json: {
          data: this.aesEncrypt(JSON.stringify({token: loginRes.data.token, serverId: this.serverId}), this.ENCRYPT_KEY, this.ENCRYPT_IV)
        }
      }, (err, res, body) => {
        const checkRoleRes = JSON.parse(this.aesDecrypt(body.result, this.ENCRYPT_KEY, this.ENCRYPT_IV));
        if (checkRoleRes.code === 0) {
          this.createClient(loginRes.data.token);
        } else {
          this.createRole(loginRes.data.token, () => {
            this.createClient(loginRes.data.token);
          });
        }
      });
    });
  }

  createRole(token, sucCB) {
    request.post('http://127.0.0.1:7001/user/createrole', {
      json: {
        data: this.aesEncrypt(JSON.stringify({token, serverId: this.serverId}), this.ENCRYPT_KEY, this.ENCRYPT_IV)
      }
    }, (err, res, body) => {
      const result = JSON.parse(this.aesDecrypt(body.result, this.ENCRYPT_KEY, this.ENCRYPT_IV));
      checkSuccessResponse(result);
      sucCB();
    });
  }

  createClient(token) {
    this._client = new PinusWSClient();
    let host = '127.0.0.1';
    let port = '3050';
    this._client.init({
      host: host,
      port: port
    }, (data) => {
      // 连接成功执行函数
        this._client.on(PUSH_ROUTE.ADD_CHANNEL, (msg) => {
          checkSuccessResponse(msg);
          expect(msg.data.roleId).to.be.a('string');
          expect(msg.data.channelName).to.be.a('string');
        });
        this._client.request('connector.entryHandler.enter', { serverId: this.serverId, token }, (enterRes) => {
          // 消息回调
          checkSuccessResponse(enterRes);
          this._client.request('connector.entryHandler.debugGetRole', { magicWord: DEBUG_MAGIC_WORD }, (enterRes) => {
            checkSuccessResponse(enterRes);
            expect(enterRes.data.role).to.be.an('object');
            checkRoleInfo(enterRes.data.role)
            this._roleInfo = enterRes.data.role;

            this._client.request('role.roleHandler.initRole', { serverId: this.serverId, token, roleName: genCode(8) }, (initRoleRes) => {
              if (initRoleRes.code !== 0 && initRoleRes.code !== STATUS.ROLE_HAS_INIT.code) {
                console.error('initRole error', initRoleRes.code, typeof initRoleRes.code);
              }
            });
          });
        });
    });
  }

  get roleInfo() {
    return this._roleInfo;
  }

  get client() {
    return this._client;
  }

  private aesEncrypt(data, key, iv) {
    const cipher = crypto.createCipheriv('aes-192-cbc', key, iv);
    var crypted = cipher.update(data, 'utf8', 'hex');
    crypted += cipher.final('hex');
    return crypted;
  }

  private aesDecrypt(data, key, iv) {
    const decipher = crypto.createDecipheriv('aes-192-cbc', key, iv);
    var decrypted = decipher.update(data, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    return decrypted;
  }
}
