var system=require("../../system")
const http=require("http")
var fs=require("fs");
const querystring = require('querystring');
var settings=require("../../../config/settings");
const AppletBase =require("../applet.base");
const cryptoJS = require("crypto-js");
const logCtl=system.getObject("web.oplogCtl");
class customerApplet extends AppletBase{
   constructor(){
     super();
     this.userSve=system.getObject("service.userSve");
     this.partnerinfoSve=system.getObject("service.partnerinfoSve");
     this.ossClient=system.getObject("util.ossClient");
     this.statisticalrateSve=system.getObject("service.statisticalrateSve");
     this.uploadCtl=system.getObject("web.uploadCtl");
     this.customerInfoSve=system.getObject("service.customerinfoSve");
     this.usercustomerSve=system.getObject("service.usercustomerSve");
   }
   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 customerDel(qobj,obj){
     console.log(obj);
     try {
       console.log("---------------------customerDel------------------------------");
       var openid = obj.openid;
       var cid = obj.id
       if(!openid){
         return {code:-1,msg:"删除失败",msg2:"openid参数有误"};
       }
       if(!cid){
         return {code:-101,msg:"删除失败",msg2:"id不能为空"};
       }
       console.log(openid);
       var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
       console.log(userInfo);
       if(userInfo){
         userInfo=JSON.parse(userInfo);
         console.log(userInfo);
         var customerObj={
           customerType:obj.customerType,name:obj.name,creditCode:obj.creditCode
         };
         var o={
           id:cid,onlyCode:userInfo.onlyCode
         };
         var result = this.usercustomerSve.deleteCustomer(o);
         return {code:1,data:result}
       }else{
         return {code:-2,msg:"删除失败"};
       }
     } catch (e) {
       console.log("openShop===========error");
       console.log(e);
       //日志记录
       logCtl.error({
          optitle:"客户删除异常,openid="+openid,
          op:"wxapplet/impl/customerApplet/customerDel",
          content:e.stack,
          clientIp:req.clientIp
        });
       return {
            code: -200,
            msg: "删除失败"
      };
     }
   }
   async customerSave(qobj,obj,req){
     console.log(obj);
     try {
       console.log("---------------------customerSave------------------------------");
       var openid = obj.openid;
       if(!openid){
         return {code:-1,msg:"保存失败",msg2:"openid参数有误"};
       }
       console.log(openid);
       var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
       console.log(userInfo);
       if(userInfo){
         userInfo=JSON.parse(userInfo);
         console.log(userInfo);
         // var count = await this.await this.dao.customQuery("select max(id) from p_customer_info",null,t);
         // count=Number(count)+1;
         // var customerNum = await this.getUidStr(8,10);
         // console.log(customerNum);
         var customerObj={
           customerType:obj.customerType,name:obj.name,creditCode:obj.creditCode
         };
         if(obj.customerType=="person"){
           customerObj={
             customerType:obj.customerType,name:obj.customerContact+obj.identityCard,identityCard:obj.identityCard
           };
         }
         var userCustomerObj={
           app_id:userInfo.app_id,user_id:userInfo.id,userName:userInfo.userName,onlyCode:userInfo.onlyCode,
           customerInfo_id:"",isFirst:"1",customerContact:obj.customerContact,customerMobile:obj.customerMobile
         }
         return this.customerInfoSve.createCustomer(customerObj,userCustomerObj);
       }else{
         return {code:-2,msg:"保存失败"};
       }
     } catch (e) {
       console.log("openShop===========error");
       console.log(e);
       //日志记录
       logCtl.error({
          optitle:"客户保存异常,openid="+openid,
          op:"wxapplet/impl/customerApplet/customerSave",
          content:e.stack,
          clientIp:req.clientIp
        });
       return {
            code: -200,
            msg: "保存失败"
      };
     }
   }
   async findOneById(obj){
     try {
       var openid = obj.openid;
       console.log(openid);
       if(!openid){
         return {code:-1,msg:"保存失败",msg2:"openid参数有误"};
       }
       var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
       console.log(userInfo);
       if(userInfo){
         userInfo=JSON.parse(userInfo);
         console.log(userInfo);
         var o={};
          var date = new Date();
          var time = date.toLocaleString();
          var sql="SELECT usercustomer.*, customerinfo.customerTypeName,"+
                  " customerinfo.name ,customerinfo.identityCard , customerinfo.creditCode,customerinfo.customerType"+
                  " FROM b_user_customer AS usercustomer"+
                  " LEFT OUTER JOIN p_customer_info AS customerinfo ON usercustomer.customerInfo_id = customerinfo.id"+
                  " AND (customerinfo.deleted_at > '"+time+"' OR customerinfo.deleted_at IS NULL )"+
                  " WHERE (usercustomer.deleted_at > '"+time+"' OR usercustomer.deleted_at IS NULL)"+
                  " AND usercustomer.id = "+obj.id+
                  " limit 1";
          var result= await this.usercustomerSve.dao.customQuery(sql);
          return {code:1,data:result}
       }else{
         return {
              code: -2,
              msg: "用户不存在"
        };
       }
     } catch (e) {
       console.log(e);
       //日志记录
       logCtl.error({
          optitle:"获取客户详情异常,openid="+openid,
          op:"wxapplet/impl/customerApplet/findOneById",
          content:e.stack,
          clientIp:""
        });
       return {
            code: -200,
            msg: "操作失败"
      };
     }

   }
   async findOneByCustomerNum(obj){
     try {
       var openid = obj.openid;
       console.log(openid);
       if(!openid){
         return {code:-1,msg:"保存失败",msg2:"openid参数有误"};
       }
       var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
       console.log(userInfo);
       if(userInfo){
         userInfo=JSON.parse(userInfo);
         console.log(userInfo);
         var o={};
          var date = new Date();
          var time = date.toLocaleString();
          var sql="SELECT usercustomer.*, customerinfo.customerTypeName,"+
                  " customerinfo.name ,customerinfo.identityCard , customerinfo.creditCode,customerinfo.customerType"+
                  " FROM b_user_customer AS usercustomer"+
                  " LEFT OUTER JOIN p_customer_info AS customerinfo ON usercustomer.customerInfo_id = customerinfo.id"+
                  " AND (customerinfo.deleted_at > '"+time+"' OR customerinfo.deleted_at IS NULL )"+
                  " WHERE (usercustomer.deleted_at > '"+time+"' OR usercustomer.deleted_at IS NULL)"+
                  " AND usercustomer.customerNum = "+obj.customerNum+
                  " limit 1";
          var result= await this.usercustomerSve.dao.customQuery(sql);
          return {code:1,data:result}
       }else{
         return {
              code: -2,
              msg: "用户不存在"
        };
       }
     } catch (e) {
       console.log(e);
       //日志记录
       logCtl.error({
          optitle:"获取客户详情异常,openid="+openid,
          op:"wxapplet/impl/customerApplet/findOneById",
          content:e.stack,
          clientIp:""
        });
       return {
            code: -200,
            msg: "操作失败"
      };
     }

   }
   async getCustomerList(obj){
     try {
       var openid = obj.openid;
       console.log(openid);
       if(!openid){
         return {code:-1,msg:"保存失败",msg2:"openid参数有误"};
       }
       var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
       console.log(userInfo);
       if(userInfo){
         userInfo=JSON.parse(userInfo);
         console.log(userInfo);
         var o={};

        if(obj.searchValue){
          var date = new Date();
          var time = date.toLocaleString();
          var sql="SELECT usercustomer.*,customerinfo.customerTypeName,"+
                  " customerinfo.name ,customerinfo.identityCard , customerinfo.creditCode,customerinfo.customerType"+
                  " FROM b_user_customer AS usercustomer"+
                  " LEFT OUTER JOIN p_customer_info AS customerinfo ON usercustomer.customerInfo_id = customerinfo.id"+
                  " AND (customerinfo.deleted_at > '"+time+"' OR customerinfo.deleted_at IS NULL )"+
                  " WHERE (usercustomer.deleted_at > '"+time+"' OR usercustomer.deleted_at IS NULL)"+
                  " AND (customerinfo.name LIKE '%"+obj.searchValue+"%' OR usercustomer.customerNum LIKE '%"+obj.searchValue+"%' OR usercustomer.customerMobile LIKE '%"+obj.searchValue+"%' OR usercustomer.customerContact LIKE '%"+obj.searchValue+"%')"+
                  " AND usercustomer.user_id = "+userInfo.id+" AND usercustomer.app_id = "+userInfo.app_id+" AND usercustomer.onlyCode = '"+userInfo.onlyCode+
                  "' ORDER BY usercustomer.created_at DESC";
          if(obj.ps && obj.cp){//cp 1 开始
            sql = sql+" limit "+Number(obj.cp-1)*Number(obj.ps)+","+Number(obj.ps);
          }
          var list= await this.usercustomerSve.dao.customQuery(sql);
          return {code:1,data:list}
        }else{
          var date = new Date();
          var time = date.toLocaleString();
          var sql="SELECT usercustomer.*, customerinfo.customerTypeName,"+
                  " customerinfo.name ,customerinfo.identityCard , customerinfo.creditCode,customerinfo.customerType"+
                  " FROM b_user_customer AS usercustomer"+
                  " LEFT OUTER JOIN p_customer_info AS customerinfo ON usercustomer.customerInfo_id = customerinfo.id"+
                  " AND (customerinfo.deleted_at > '"+time+"' OR customerinfo.deleted_at IS NULL )"+
                  " WHERE (usercustomer.deleted_at > '"+time+"' OR usercustomer.deleted_at IS NULL)"+
                  " AND usercustomer.user_id = "+userInfo.id+" AND usercustomer.app_id = "+userInfo.app_id+" AND usercustomer.onlyCode = '"+userInfo.onlyCode+
                  "' ORDER BY usercustomer.created_at DESC";
                  if(obj.ps && obj.cp){//cp 1 开始
                    sql = sql+" limit "+Number(obj.cp-1)*Number(obj.ps)+","+Number(obj.ps);
                  }
                  console.log(sql);
          var list= await this.usercustomerSve.dao.customQuery(sql);
          console.log(list);
          return {code:1,data:list}
        }
       }else{
         return {
              code: -2,
              msg: "用户不存在"
        };
       }
     } catch (e) {
       console.log(e);
       //日志记录
       logCtl.error({
          optitle:"获取客户列表异常,openid="+openid,
          op:"wxapplet/impl/customerApplet/getCustomerList",
          content:e.stack,
          clientIp:""
        });
       return {
            code: -200,
            msg: "操作失败"
      };
     }

   }

   async customerEdit(qobj,obj,req){
     console.log(obj);
     try {
       console.log("---------------------customerEdit------------------------------");
       var openid = obj.openid;
       if(!openid){
         return {code:-1,msg:"保存失败",msg2:"openid参数有误"};
       }
       console.log(openid);
       var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
       console.log(userInfo);
       if(userInfo){
         userInfo=JSON.parse(userInfo);
         // var customerNum = await this.getUidStr(8,10);
         // console.log(customerNum);
         var customerObj={
           customerType:obj.customerType,name:obj.name,creditCode:obj.creditCode
         };
         if(obj.customerType=="person"){
           customerObj={
             customerType:obj.customerType,name:obj.customerContact+obj.identityCard,identityCard:obj.identityCard
           };
         }
         var userCustomerObj={
           id:obj.id,
           customerInfo_id:"",customerContact:obj.customerContact,customerMobile:obj.customerMobile
         }
         return this.customerInfoSve.editCustomer(customerObj,userCustomerObj);
       }else{
         return {code:-2,msg:"保存失败"};
       }
     } catch (e) {
       console.log("openShop===========error");
       console.log(e);
       //日志记录
       logCtl.error({
          optitle:"客户修改异常,openid="+openid,
          op:"wxapplet/impl/customerApplet/customerEdit",
          content:e.stack,
          clientIp:req.clientIp
        });
       return {
            code: -200,
            msg: "保存失败"
      };
     }
   }
   async putCustomerNum(qobj,obj){
     try {
       console.log("---------------------putCustomerNum------------------------------");
       var openid = obj.openid;
       var customerNum=obj.customerNum;
       console.log(obj);
       if(!openid){
         return {code:-1,msg:"保存失败",msg2:"openid参数有误"};
       }
       console.log(openid);
       var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
       console.log(userInfo);
       if(userInfo && customerNum){
         var userInfoObj=JSON.parse(userInfo);
         if(customerNum && customerNum!=userInfoObj.customerNum){
           var o={id:userInfoObj.id,customerNum:customerNum}
           console.log(o);
           await this.userSve.dao.model.update(o,{where:{id:o.id}});
           await this.cacheManager["AppletUserinfoCache"].del(openid);
           var r = await  this.cacheManager["AppletUserinfoCache"].get(openid);
           r=JSON.parse(r);
           return {code:1,data:r}
         }else{
           return {code:1,data:userInfoObj};
         }
       }else{
         return {code:-2,msg:"保存失败"};
       }
     } catch (e) {
       console.log(e);
       //日志记录
       logCtl.error({
          optitle:"用户客户号异常,openid="+openid,
          op:"wxapplet/impl/customerApplet/putCustomerNum",
          content:e.stack,
          clientIp:req.clientIp
        });
       return {
            code: -200,
            msg: "保存失败"
      };
     }
   }
}
module.exports=customerApplet;
// var task=new customerApplet();
// var obj ={"openid":"ovPx35GktY-8pn3GmpIYfcbmqZQk","id":"5"};
// task.findOneById(obj).then(function(result){
//   console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
//   console.log((result));
// }).catch(function(e){
//   console.log(e);
// });
