const system=require("../../system");
const ServiceBase=require("../sve.base");
const settings=require("../../../config/settings");
const uuidv4 = require('uuid/v4');
class BusinesschanceService extends ServiceBase{
  constructor(){
     super(ServiceBase.getDaoName(BusinesschanceService));
     this.cacheManager=system.getObject("db.cacheManager");
     this.shopSve=system.getObject("service.shopSve");
     this.servicesitemSve=system.getObject("service.servicesitemSve");
     this.pconfigSve=system.getObject("service.pconfigSve");
     this.channelSve=system.getObject("service.channelSve");
  }
  async findAllChances(obj){
    return this.dao.model.findAll({where:obj,attributes:["id","chanceStatus","chanceStatusName","publisherName","publisherMobile","created_at","channelCode","chanceType","chanceTypeName"],raw:true,order:[["created_at","desc"]]});
  }
  async findchance(obj){
    return this.dao.model.findOne({where:obj});
  }
  async findAllChancesByPublisherids(ids){
    var sql=  "SELECT * FROM	h_business_chance	WHERE	user_id = "+userId;
    console.log(sql);
    var payUserIds=await this.dao.customQuery(sql);
    return payUserIds;
  }
  async findCustomersByOnlyCode(onlycode){
    var sql="SELECT id,nickName,openId,unionId,headUrl,account_id,app_id,userName,referrerOnlyCode "+
    "FROM p_user "+
    "WHERE id IN ( "+
    		"SELECT DISTINCT payUserId FROM h_order_info WHERE onlyCode = '"+onlycode+"' AND payUserId IS NOT NULL "+
     ")";
    console.log(sql);
    var users=await this.dao.customQuery(sql);
    return users;
  }
  async findCustomers(onlycode,nickName){
    var sql="SELECT id,nickName,openId,unionId,headUrl,account_id,app_id,userName,referrerOnlyCode "+
    "FROM p_user "+
    "WHERE id IN ( "+
    		"SELECT DISTINCT payUserId FROM h_order_info WHERE onlyCode = '"+onlycode+"' AND nickName like '%"+nickName+"%' AND payUserId IS NOT NULL "+
     ")";
    console.log(sql);
    var users=await this.dao.customQuery(sql);
    return users;
  }
  //添加需求-移动端
  async addChanceType(obj){
    var result={
       code: 1,
       message: "success",
       data: null
    };
    var shopInfo=await this.shopSve.getShopItemInfo(obj);
    if(shopInfo.code!=1){
      result.code=shopInfo.code;
      result.message=shopInfo.message;
      return result;
    }
    var userInfo =await this.cacheManager["AppletUserinfoCache"].get(obj.openid);
    var tUserInfo=JSON.parse(userInfo);
    var channel=obj.channel==null||obj.channel==""||obj.channel=="undefined"?"hhr":obj.channel;

    var addParams={
      chanceStatus:"1",
      app_id:tUserInfo.app_id,
      publisherId:tUserInfo.id,//发布者id
      publisherName:tUserInfo.nickName,//发布者姓名
      publisherMobile:tUserInfo.mobile,//发布者手机号
      publisherOnlyCode:tUserInfo.onlyCode,//发布者唯一码
      chanceType:obj.needcode,//商机类型
      shopOnlyCode:obj.onlycode,//商铺唯一码
      shopName:shopInfo.data.shop_name,//店铺名称
      shopNum:shopInfo.data.shop_num,//店铺号
      shopMobile:shopInfo.data.user_mobile,//店铺手机号
      channelCode:channel
    };
    var chanceTypeName="";
    if(obj.needcode=="ip"){
      chanceTypeName= "商标";
    }else if(obj.needcode=="ic"){
      chanceTypeName= "版权";
    }else if(obj.needcode=="pa"){
      chanceTypeName= "专利";
    }else if(obj.needcode=="common"){
      chanceTypeName= "增值";
    }else if(obj.needcode=="icbc"){dao
      chanceTypeName= "工商";
    }else{
      chanceTypeName= "其他";
    }
    await this.dao.create(addParams);
    //发送短信
    var smsClient=system.getObject("util.smsClient");
    smsClient.sendMsg(shopInfo.data.user_mobile,"亲爱的知产合伙人，你的客户于"+(new Date()).Format("yyyy-MM-dd")+"发布了新的【"+
                           chanceTypeName+"】需求，亲，赶紧联系客户吧！");
    return result;
  }
  //获取需求-移动端
  async getChanceTypeList(obj){
    var openid = obj.openid;
    var result={
       code: 1,
       message: "success",
       data: []
    };
    if(openid==null||openid==""||openid=="undefined"){
      result.code=-101;
      result.message="openid参数有误";
      return result;
    }
    var channel=obj.channel==null||obj.channel==""||obj.channel=="undefined"?"hhr":obj.channel;

    var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
    if(userInfo=="null"||userInfo==null||userInfo=="undefined"){
      result.code=-102;
      result.message="用户信息有误";
      return result;
    }
    var tUserInfo=JSON.parse(userInfo);
    //获取需求信息
    var sqlWhere={where:{publisherOnlyCode:tUserInfo.onlyCode,channelCode:channel},attributes:["chanceStatus","chanceStatusName","chanceType","chanceTypeName","created_at","shopName",
                    "shopMobile","shopNum"],order:[["created_at", 'desc']],raw:true};
    var list=await this.dao.model.findAll(sqlWhere);
    if(list==null||list.length==0){
      result.message="暂无需求数据";
      return result;
    }
    for (var i = 0; i < list.length; i++) {
      var item=list[i];
      if(item!=null){
        var need_item={
               need_item:{
                 chance_status:item.chanceStatus,
                 chance_status_name:item.chanceStatusName,
                 need_code: item.chanceType,
                 need_name: item.chanceTypeName,
                 created_at: item.created_at,
                 customer_contact: item.shopName,
                 customer_mobile: item.shopMobile,
                 shop_num: item.shopNum
             }
        };
        result.data.push(need_item);
      }
    }
    return result;
  }

  //渠道商标交易需求操作
  async getTmTradeNeedList(obj){
    var openid = obj.openid;
    var result={
       code: 1,
       message: "success",
       data: []
    };
    if(openid==null||openid==""||openid=="undefined"){
      result.code=-101;
      result.message="openid参数有误";
      return result;
    }
    var channel=obj.channel==null||obj.channel==""||obj.channel=="undefined"?"hhr":obj.channel;

    var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
    if(userInfo=="null"||userInfo==null||userInfo=="undefined"){
      result.code=-102;
      result.message="用户信息有误";
      return result;
    }
    var tUserInfo=JSON.parse(userInfo);
    console.log(tUserInfo);
    var sql = "SELECT chance.publisherOnlyCode,chance.chanceStatus,chance.chanceStatusName,chance.chanceType,chance.chanceTypeName,"+
	    "chance.created_at,chance.shopName,chance.shopMobile,chance.shopNum,service.mobilePic,service.sellStatus,service.sellStatusName,"+
	    "service.priceRangeMax,service.priceRangeMin,service.tmExpirationDate,service.nclOneCodes,service. CODE,service. NAME,"+
      "service.itemType,service.itemTypeName"+
      " FROM `h_business_chance` AS chance LEFT JOIN cms_servicesitem AS service ON chance.serviceItem_code = service. CODE"+
      " WHERE chance.channelCode = '"+channel+"' and chance.publisherOnlyCode='"+tUserInfo.onlyCode+"' and chance.deleted_at is null and service.deleted_at is null"+
      " ORDER BY created_at DESC";
    var paras={};
    var list= await this.dao.customQuery(sql,paras);
    if(list==null||list.length==0){
      result.message="暂无需求数据";
      return result;
    }
    for (var i = 0; i < list.length; i++) {
      var item=list[i];
      if(item!=null){
        var need_item={
               need_item:{
                 chance_status:item.chanceStatus,
                 chance_status_name:item.chanceStatusName,
                 need_code: item.chanceType,
                 need_name: item.chanceTypeName,
                 created_at: item.created_at,
                 customer_contact: item.shopName,
                 customer_mobile: item.shopMobile,
                 shop_num: item.shopNum,
                 mobile_pic:item.mobilePic,
              	sell_status:item.sellStatus,
              	sell_status_ame:item.sellStatusName,
              	price_range_max:item.priceRangeMax,
              	price_range_min:item.priceRangeMin,
              	tm_expiration_date:item.tmExpirationDate,
              	ncl_one_codes:item.nclOneCodes,
              	code:item.CODE,
              	name:item.NAME,
              	item_type:item.itemType,
              	item_type_name:item.itemTypeName
             }
        };
        result.data.push(need_item);
      }
    }
    return result;
  }

  //获取商机详情（商标交易商机）
  async getTmTradeDetails(obj){//openid chanceId
    var openid = obj.openid;
    var chanceId = obj.chanceId;
    // var usertype = obj.usertype;
    var result={
       code: 1,
       message: "success",
       data: {}
    };
    if(openid==null||openid==""||openid=="undefined"){
      result.code=-101;
      result.message="openid参数有误";
      return result;
    }
    if(chanceId==null||chanceId==""||chanceId=="undefined"){
      result.code=-102;
      result.message="chanceId参数有误";
      return result;
    }
    console.log(openid);
    var userInfo =await this.cacheManager["AppletUserinfoCache"].get(openid);
    console.log(userInfo);
    if(userInfo=="null"||userInfo==null||userInfo=="undefined"){
      result.code=-105;
      result.message="用户信息有误";
      return result;
    }
    var tUserInfo=JSON.parse(userInfo);
    var sql = "SELECT service.authorMobile,service.authorName,service.isPubed,chance.publisherName,chance.publisherMobile, chance.publisherOnlyCode,chance.notes,chance.chanceStatus,chance.chanceStatusName,chance.chanceType,chance.chanceTypeName,"+
	    "chance.created_at,chance.shopName,chance.shopMobile,chance.shopNum,service.mobilePic,service.sellStatus,service.sellStatusName,"+
	    "service.priceRangeMax,service.priceRangeMin,service.tmExpirationDate,service.nclOneCodes,service.code,service.name,"+
      "service.itemType,service.itemTypeName,service.descr"+
      " FROM `h_business_chance` AS chance LEFT JOIN cms_servicesitem AS service ON chance.serviceItem_code = service.code"+
      " WHERE chance.id = "+chanceId+" and chance.shopOnlyCode='"+tUserInfo.onlyCode+"' and chance.deleted_at is null and service.deleted_at is null"+
      " ORDER BY created_at DESC";
    var paras={};
    var list= await this.dao.customQuery(sql,paras);
    if(list==null||list.length==0){
      result.message="暂无商机数据";
      return result;
    }
     var detail = list[0];
     result.data=detail;
    return result;
    // return sql;
  }

  //======================================================渠道合作=============================================
  //获取某一个渠道的商机统计
  async getChannelTotal(obj){
    var channel_code=obj.channel_code||"";
    if(channel_code==""){
      result.code=-104;
      result.message="channel_code参数有误";
      return result;
    }
    var result={
       code: 1,
       message: "success",
       data:{
         total_sum:0,
         self_profit:0,
         every_single_profit:0,
         profit_type:'1',
         total_count:0,
         success_count:0,
         failue_count:0
       }
    };
    var channel=await this.channelSve.getChannelItem(channel_code);
    if(!channel){
      result.code=-105;
      result.message="渠道编码输入有误";
      return result;
    }

    result.data.every_single_profit=parseFloat(channel.everySingleProfit||0);
    result.data.profit_type=Number(channel.profitType);
    var sql = "SELECT COUNT(id) AS total_count, COUNT(chanceStatus='4' OR NULL) AS success_count,COUNT(chanceStatus='8' OR NULL) AS failue_count FROM h_business_chance WHERE channelCode=:channelCode";
    var param={channelCode:channel_code};
    var list= await this.dao.customQuery(sql,param);
    if(list==null||list.length==0){
      return result;
    }
    result.data.total_count=list[0].total_count;
    result.data.success_count=list[0].success_count;
    result.data.failue_count=list[0].failue_count;

    sql ="SELECT SUM(channelProfit) AS channel_profit,SUM(platformProfit) AS platform_profit FROM h_business_chance WHERE channelCode=:channelCode AND chanceStatus='4'";
    var tList= await this.dao.customQuery(sql,param);
    if(tList==null||tList.length==0){
      return result;
    }
    result.data.total_sum=parseFloat(tList[0].platform_profit||0);
    result.data.self_profit=parseFloat(tList[0].channel_profit||0);
    return result;
  }
  //获取某一个渠道的商机列表
  async getChannelBusinessList(obj){
    var channelCode = obj.channel_code||"";
    var chanceStatus = Number(obj.chance_status||0);
    var currentPage =  Number(obj.current_page||1);
    var pageSize= Number(obj.page_size||10);
    if(currentPage<1){
      currentPage=1;
    }
    if(pageSize>50){
      pageSize=50;
    }
    var result={
       code: 1,
       message: "success",
       data:[]
    };
    //当前第几页,从1开始
    var currentPage=obj.current_page;
    if(channelCode==""||channelCode=="undefined"){
      result.code=-101;
      result.message="channel_code参数有误";
      return result;
    }
    if(chanceStatus==""||chanceStatus=="undefined"){
       chanceStatus=0;
    }

    var whereObj={channelCode:channelCode}
    if(chanceStatus>0){
      whereObj.chanceStatus=chanceStatus.toString();
    }
    var attributesObj=["id","created_at","chanceTypeName","chanceStatusName","serviceItem_code","serviceItem_name","profitTypeName","channelProfit","channelProfitRatio","disposeNotes"];
    var businessList=await this.getPageList(currentPage,pageSize,whereObj,[["created_at", 'desc']],attributesObj);
    if(!businessList||businessList.rows.length==0){
      result.message="空空如也";
      return result;
    }
    for (var i = 0; i < businessList.rows.length; i++) {
      var tItem=businessList.rows[i];
      if(tItem!=null){
        var tParam={
          id:tItem.id,
          created_at:tItem.created_at,
          chance_type_name:tItem.chanceTypeName,
          chance_status_name:tItem.chanceStatusName,
          service_code:tItem.serviceItem_code,
          service_name:tItem.serviceItem_name,
          profit_type_name:tItem.profitTypeName,
          channel_profit:parseFloat(tItem.channelProfit||0),
          channel_profit_ratio:parseFloat(tItem.channelProfitRatio||0),
          dispose_notes:tItem.disposeNotes
        };
        result.data.push(tParam);
      }
    }
    console.log("result....................................");
    console.log(result);
    return result;
  }
  //获取指定渠道的所有商机_暂时没有用到
  async getBusinessAllotList(channelStatus){
    var bussinessAllotChannel=await this.pconfigSve.getBussinessAllotChannelConfig();
    var tList=bussinessAllotChannel.split(',');
    if(tList==null||tList.length==0){
      return null;
    }
    var tArray=[];
    for (var i = 0; i < tList.length; i++) {
      var c=tList[i];
      if(c!=null&&c!=""){
        tArray.push(c);
      }
    }
    var sqlWhere={where:{chanceStatus:channelStatus,channelCode:{[this.dao.db.Op.in]:tArray}},offset:0,limit:2000};
    return this.dao.model.findAll(sqlWhere);
  }
}
module.exports=BusinesschanceService;
// var task=new BusinesschanceService();
// var obj ={openid:"ovPx35GktY-8pn3GmpIYfcbmqZQk",chanceId:"53"};
// task.getTmTradeDetails(obj).then(function(result){
//   console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
//   console.log((result));
// }).catch(function(e){
//   console.log(e);
// });
