const system=require("../../system");
const ServiceBase=require("../sve.base");
class BusinessLicenseService extends ServiceBase{
  constructor(){
     super(ServiceBase.getDaoName(BusinessLicenseService));
     this.pagestatisticsDao=system.getObject("db.pagestatisticsDao");
     this.userDao=system.getObject("db.userDao");
  }
  async addCompany(params,userInfo,channelInfo){
    var opCode = params.opCode || "";
    var bl = null;
    var id = 0;
    if(opCode) {
      bl = await super.findOne({opCode:opCode});
      bl.serviceTypeOneId = params.serviceTypeOneId || 0;
      bl.serviceTypeTwoId = params.serviceTypeTwoId || 0;
      bl.name = params.name  || "";
      bl.registerProvince = params.registerProvince || "";
      bl.registerCity = params.registerCity || "";
      bl.registerArea = params.registerArea || "";
      bl.registerAddr = params.registerAddr || "";
      bl.registerDay = params.registerDay;
      bl.businessEndDay = params.businessEndDay;
      bl.registerCapital = params.registerCapital || 0;
      bl.serviceScope = params.serviceScope || "";
      bl.companyProperty = params.companyProperty || '1';
      bl.isBankAccount = params.isBankAccount || 0;
      bl.isNormalOperation = params.isNormalOperation || 0;
      bl.isLocalTax = params.isLocalTax || 0;
      bl.isFiscal = params.isFiscal || 0;
      bl.isKeepAccountsTax = params.isKeepAccountsTax || 0;
      bl.invoiceVersion = params.invoiceVersion || "1";
      bl.isAddrCharge = params.isAddrCharge || 0;
      bl.changeService = params.changeService || 0;
      bl.guidePrice = params.guidePrice || 0;
      bl.intro = params.intro || "";
      bl.legalPerson = params.legalPerson || "";
      bl.guidePriceScope = params.guidePriceScope || 0;
      bl.isPubed=1;
      var r = await bl.save();

      // 删除图片
      var delRoleSql = "DELETE FROM `yz_business_license_img` WHERE type = 0 AND licenseId = " + bl.id;
      await this.dao.customExecAddOrPutSql(delRoleSql);

      id = bl.id;
    } else {
      var tmpuid=await this.getUidInfo(5,36);
      opCode=tmpuid+""+Date.now();
      params.channel_id=channelInfo.id;
      params.channelCode=channelInfo.channelCode;
      params.isPubed=1;
      params.opCode=opCode;
      params.onlyCode=userInfo.onlyCode;
      params.companyOnlyCode=userInfo.referrerOnlyCode||userInfo.onlyCode;
      params.hotline=userInfo.mobile;
      var obj = await this.create(params);

      id = obj.id;
    }

    if(params.businessLicenseImgs && params.businessLicenseImgs.length > 0) {
      var sql="insert into `yz_business_license_img` (`created_at`,`updated_at`,`type`,`licenseId`,`url`) values ";
      var now = new Date();
      var values = [];
      var replacements = [];
      for(var bli of params.businessLicenseImgs) {
        values.push("(?,?,?,?,?)");
        replacements.push(now);
        replacements.push(now);
        replacements.push(0);
        replacements.push(id);
        replacements.push(bli.url || "");
      }
      if(values.length > 0) {
        sql = sql + values.join(",");
        var params={replacements: replacements};
        await this.dao.customExecAddOrPutSql(sql, params);
      }
    }

    return {
         code: 1,
         message: "success",
         data: {op_code:opCode}
      };
  }

  // 获取公司下全部易照数量
  async countLicenseByCompany(userId) {
    var result = {all : 0};
    var user = await this.userDao.findById(userId);
    if(!user || !user.companyOnlyCode) {
      return result;
    }
    result.all = await super.findCount({where : {companyOnlyCode : user.companyOnlyCode}});
    return result;
  }

  // 获取全部易照数量
  async countAllLicense(userId) {
    var result = {all : 0};
    result.all = await super.findCount();
    return result;
  }


  //获取易照列表
  /*
    参数：userOnlyCode 当前登录者的onlyCode、type请求类型（1页面展示、2后台展示）
  */
  async getList(params, opUser){
    var userOnlyCode = opUser.onlyCode;
    // 查当前用户权限
    var roleSql = "SELECT t1.code FROM `p_role` t1 INNER JOIN p_userrole t2 ON t1.`id` = t2.`role_id` WHERE t2.`user_id` = :userId AND t1.id >= 12 AND t1.id <= 16 ";
    var roleList = await this.dao.customQuery(roleSql, {userId:opUser.id});
    
    var hasRole = roleList && roleList.length > 0;

    //请求类型：1页面展示、2后台展示
    var type=params.type||1;
    //渠道码
    var channel_code=params.channel_code||"";
    //公司唯一码
    var company_only_code=params.company_only_code||"";
    //是否推荐
    var is_recommend=params.is_recommend||"";
    //一级类id
    var service_type_one_id=params.service_type_one_id||"";
    //二级类id
    var service_type_two_id=params.service_type_two_id||"";
    // 上下架状态 1全部 2在售 3下架
    var isPubed = params.is_pubed || 1;

    var currentPage =  Number(params.current_page||1);
    var pageSize= Number(params.page_size||10);
    if(currentPage<1){
      currentPage=1;
    }
    if(pageSize>20){
      pageSize=20;
    }
    var whereObj={};
    if(channel_code && channel_code!="undefined"){
      whereObj.channelCode=channel_code;
    }
    if(company_only_code && company_only_code!="undefined"){
      whereObj.companyOnlyCode=company_only_code;
    }
    if(is_recommend && is_recommend!="undefined"){
      whereObj.isRecommend=is_recommend;
    }
    console.log(service_type_one_id, "--------------------------------------------- ");
    if(service_type_one_id && service_type_one_id!="undefined"){
      whereObj.serviceTypeOneId=Number(service_type_one_id);
    }

    if(service_type_two_id && service_type_two_id!="undefined"){
      whereObj.serviceTypeTwoId=Number(service_type_two_id);
    }
    //1页面展示、2后台展示
    if(type==2){
      whereObj.onlyCode=userOnlyCode;
    }
    if(isPubed > 1) {
      whereObj.isPubed = isPubed == 2 ? true : false;
    }
    //搜索的条件
    //城市
    var city=params.city||"";
    if(city && city!="undefined"){
      whereObj.registerCity=city;
    }
    //赛选
    //售价最小
    var guide_price_min=params.guide_price_min||"";
    //售价最大
    var guide_price_max=params.guide_price_max||"";
    //持有人
    var published_sources=params.published_sources||"";
    //注册资本最小
    var register_capital_min=params.register_capital_min||"";
    //注册资本最大
    var register_capital_max=params.register_capital_max||"";
    //注册时间
    var register_day=params.register_day||"";

    if(guide_price_min && guide_price_min != "undefined" && guide_price_max && guide_price_max != "undefined"){
      whereObj.guidePrice={[this.db.Op.between]:[guide_price_min,guide_price_max]};
    }
    if(published_sources && published_sources!="undefined"){
      whereObj.publishedSources=published_sources;
    }
    if(register_capital_min && register_capital_min != "undefined" && register_capital_max && register_capital_max != "undefined"){
      whereObj.registerCapital={[this.db.Op.between]:[register_capital_min,register_capital_max]};
    }
    if(register_day && register_day!="undefined"){
      // whereObj.registerDay={[this.db.Op.gte]:register_day};
      whereObj.registerDay={[this.db.Op.between]:[register_day + "-01-01 00:00:00",register_day + "-12-31 23:59:59"]};
    }

    //排序
    var sort=params.sort||"";
    var orderbyObj=[["created_at", 'desc']];
    if(sort && sort != "undefined"){
      if(sort==3){
        orderbyObj=[["guidePrice", 'asc']];
      }
      else if (sort==4) {
        orderbyObj=[["guidePrice", 'desc']];
      }
    }
    var attributesObj=["id", "serviceTypeOneId","serviceTypeTwoId", "opCode","name","registerDay","registerProvince","registerCity","registerArea","registerCapital",
    "guidePrice", "guidePriceScope","companyOnlyCode","notes", "onlyCode", "isRecommend"];
    var list=await this.getPageList(currentPage,pageSize,whereObj,orderbyObj,attributesObj);
    var result= {
       code: 1,
       message: "success",
       data: list
    };
    if(list && list.rows.length>0){
      await this.setUid(list.rows);
      await this.setListServiceTypeName(list.rows);
      result.data.rows=await this.getPagestatistics(userOnlyCode,list,type);
      for(var row of result.data.rows){
        if(!hasRole && row.guidePriceScope == 1 && userOnlyCode != row.onlyCode) {
          row.guidePrice = -1;
        }
      }
    }
    return result;
  }
  async setUid(list) {
    var codeList = [];
    for(var o of list) {
      codeList.push("'" + o.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;
      }
    }
    console.log(userMap, "------------------------------------------------------- userMap");
    for(var o of list) {
      o.uid = userMap[o.onlyCode];
    }
  }

  //易照详情
  async getDetailByOpCode(opUser, op_code,type){
    var userOnlyCode = opUser.onlyCode;

    // 查当前用户权限
    var roleSql = "SELECT t1.code FROM `p_role` t1 INNER JOIN p_userrole t2 ON t1.`id` = t2.`role_id` WHERE t2.`user_id` = :userId AND t1.id >= 12 AND t1.id <= 16 ";
    var roleList = await this.dao.customQuery(roleSql, {userId:opUser.id});
    var hasRole = roleList && roleList.length > 0;
    

    //请求类型：1页面展示、2后台展示
      var tmpType=type||1;
      var item=await this.dao.model.findOne({where:{opCode:op_code},
                                             attributes:["id", "serviceTypeOneId","serviceTypeTwoId","code","name","serviceScope","registerProvince","registerCity","registerArea","isPubed",
                                                         "registerAddr","registerDay","businessEndDay","registerCapital","guidePrice", "guidePriceScope","companyPropertyName","companyProperty","intro",
                                                         "isBankAccount","isNormalOperation","isLocalTax","isFiscal","isKeepAccountsTax","invoiceVersion","invoiceVersionName",
                                                         "isAddrCharge","changeServiceName","changeService","publishedSourcesName","publishedSources","companyOnlyCode", "onlyCode"],raw:true});
      if(item!=null){
        item.visit=0;
        item.collect=0;
        if(tmpType==1){
          //获取用户收藏的信息
          var tmpList= await this.pagestatisticsDao.getUserAllStatistics(userOnlyCode,[op_code],"mryz_sellsc");
          if(tmpList && tmpList.length>0){
            item.collect=1;
          }
          //获取用户访问的信息
          var tmpCount= await this.pagestatisticsDao.getUserAllStatisticsCount(op_code,"mryz_sellfw");
          item.visit=tmpCount;
        }

        var serviceTypeIds = [item.serviceTypeOneId, item.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) {
          for(var t of typeList) {
            if(t.id == item.serviceTypeOneId) {
              item.serviceTypeOneName = t.name;
            } else if(t.id == item.serviceTypeTwoId) {
              item.serviceTypeTwoName = t.name;
            } else {}
          }
        }
        await this.setUid([item]);
        var sql="insert into `yz_business_license_img` (`created_at`,`updated_at`,`type`,`licenseId`,`url`) values ";

        var imgSql = "SELECT url FROM yz_business_license_img WHERE type = 0 AND licenseId = :licenseId ";
        var imgList = await this.dao.customQuery(imgSql, {licenseId:item.id});

        item.businessLicenseImgs = imgList;

        if(!hasRole && item.guidePriceScope == 1 && userOnlyCode != item.onlyCode) {
          item.guidePrice = -1;
        }
      }

      return {
           code: 1,
           message: "success",
           data: item
        };
  }

  async getDetailById(id) {
    var item=await this.dao.model.findOne({where:{id:id},
                                           attributes:["id", "serviceTypeOneId","serviceTypeTwoId","name",
                                           "registerProvince","registerCity","registerArea", "registerAddr","registerDay", "guidePrice"],raw:true});
    await this.setItemServiceTypeName(item);
    return {
         code: 1,
         message: "success",
         data: item
      };
  }

  async setItemServiceTypeName (item) {
    if(!item) return;

    var serviceTypeIds = [item.serviceTypeOneId, item.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) {
      for(var t of typeList) {
        if(t.id == item.serviceTypeOneId) {
          item.serviceTypeOneName = t.name;
        } else if(t.id == item.serviceTypeTwoId) {
          item.serviceTypeTwoName = t.name;
        } else {}
      }
    }
  }

  async setListServiceTypeName (itemList) {
    if(!itemList || itemList.length == 0) return;

    var serviceTypeIds = [];
    for(var item of itemList) {
      serviceTypeIds.push(item.serviceTypeOneId);
      serviceTypeIds.push(item.serviceTypeTwoId);
    }

    if(serviceTypeIds.length == 0) {
      return;
    }

    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["type" + t.id] = t.name;
      }
      for(var item of itemList) {
        item.serviceTypeOneName = typeMap["type" + item.serviceTypeOneId];
        item.serviceTypeTwoName = typeMap["type" + item.serviceTypeTwoId];
      }
    }
  }

  //获取打点统计
  async getPagestatistics(userOnlyCode,list,type){
    //请求类型type：1页面展示、2后台展示
    var opCodeList=[];
    for (var i in list.rows) {
       var tItem=list.rows[i];
       if(tItem!=null){
         opCodeList.push(tItem.opCode);
       }
    }
    var tmpDataList=[];
    if(type==1){
      //获取用户收藏的信息
      var tmpList= await this.pagestatisticsDao.getUserAllStatistics(userOnlyCode,opCodeList,"mryz_sellsc");
      for (var i in list.rows) {
         var tItem=list.rows[i];
         if(tItem) {
          tItem.visit=0;
          tItem.collect=0;
          if(tItem!=null && tmpList && tmpList.length>0){
            tItem.collect=tmpList.findIndex(f=>f.itemCode===tItem.opCode)<0?0:1;
          }
          tmpDataList.push(tItem);
         }
      }
    }
    else if (type==2) {
      var statistics_code_list=["mryz_sellfw","mryz_sellsc"];
      //获取产品访问量、收藏量的数量
      var tmpList= await this.pagestatisticsDao.getUserTotalList(opCodeList,statistics_code_list);
      for (var i in list.rows) {
         var tItem=list.rows[i];
         if(tItem) {
          tItem.visit=0;
          tItem.collect=0;
          if(tItem!=null && tmpList && tmpList.length>0){
            var visitList=tmpList.filter(f=>f.itemCode===tItem.opCode && f.statisticsCode==="mryz_sellfw");
            var collectList=tmpList.filter(f=>f.itemCode===tItem.opCode && f.statisticsCode==="mryz_sellsc");
            if(visitList && visitList.length>0){
              tItem.visit=visitList[0].totalCount;
            }
            if(collectList && collectList.length>0){
              tItem.collect=collectList[0].totalCount;
            }
          }
          tmpDataList.push(tItem);
        }
      }
    }
    console.log("tmpDataList..............................");
    console.log(tmpDataList);
    return tmpDataList;
  }
  //修改用户公司唯一码
  async putUserCompanyOnlyCode(openid,userId,company_only_code,result){
    await this.userDao.putUserCompanyOnlyCode(userId,company_only_code,result);
    //清空用户缓存
    await this.cacheManager["AppletUserinfoCache"].del(openid);
    return result;
  }

  async updateIsPubed(opCode, isPubed, notes) {
    var bl = await super.findOne({opCode:opCode});
    if(bl) {
      bl.isPubed = isPubed;
      if(notes) {
        bl.notes = notes;
      }
      await bl.save();
    }
    return 1;
  }

  async setRecommend(opCode, recommend) {
    var bl = await super.findOne({opCode:opCode});
    console.log(bl, "-----------------------------------blblblbl---------------------");
    if(bl) {
      bl.isRecommend = recommend;
      return await bl.save();
    }
    return 1;
  }

  async delete(opCode) {
    await this.dao.delete({opCode:opCode});
    return 1;
  }
}
module.exports=BusinessLicenseService;
