const system=require("../../system");
const ServiceBase=require("../sve.base");
class BuybusinessLicenseService extends ServiceBase{
  constructor(){
     super(ServiceBase.getDaoName(BuybusinessLicenseService));
  }
  async addCompany(obj,userInfo,channelInfo){
    var opCode = obj.opCode || "";
    var bbl = null;
    if(opCode) {
      bbl = await super.findOne({opCode:opCode});
      bbl.serviceTypeTwoId=obj.serviceTypeOneId;
      bbl.serviceTypeTwoId=obj.serviceTypeTwoId;

      bbl.registerProvince=obj.registerProvince;
      bbl.registerCity=obj.registerCity;
      bbl.registerArea=obj.registerArea;

      bbl.registerCapital = obj. registerCapital || 0;
      bbl.registerDay=obj.registerDay;
      bbl.companyProperty=obj.companyProperty || "1";
      bbl.changeService=obj.changeService || "1";
      bbl.guidePrice = obj.guidePrice || 0
      await bbl.save();
    } else {
      var tmpuid=await this.getUidInfo(5,36);
      opCode=tmpuid+""+Date.now();
      obj.channel_id=channelInfo.id;
      obj.channelCode=channelInfo.channelCode;
      obj.isPubed=1;
      obj.opCode=opCode;
      obj.onlyCode=userInfo.onlyCode;
      obj.companyOnlyCode=userInfo.referrerOnlyCode||userInfo.onlyCode;
      obj.hotline=userInfo.mobile;
      await this.create(obj);
    }
    return {
         code: 1,
         message: "success",
         data: {op_code:opCode}
      };
  }

  async listByUser(onlyCode, pageIndex, pageSize) {
    var whereObj={onlyCode : onlyCode};

    var attributesObj=["opCode","serviceTypeOneId","serviceTypeTwoId","registerCapital", "registerDay","registerProvince","registerCity","registerArea","registerAddr","companyPropertyName","guidePrice","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;
    }

    await this.setServiceTypeName(result);
    return result;
  }

  //易照详情
  async getDetailByOpCode(userOnlyCode, op_code){

      // 请求类型：1页面展示、2后台展示
    var item = await this.dao.model.findOne({where:{opCode:op_code},
                     attributes:["opCode","serviceTypeOneId","serviceTypeTwoId", "registerDay", "registerProvince","registerCity","registerArea",
                     "registerCapital","companyProperty","companyPropertyName","changeService","changeServiceName","guidePrice", "created_at"],raw:true});


    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;
       }
     }
    }
    return {
       code: 1,
       message: "success",
       data: item
    };
  }

  async buyList(params) {
    var userId = Number(params.userId);
    var pageIndex = Number(params.pageIndex);
    var pageSize = Number(params.pageSize);
    var serviceTypeOneId = params.serviceTypeOneId;
    var serviceTypeTwoId = params.serviceTypeTwoId;
    var registeredCapital = params.registeredCapital;
    var created_at = params.created_at;
    var priceDict = params.priceDict;

    var whereObj={};
    if(serviceTypeOneId) {
      whereObj.serviceTypeOneId = serviceTypeOneId;
    }
    if(serviceTypeTwoId) {
      whereObj.serviceTypeTwoId = serviceTypeTwoId;
    }
    if(registeredCapital) {
      whereObj.registeredCapital = registeredCapital.toString();
    }

    if(created_at) {
      whereObj.created_at = {[this.db.Op.between]:[created_at + " 00:00:00", created_at + " 23:59:59"]};
    }

    // 大照商 10万以下
    // 超管 所有
    var sql = "SELECT t2.user_id, t1.code FROM p_role t1 INNER JOIN p_userrole t2 ON t1.id = t2.`role_id` WHERE t2.`user_id` = :user_id";
    var roleList = await this.dao.customQuery(sql, {user_id: userId});
    if(!roleList || roleList.length == 0) {
      return {count:0, rows:[]};
    }

    var rcodes = [];
    for(var r of roleList) {
      rcodes.push(r.code);
    }

    if(rcodes.indexOf("yz_super_admin") != -1) {
    } else if(rcodes.indexOf("yz_big_business") != -1) {
      priceDict = {min:0, max:100000};
    } else {
      return {count:0, rows:[]};
    }

    // if(priceDict) {
    //   whereObj.guidePrice = {[this.db.Op.between]:[priceDict.min, priceDict.max]};
    // }

    var attributesObj=["id", "opCode","onlyCode","serviceTypeOneId","serviceTypeTwoId","registerCapital", "registerDay","registerProvince","registerCity","registerArea","registerAddr","companyPropertyName","guidePrice","created_at"];
    var result = await super.getPageList(pageIndex, pageSize,whereObj, [["id", 'DESC']], attributesObj);

    if(!result || !result.rows || result.rows.length == 0) {
      return result;
    }
    await this.setServiceTypeName(result);
    await this.setUid(result.rows);
    return result;
  }

  async getDetailById(id) {
    var item=await this.dao.model.findOne({where:{id:id},
                                           attributes:["id", "serviceTypeOneId","serviceTypeTwoId",
                                           "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 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 setServiceTypeName(result) {
    var serviceTypeIds = [];
    for(var r of result.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 result.rows) {
        r.serviceTypeOneName = typeMap["id" + r.serviceTypeOneId] || "";
        r.serviceTypeTwoName = typeMap["id" + r.serviceTypeTwoId] || "";
      }
    }
  }

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