const system=require("../../system");
const ServiceBase=require("../sve.base");
class PageStatisticsService extends ServiceBase{
  constructor(){
     super(ServiceBase.getDaoName(PageStatisticsService));
     this.shopSve=system.getObject("service.shopSve");
     this.servicetypeDao=system.getObject("db.servicetypeDao");
     this.userDao = system.getObject("db.userDao");
  }
  /*增加页面统计tUserInfo用户信息
  （
    附加参数
    isCheckExist 验证是否存在，1不验证,2验证
    target_only_code目标唯一码（用户唯一码或店铺唯一码）
    item_code服务项目编码
    client_ip
    statistics_code统计编码
    statistics_name统计编码名称
   ）*/
  async add(tUserInfo,result,isCheckExist){
    var tmpItem=await this.servicetypeDao.getItemByCode(tUserInfo.statistics_code);
    if(tmpItem==null){
      result.code=-201;
      result.message="tj_code统计编码有误";
      return result;
    }
    //验证要添加的数据是否存在---验证是否存在，1不验证,2验证
    if(isCheckExist && isCheckExist==2){
      var tCount=await this.findCount({where:{onlyCode:tUserInfo.onlyCode,itemCode:tUserInfo.item_code,statisticsCode:tUserInfo.statistics_code}});
      if(tCount>0){
        result.code=-202;
        result.message="请勿重复操作";
        return result;
      }
    }
    var addParams={
        app_id:tUserInfo.app_id,
        user_id:tUserInfo.id,
        userName:tUserInfo.userName,
        onlyCode:tUserInfo.onlyCode,
        mobile:tUserInfo.mobile,
        //以下为新增项目
        targetOnlyCode:tUserInfo.target_only_code,//目标唯一码（用户唯一码或店铺唯一码）
        itemCode:tUserInfo.item_code,
        clientIp:tUserInfo.client_ip,
        statisticsCode:tUserInfo.statistics_code,
        statisticsCodeName:tmpItem.name
    };
    this.dao.create(addParams);
    return result;
  }
  //删除某个用户统计编码对应的 itemCode
  async delUserStatistics(onlycode,item_code,statistics_code){
     this.delete({onlyCode:onlycode,itemCode:item_code,statisticsCode:statistics_code});
  }


  async getYjsRankList(tjCode,topNum){
    var result={
       code: 1,
       message: "success",
       data: []
    };
    if(tjCode==null||tjCode==""||tjCode=="undefined"){
      result.code=-101;
      result.message="tjcode参数有误";
      return result;
    }
    if(topNum==null||topNum==""||topNum=="undefined"){
      topNum=10;
    }
    if(topNum>100){
      topNum=100;
    }
    var sql="SELECT userName,nickName,onlyCode,pvCount,headUrl FROM p_account AS a RIGHT JOIN"+
             " (SELECT onlyCode,COUNT(id) AS pvCount FROM `h_page_statistics`"+
              " WHERE statisticsCode=:statisticsCode GROUP BY onlyCode ORDER BY pvCount DESC LIMIT 0,:tmpTopNum ) AS b"+
              " ON a.`unionId`=b.onlyCode ORDER BY pvCount DESC";
    var paras={statisticsCode:tjCode,tmpTopNum:topNum};
    var list= await this.dao.customQuery(sql,paras);
    if(list==null&&list.length==0){
      result.message="暂无排名数据";
      return result;
    }
    var self=this;
    for (var i = 0; i < list.length; i++) {
      var item=list[i];
      if(item!=null){
        //返回的服务项目列表
        var rank_item={
               rank:{
                  name:item.nickName,
                  head_url:item.headUrl,
                  pv_count:item.pvCount
             }
        };
        result.data.push(rank_item);
      }
    }
    return result;
  }

  async getRankList(tjCode,topNum){
    var result={
       code: 1,
       message: "success",
       data: []
    };
    if(tjCode==null||tjCode==""||tjCode=="undefined"){
      result.code=-101;
      result.message="tjcode参数有误";
      return result;
    }
    if(topNum==null||topNum==""||topNum=="undefined"){
      topNum=10;
    }
    if(topNum>100){
      topNum=100;
    }
    // var sql="SELECT targetOnlyCode,COUNT(DISTINCT(onlyCode)) AS pvCount FROM `h_page_statistics` WHERE targetOnlyCode IS NOT NULL AND statisticsCode=:statisticsCode GROUP BY targetOnlyCode ORDER BY pvCount DESC LIMIT 0,:tmpTopNum";
    var sql="SELECT userName,nickName,targetOnlyCode,pvCount,headUrl FROM p_account AS a RIGHT JOIN"+
            " (SELECT targetOnlyCode,COUNT(DISTINCT(onlyCode)) AS pvCount FROM `h_page_statistics`"+
            "  WHERE targetOnlyCode IS NOT NULL AND statisticsCode=:statisticsCode GROUP BY targetOnlyCode ORDER BY pvCount DESC LIMIT 0,:tmpTopNum ) as b"+
            " ON a.`unionId`=b.targetOnlyCode ORDER BY pvCount DESC";
    var paras={statisticsCode:tjCode,tmpTopNum:topNum};
    var list= await this.dao.customQuery(sql,paras);
    if(list==null&&list.length==0){
      result.message="暂无排名数据";
      return result;
    }
    var self=this;
    for (var i = 0; i < list.length; i++) {
      var item=list[i];
      if(item!=null){
        var shopItem= await self.shopSve.getShopItem(item.targetOnlyCode);
        //返回的服务项目列表
        var rank_item={
               rank:{
                  name:shopItem==null?"":shopItem.name,
                  shop_num:shopItem==null?"":shopItem.shopNum,
                  head_url:item.headUrl,
                  user_mobile:shopItem==null?"":shopItem.userMobile,
                  pv_count:item.pvCount
             }
        };
        result.data.push(rank_item);
      }
    }
    return result;
  }

  async userCollectList(userId, pageIndex, pageSize) {
    var whereObj={user_id : userId, statisticsCode: "mryz_sellsc"};

    var attributesObj=["id","itemCode"];
    var result = await super.getPageList(Number(pageIndex), Number(pageSize), whereObj, [["id", 'DESC']], attributesObj);

    if(!result || !result.rows || result.rows.length == 0) {
      return result;
    }

    var onlyCodes = [];
    for(var r of result.rows) {
      onlyCodes.push("'" + r.itemCode + "'");
    }

    var columns = "id, opCode, mobilePic, name, registerDay, registerAddr, registerCapital, onlyCode, guidePrice ";
    var sql = "SELECT " + columns + " FROM yz_business_license WHERE opCode IN (" + onlyCodes.join(",") + ")";
    var blList = await this.dao.customQuery(sql);
    var blMap = [];
    var rows = [];
    var codeList = [];
    for(var bl of blList) {
      blMap[bl.opCode] = bl;
      codeList.push("'" + bl.onlyCode + "'");
    }
    var userSql = "SELECT onlyCode, id from p_user WHERE onlyCode IN (" + codeList.join(",") + ") GROUP by onlyCode ";
    var userList = await this.dao.customQuery(userSql);
    var userMap = [];
    if(userList && userList) {
      for(var u of userList) {
        userMap[u.onlyCode] = u.id;
      }
    }

    for(var r of result.rows) {
      var bl = blMap[r.itemCode];
      if(bl) {
        bl.collectid = r.id;
        bl.uid = userMap[bl.onlyCode];
        rows.push(bl);
      }
    }

    result.rows = rows;
    return result;
  }

  async delUserCollect(userId, collectid) {
    var collect = await this.findById(collectid);
    if(!collect) {
      return 0;
    }
    console.log(userId, collect.user_id , collect.statisticsCode,"--------------------------------------------------------- ");
    if(userId != collect.user_id || "mryz_sellsc" != collect.statisticsCode) {
      return 0;
    }

    await this.dao.delete({id:collectid});
    return 1;
  }

  async historyVisits(params, pageIndex, pageSize) {
    var userId = params.userId;
    var opCode = params.opCode;
    var statisticsCode = params.type == 1 ? "mryz_sellsc" : "mryz_sellfw";

    var user = await this.userDao.findById(userId);
    if(!user) {
      return {count:0, rows:[]};
    }
    // 查所有执照
    var sql = "SELECT opCode FROM yz_business_license WHERE onlyCode = '" + user.onlyCode + "' ";
    if(opCode) {
      sql = sql + " AND opCode = '" + opCode + "' ";
    }
    var blList = await this.dao.customQuery(sql);
    if(!blList || blList.length == 0) {
      return {count:0, rows:[]};
    }

    var blCodes = [];
    for(var bl of blList) {
      blCodes.push(bl.opCode);
    }

    var whereObj={statisticsCode: statisticsCode, itemCode:{[this.db.Op.in]:blCodes}};
    var attributesObj=["user_id", "id", "itemCode", "created_at"];
    var result = await super.getPageList(Number(pageIndex), Number(pageSize), whereObj, [["id", 'DESC']], attributesObj);

    if(!result || !result.rows || result.rows.length == 0) {
      return result;
    }

    var userIds = [];
    var itemCodes = [];
    for(var r of result.rows) {
      userIds.push(r.user_id);
      itemCodes.push("'" + r.itemCode + "'")
    }

    // 查用户
    var userSql = "SELECT id, openId, nickName, headUrl FROM p_user WHERE id IN (" + userIds.join(",") + ")";
    var userList = await this.dao.customQuery(userSql);
    console.log(userList, "----------------------------- userList --------------------- ");

    var userMap = [];
    if(userList) {
      for(var u of userList) {
        userMap["id" + u.id] = u;
      }
    }

    // 查执照
    var blColumns = "id, opCode, mobilePic, name, registerDay, registerAddr, registerCapital, onlyCode, guidePrice, serviceTypeOneId, serviceTypeTwoId ";
    var blSql = "SELECT " + blColumns + " FROM yz_business_license WHERE opCode IN (" + itemCodes.join(",") + ")";
    var lincenseList = await this.dao.customQuery(blSql);
    await this.setServiceTypeName(lincenseList);
    var blMap = [];
    if(lincenseList) {
      for(var bl of lincenseList) {
        blMap[bl.opCode] = bl;
      }
    }

    for(var r of result.rows) {
      r.user = userMap["id" + r.user_id];
      r.businessLicense = blMap[r.itemCode];
    }

    return result;
  }

  async setServiceTypeName(rows) {
    var serviceTypeIds = [];
    for(var r of rows) {
      serviceTypeIds.push(r.serviceTypeOneId);
      serviceTypeIds.push(r.serviceTypeTwoId);
    }

    var sql = "SELECT id, name FROM `p_service_type` WHERE id IN (" + serviceTypeIds.join(",") + ") ";
    var typeList = await this.dao.customQuery(sql);

    if(typeList && typeList.length > 0) {
      var typeMap = [];
      for(var t of typeList) {
        typeMap["id" + t.id] = t.name;
      }

      for(var r of rows) {
        r.serviceTypeOneName = typeMap["id" + r.serviceTypeOneId] || "";
        r.serviceTypeTwoName = typeMap["id" + r.serviceTypeTwoId] || "";
      }
    }
  }
}
module.exports=PageStatisticsService;
