var System = require("../../system")
const http = require("http")
const querystring = require('querystring');
const md5 = require("MD5");
const uuidv4 = require('uuid/v4');
var settings = require("../../../config/settings");
const logCtl = System.getObject("web.oplogCtl");
/**
 * 接收渠道提报数据
 * 2020.03.04
 * zhuangbing
 */
class ChannelReceiveApi {
  constructor() {
    this.channelreceiveSve = System.getObject("service.channelreceiveSve");
    this.userSve = System.getObject("service.userSve");
    this.appSve = System.getObject("service.appSve");
    this.channelSve = System.getObject("service.channelSve");
  };
  async getUidStr(len, radix) {
    var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
    var uuid = [],
      i;
    radix = radix || chars.length;
    if (len) {
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
      var r;
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random() * 16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }
    return uuid.join('');
  }
  async checkAndLogin(userInfo, appInfo) {
    if (!userInfo || !userInfo.channel_userid) {
      return { code: -1, msg: "未知渠道用户" };
    }
    if (!appInfo || !appInfo.app_code) {
      return { code: -2, msg: "渠道编码错误" };
    }
    var app = await this.appSve.dao.model.findOne({
      where: { appid: "2e787bbaacda4c6488b9fae58fff30ba", isEnabled: 1 },
      raw: true
    });
    if (!app || !app.id) {
      return { code: -100, msg: "未知应用" };
    }
    var openid = appInfo.app_code + "_" + userInfo.channel_userid;
    var user = await this.userSve.dao.model.findOne({
      where: {
        openid: openid, app_id: app.id
      },
      raw: true
    });
    if (!user) {
      var name = await this.getUidStr(8, 62);
      user = {
        app_id: app.id,//应用id
        nickName: userInfo.channel_nickname || userInfo.channel_username || name,
        openId: openid,
        unionId: openid,
        onlyCode: openid,
        mobile: userInfo.channel_userid || "",
        userName: userInfo.channel_username || userInfo.channel_nickname || name,
        headUrl: "",
        appKey: "2e787bbaacda4c6488b9fae58fff30ba"
      };
      user["description"] = "渠道接入_自动提报";
      await this.userSve.loginWithoutGift(user);
      // user = await this.userSve.getUserByOpenId(openid, "2e787bbaacda4c6488b9fae58fff30ba");
      user = await this.userSve.dao.model.findOne({
        where: {
          openid: openid, app_id: app.id
        },
        raw: true
      });
    }
    return { code: 1, data: user };
  };

  //商标自动提报(渠道)
  async createChannelOrder(pobj, obj) {
    //日志记录
    logCtl.info({
      optitle: "接收渠道推送过来的订单信息",
      op: "/api/channelreceiveApi/createChannelOrder",
      content: JSON.stringify(obj),
      clientIp: ""
    });
    var userInfo = obj.userInfo;
    var appInfo = obj.appInfo;
    if (!appInfo || !appInfo.app_code) {
      return { code: -1, msg: "appInfo参数错误" };
    }
    try {
      var app = await this.appSve.dao.model.findOne({
        where: { appid: "2e787bbaacda4c6488b9fae58fff30ba", isEnabled: 1 },
        raw: true
      });
      if (app) {
        obj["app"] = app
      } else {
        return { code: -100, msg: "未知应用" };
      }
      var channel = await this.channelSve.getChannelItem(appInfo.app_code);
      if (channel) {
        obj["channel"] = channel
      } else {
        return { code: -101, msg: "未知渠道" };
      }
      var userRes = await this.checkAndLogin(userInfo, appInfo);
      if (!userRes || userRes.code != 1) {
        return { code: -102, msg: "未知用户" };
      } else {
        obj["user"] = userRes.data;
      }
      return await this.channelreceiveSve.createChannelOrder(obj);
    } catch (e) {
      return { code: -200, msg: "操作失败", err: e.stack };
    }
  }
  async getUserInfo(userInfo, appInfo, app) {
    if (!userInfo || !userInfo.channel_userid) {
      return { code: -1, msg: "未知渠道用户" };
    }
    if (!appInfo || !appInfo.app_code) {
      return { code: -2, msg: "渠道编码错误" };
    }
    var openid = appInfo.app_code + "_" + userInfo.channel_userid;
    if (!app || !app.id) {
      return { code: -100, msg: "未知应用" };
    }
    var user = await this.userSve.dao.model.findOne({
      where: {
        openid: openid, app_id: app.id
      },
      raw: true
    });
    return user;
  };
  //修改商标信息
  async updateChannelTmInfo(pobj, obj) {
    var userInfo = obj.userInfo;
    var appInfo = obj.appInfo;
    if (!appInfo || !appInfo.app_code) {
      return { code: -1, msg: "appInfo参数错误" };
    }
    try {
      var app = await this.appSve.dao.model.findOne({
        where: { appid: "2e787bbaacda4c6488b9fae58fff30ba", isEnabled: 1 },
        raw: true
      });
      if (app) {
        obj["app"] = app
      } else {
        return { code: -100, msg: "未知应用" };
      }
      var channel = await this.channelSve.getChannelItem(appInfo.app_code);
      if (channel) {
        obj["channel"] = channel
      } else {
        return { code: -101, msg: "未知渠道" };
      }
      var user = await this.getUserInfo(userInfo, appInfo, app);
      if (user) {
        obj["user"] = user;
      } else {
        return { code: -102, msg: "未知用户" };
      }
      return await this.channelreceiveSve.updateChannelTmInfo(obj);
    } catch (e) {
      return { code: -200, msg: "操作失败", err: e.stack };
    }
  }
  //修改商标联系人信息
  async updateChannelCustomerInfo(pobj, obj) {
    var userInfo = obj.userInfo;
    var appInfo = obj.appInfo;
    if (!appInfo || !appInfo.app_code) {
      return { code: -1, msg: "appInfo参数错误" };
    }
    try {
      var app = await this.appSve.dao.model.findOne({
        where: { appid: "2e787bbaacda4c6488b9fae58fff30ba", isEnabled: 1 },
        raw: true
      });
      if (app) {
        obj["app"] = app
      } else {
        return { code: -100, msg: "未知应用" };
      }
      var channel = await this.channelSve.getChannelItem(appInfo.app_code);
      if (channel) {
        obj["channel"] = channel
      } else {
        return { code: -101, msg: "未知渠道" };
      }
      var user = await this.getUserInfo(userInfo, appInfo, app);
      if (user) {
        obj["user"] = user;
      } else {
        return { code: -102, msg: "未知用户" };
      }
      return await this.channelreceiveSve.updateChannelCustomerInfo(obj);
    } catch (e) {
      return { code: -200, msg: "操作失败", err: e.stack };
    }
  }

  //渠道商标方案确认
  async channelTmConfirm(pobj, obj) {
    // var userInfo = obj.userInfo;
    var appInfo = obj.appInfo;
    if (!appInfo || !appInfo.app_code) {
      return { code: -1, msg: "appInfo参数错误" };
    }
    try {
      var app = await this.appSve.dao.model.findOne({
        where: { appid: "2e787bbaacda4c6488b9fae58fff30ba", isEnabled: 1 },
        raw: true
      });
      if (app) {
        obj["app"] = app
      } else {
        return { code: -100, msg: "未知应用" };
      }
      // var channel = await this.channelSve.getChannelItem(appInfo.app_code);
      // if (channel) {
      //   obj["channel"] = channel
      // } else {
      //   return { code: -101, msg: "未知渠道" };
      // }
      // var user = await this.getUserInfo(userInfo, appInfo,app);
      // if (user) {
      //   obj["user"] = user;
      // } else {
      //   return { code: -102, msg: "未知用户" };
      // }
      return await this.channelreceiveSve.channelTmConfirm(obj);
    } catch (e) {
      return { code: -200, msg: "操作失败", err: e.stack };
    }
  }
}
module.exports = ChannelReceiveApi;