const system = require("../../system");
const ServiceBase = require("../sve.base");
const moment = require("moment");
const md5 = require("MD5");

class EcompanywxuserService extends ServiceBase {
   constructor() {
      super(ServiceBase.getDaoName(EcompanywxuserService));
      this.ecompanybusiDao = system.getObject("db.ecompanybusiDao");
      this.restClient = system.getObject("util.restClient");
   }

   async savewxuser(wxuser) {
      var busi = await this.ecompanybusiDao.findOne({ecompany_id: wxuser.ecompany_id});
      if(!busi) {
         return -101;
      }

      // var idNoUser = await this.dao.findOne({id_no: wxuser.id_no});

      var user = await this.dao.findOne({openId: wxuser.openId});
      if(user) {
         // if(idNoUser && idNoUser.id != user.id) {
         //    return -201;
         // }

         user.ecompany_id = wxuser.ecompany_id;
         user.id_no = wxuser.id_no;
         user.openId = wxuser.openId;
         user.id_name = wxuser.id_name;
         user.userCode = wxuser.userCode;
         user.isSend = false;
         await user.save();
      } else {
         // if(idNoUser) {
         //    return -201;
         // }
         user = await this.create(wxuser);
      }

      if(busi.postwxurl) {
         var param = {
            "appId": busi.appId,
            "idNo": user.id_no,
            "idName": user.id_name,
            "openId": user.openId,
            "nonceStr": await this.getUidStr(16),
            "userCode": user.userCode,
         }

         var signArr = [];
         signArr.push("appId=" + param.appId);
         signArr.push("idName=" + param.idName);
         signArr.push("idNo=" + param.idNo);
         signArr.push("nonceStr=" + param.nonceStr);
         signArr.push("openId=" + user.openId);
         signArr.push("userCode=" + user.userCode);
         signArr.push("key=" + busi.key);

         param.sign = md5(signArr.join("&")).toUpperCase();
         console.log(JSON.stringify(param));
         try {
            var rs = await this.restClient.execPost(param, busi.postwxurl);
            if (rs.stdout) {
               let rsData = JSON.parse(rs.stdout);
               if (rsData.code == "0") {
                  user.isSend = true;
                  user.save();
               }
            }
         } catch (error) {
            console.log(error);
         }
      }
      return 1;
   }

   async saveEcidUser(wxuser) {
      var busi = await this.ecompanybusiDao.findOne({etemplate_id: wxuser.etemplate_id});
      if(!busi) {
         return -101;
      }

      var user = await this.dao.findOne({openId: wxuser.openId});
      if(user) {
         user.ecompany_id = wxuser.ecompany_id;
         user.etemplate_id = wxuser.etemplate_id;
         user.openId = wxuser.openId;
         user.userCode = wxuser.userCode;

         user.id_no = "";
         user.id_name = "";
         user.isSend = false;
         await user.save();
      } else {
         user = await this.create(wxuser);
      }

      if(busi.postwxurl) {
         var param = {};
         var signArr = [];

         var param = {
            "appId": busi.appId,
            "openId": user.openId,
            "nonceStr": await this.getUidStr(16),
            "userCode": user.userCode,
         }
         signArr.push("appId=" + param.appId);
         signArr.push("nonceStr=" + param.nonceStr);
         signArr.push("openId=" + user.openId);
         signArr.push("userCode=" + user.userCode);
         signArr.push("key=" + busi.key);

         param.sign = md5(signArr.join("&")).toUpperCase();
         console.log(JSON.stringify(param));
         try {
            var rs = await this.restClient.execPost(param, busi.postwxurl);
            if (rs.stdout) {
               let rsData = JSON.parse(rs.stdout);
               if (rsData.code == "0") {
                  user.isSend = true;
                  user.save();
               }
            }
         } catch (error) {
            console.log(error);
         }
      }
      return 1;
   }

   async pushwxuser(wxuserid) {
      var user = await this.findById(wxuserid);
      if(!user) {
         return -1;
      }
      var busi = await this.ecompanybusiDao.findOne({ecompany_id: user.ecompany_id});
      if(!busi) {
         return -101;
      }
      var rs = {};

      // var idNoUser = await this.dao.findOne({id_no: wxuser.id_no});
      if(busi.postwxurl) {
         var param = {
            "appId": busi.appId,
            "idNo": user.id_no,
            "idName": user.id_name,
            "openId": user.openId,
            "nonceStr": "KklFn7qQtb39zwPL",
            "userCode": user.userCode,
         }

         var signArr = [];
         signArr.push("appId=" + param.appId);
         signArr.push("idName=" + param.idName);
         signArr.push("idNo=" + param.idNo);
         signArr.push("nonceStr=" + param.nonceStr);
         signArr.push("openId=" + user.openId);
         signArr.push("userCode=" + user.userCode);
         signArr.push("key=" + busi.key);

         param.sign = md5(signArr.join("&")).toUpperCase();
         console.log(JSON.stringify(param));
         try {
            rs = await this.restClient.execPost(param, busi.postwxurl);
            if (rs.stdout) {
               let rsData = JSON.parse(rs.stdout);
               if (rsData.code == "0") {
                  user.isSend = true;
                  user.save();
               }
            }
         } catch (error) {
            console.log(error);
            rs.error = error.message;
         }
      }
      return rs;
   }

   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('');
    }
}
module.exports = EcompanywxuserService;