const system=require("../../system");
const ServiceBase=require("../sve.base");
class CustomerInfoService extends ServiceBase{
  constructor(){
     super(ServiceBase.getDaoName(CustomerInfoService));
     this.orderSve=system.getObject("service.orderSve");
     this.usercustomerDao=system.getObject("db.usercustomerDao");
     this.userCustomerDao=system.getObject("db.usercustomerDao");
     this.apiic=system.getObject("api.gsbicsearch");
  }

  async firstloading( userinfo, customerinfos ){
    var self=this;
    return this.db.transaction(async function (t){
      var lengths=0;
      var sources=[];
      var sourceucs=[];
      for(var i=0;i<customerinfos.length;i++)
      {
        customerinfos[i].companyname=customerinfos[i].companyname==null?"":customerinfos[i].companyname;
        customerinfos[i].companyname=await self.getConvertSemiangleStr(customerinfos[i].companyname);
        var customerinfo=await self.dao.findOne({customerType:'ent',name:customerinfos[i].companyname},t);
        if(!customerinfo){
           var cnum=await self.dao.customQuery("select max(id) from p_customer_info",null,t);
           if( isNaN(cnum) ){
             cnum=0;
           }
           cnum=Number(cnum)+1;
           var tNum=await self.orderSve.getUidStr(5,10);
          tNum=tNum+""+cnum;
          var obj={appKey:'wxda6eab8429128ccd',companyName:customerinfos[i].companyname};

          var companyinfo=await self.apiic.companynameonesearch(obj);
          var creditCode='';
          var scope='';
          var addr='';
          if( companyinfo.data!=null&&companyinfo.data.list.length>0 ){
            creditCode=companyinfo.data.list[0].creditCode;
            scope=companyinfo.data.list[0].scope;
            addr=companyinfo.data.list[0].businessAddress;
          }
          var source={
            customerType:'ent',
            customerTypeName:'企业',
            name:customerinfos[i].companyname,
            creditCode:creditCode,
            businessScope:scope,
            addr:addr,
            created_at:new Date(),
            updated_at:new Date(),
            customerNum:tNum,
          }
          sources.push(source);
         }
      }
      await self.dao.model.bulkCreate(sources,t);
      for(var i=0;i<customerinfos.length;i++)
      {
        var customerinfo=await self.dao.findOne({customerType:'ent',name:customerinfos[i].companyname},t);
        var ucinfo=await self.usercustomerDao.findOne({user_id:userinfo.id,customerInfo_id:customerinfo.id},t);
        if(!ucinfo){
          var sourceuc={
            app_id:userinfo.app_id,
            user_id:userinfo.id,
            customerInfo_id:customerinfo.id,
            onlyCode:userinfo.onlyCode,
            userName:userinfo.nickName,
            customerNum:customerinfo.customerNum,
            customerContact:customerinfos[i].cname,
            customerMobile:customerinfos[i].mobile,
            created_at:new Date(),
            updated_at:new Date(),
          }
          sourceucs.push(sourceuc);
          lengths+=1;
        }
      }
      await self.usercustomerDao.model.bulkCreate(sourceucs,t);
      return {code:0,msg:"导入成功",data:lengths}
    })
  }

  async getConvertSemiangleStr(str){
    var result = "";
    str=str.replace(/\s+/g,"");
    var len = str.length;
    for(var i=0;i<len;i++)
    {
        var cCode = str.charCodeAt(i);
        //全角与半角相差（除空格外）：65248（十进制）
        cCode = (cCode>=0xFF01 && cCode<=0xFF5E)?(cCode - 65248) : cCode;
        //处理空格
        cCode = (cCode==0x03000)?0x0020:cCode;
        result += String.fromCharCode(cCode);
    }
   return result;
  };
  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 createCustomer(customerObj,userCustomerObj){
    var o={};
    if(customerObj.customerType=="ent"){
      o={creditCode:customerObj.creditCode,name:customerObj.name}
    }else{
      o={identityCard:customerObj.identityCard}
    }
    var c = await this.dao.findOne(o);
    console.log(c);
    if(c){
      userCustomerObj["isFirst"]=0
    }else{
      userCustomerObj["isFirst"]=1
    }
    var that =this;
    return this.db.transaction(async function (t){
      var count = await that.dao.customQuery("select max(id) as maxid from p_customer_info",null,t);
      count=Number(count[0]["maxid"])+1;
      var customerNum = count+""+await that.getUidStr(8,10);
      console.log(customerNum);
      var customer={};
      if(c){
        customer=c;
      }else{
        customerObj["customerNum"]=customerNum;
        customer = await that.dao.create(customerObj,t);
      }
      userCustomerObj["customerInfo_id"]=customer.dataValues.id;
      userCustomerObj["customerNum"]=customer.dataValues.customerNum;

      console.log(userCustomerObj);
      var uco = {user_id:userCustomerObj.user_id,app_id:userCustomerObj.app_id,customerMobile:userCustomerObj.customerMobile,
        customerInfo_id:userCustomerObj.customerInfo_id
      };
      console.log(uco);
      var uc = await that.userCustomerDao.findOne(uco);
      if(!uc){
        var userCustomer=await that.userCustomerDao.create(userCustomerObj,t);
        return {code:1,data:{customer:customer,userCustomer:userCustomer}};
      }else{
        return {code:-3,msg:"保存失败，该客户已存在",data:{userCustomer:uc}};
      }

    })
  }

  async editCustomer(customerObj,userCustomerObj){

    var o={};
    if(customerObj.customerType=="ent"){
      o={creditCode:customerObj.creditCode,name:customerObj.name}
    }else{
      o={identityCard:customerObj.identityCard}
    }
    var c = await this.dao.findOne(o);
    console.log(c);
    if(c){
      userCustomerObj["isFirst"]=0
    }else{
      userCustomerObj["isFirst"]=1
    }
    var that =this;
    return this.db.transaction(async function (t){
      // var count = await that.dao.customQuery("select max(id) from p_customer_info",null,t);
      var count = await that.dao.customQuery("select max(id) as maxid from p_customer_info",null,t);
      count=Number(count[0]["maxid"])+1;
      var customerNum = count+""+await that.getUidStr(8,10);
      console.log(customerNum);
      var customer={};
      if(c){
        customer=c;
      }else{
        customerObj["customerNum"]=customerNum;
        customer = await that.dao.create(customerObj,t);
      }
      userCustomerObj["customerInfo_id"]=customer.dataValues.id;
      userCustomerObj["customerNum"]=customer.dataValues.customerNum;
      console.log(userCustomerObj);
      console.log("########################################");
      var userCustomer=await that.userCustomerDao.update(userCustomerObj,t);
      return {code:1,data:{customer:customer,userCustomer:userCustomer}};
      // var uco = {user_id:userCustomerObj.user_id,app_id:userCustomerObj.app_id,customerMobile:userCustomerObj.customerMobile,
      //   customerinfo_id:userCustomerObj.customerinfo_id
      // };
      // var uc = await that.userCustomerDao.findOne(uco);
      // if(!uc){
      //   var userCustomer=await that.userCustomerDao.update(userCustomerObj,t);
      //   return {code:1,data:{customer:customer,userCustomer:userCustomer}};
      // }else{
      //   return {code:-3,msg:"保存失败，该客户已存在"};
      // }

    })
  }

}
module.exports=CustomerInfoService;
