var system=require("../../system")
const http=require("http")
const querystring = require('querystring');
var settings=require("../../../config/settings");
const CtlBase = require("../ctl.base");
const logCtl=system.getObject("web.oplogCtl");
class UserAddrCtl extends CtlBase{
   constructor(){
     super(CtlBase.getServiceName(UserAddrCtl));
   }
   //获取当前登录人所有地址
   async fetchAllAddress(pobj,obj,req){
    var result=await this.service.fetchAllAddress(
      req.companyid ,req.session.user.id,
      );
     return system.getResult2(result);
   }
    //新增地址
    async createAddress(pobj,gobj,req){
    var result = {
      code: 1,
      msg: "ok",
      data:{}
    };
    try {
      // var count=await this.service.findCount({ 
      //   where: {company_id: req.companyid ,createuser_id: req.session.user.id} 
      // });
      var lists=await this.service.fetchAllAddress(
        req.companyid ,req.session.user.id,
        );
      if (lists.length> 19) {
        result.code = -100; 
        result.msg = "用户地址已达上限20个！";
        return result;
      }
      for (var i=0;i<lists.length;i++){
        if(lists[i].isDefault == "1"){
          result.code = -100; 
          result.msg = "用户默认地址只能有一个！";
          return result;
        }
      }
      super.create(pobj,gobj,req);
      result.data = gobj
      return result;
    } catch (e) {
      //日志记录
      logCtl.error({
      optitle: "新增地址出错---error",
      op: "/igirl-web/app/base/controller/impl/useraddrCtl.js/createAddress",
      content: e.stack,
      clientIp: req.clientIp
    });
    }
  }
  //修改地址
  async updateAddress(pobj,gobj,req){
    var result = {
      code: 1,
      msg: "ok",
      data:{}
    };
    try { 
        var user = req.session.user;
        await this.service.updateByWhere({
        name: gobj.nick_name ,mobile: gobj.nick_mobile,address: gobj.nick_address,email: gobj.nick_email,isDefault: gobj.nick_isDefault}, {
        where:{createuser_id: user.id ,id: gobj.addressid} 
      });
      result.data = gobj;
      return result;
    } catch (e) {
      //日志记录
      logCtl.error({
      optitle: "修改地址出错---error",
      op: "/igirl-web/app/base/controller/impl/useraddrCtl.js/updateAddress",
      content: e.stack,
      clientIp: req.clientIp
    });
    }
  }
}
module.exports=UserAddrCtl ;
