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 ServiceitemCtl extends CtlBase {
  constructor() {
    super(CtlBase.getServiceName(ServiceitemCtl));
    this.producttypeSve = system.getObject("service.producttypeSve");
    this.companyS = system.getObject("service.companySve");
  }
  async initNewInstance(queryobj, req) {
    var rtn = {};
    var vcode = await this.service.getBusUid("cp");
    rtn.code = vcode;
    return system.getResult2(rtn, null);
  }
  async getAllForOrder(pobj, obj, req) {
    var companyId = obj.company_id || "";
    let list = await this.service.findAll({ company_id: companyId, isPubed: true });
    console.log(list);
    if (list.length == 0) {
      return system.getResult2(list);
    }
    var resultData = [];
    for (var item of list) {
      if (item && item.code != "dlrfzzc" && item.code != "zzsbzc" && item.code != "dbsbzc" && item.itemType) {
        var findIndex = resultData.findIndex(f => f.itemType == item.itemType);
        if (findIndex < 0) {
          var addData = {
            itemType: item.itemType,
            itemTypeName: item.itemTypeName,
            productList: []
          };
          addData.productList.push(item);
          resultData.push(addData);
        } else {
          resultData[findIndex].productList.push(item);
        }
      }
    }
    return system.getResult2(resultData);
  }
  async getRecommendProducts(pobj, obj, req) {
    var companyId = req.companyid || "";
    let list = await this.service.findAll({ company_id: companyId, isRecommend: '1', isPubed: true });
    if (list.length == 0) {
      return system.getResult2(list);
    }
    let itemMap = new Array();
    for (var item of list) {
      var l = itemMap[item.itemType];
      if (!l) {
        l = {
          itemType: item.itemType,
          itemTypeName: item.itemTypeName,
          productList: []
        };
      }
      l.productList.push(item);
      itemMap[item.itemType] = l;
    }
    let result = [];
    for (var idx in itemMap) {
      result.push(itemMap[idx]);
    }
    return system.getResult2(result);
  }

  async getAllProducts2(gobj, pobj, req) {
    try {
      var companyId = req.companyid || "";
      var hostname = req.hostname;
      //按照hostname去查找公司站点信息
      if(companyId==""){
        var companytmp = await this.companyS.findOne({ domainname: hostname, isEnabled: true });
        companyId=companytmp.id;
      }
      var tbDataList = await this.cacheManager["ProductListCache"].getProductListByCache(companyId);
      return tbDataList;
    } catch (e) {
      logCtl.error({
        optitle: "获取产品错误===error",
        op: "/controller/impl/serviceitemCtl.js/getAllProducts",
        content: "obj=" + JSON.stringify(pobj) + "，error=" + e.stack,
        clientIp: ""
      });
    }
    return null;
  }
  async getAllProducts(gobj, pobj, req) {
    try {
      var companyId = req.companyid || "";
      var hostname = req.hostname;
      // console.log("xccccccccccccccccccccccccccccccccccccccc", hostname);
      //按照hostname去查找公司站点信息
      if(companyId==""){
        var companytmp = await this.companyS.findOne({ domainname: hostname, isEnabled: true });
        companyId=companytmp.id;
      }
      var tbDataList = await this.cacheManager["ProductListCache"].getProductListByCache(companyId);
      return system.getResult2(tbDataList);
    } catch (e) {
      logCtl.error({
        optitle: "获取产品错误===error",
        op: "/controller/impl/serviceitemCtl.js/getAllProducts",
        content: "obj=" + JSON.stringify(pobj) + "，error=" + e.stack,
        clientIp: ""
      });
      return system.getResult2(null);
      console.log(e, "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++error ");
    } finally {

    }
  }

  async findOneByCode(obj, req) {
    var code = obj.code;
    // var user = req.session.user;
    if (!code) {
      return { code: -1, msg: "code参数错误" };
    }
    if (!req.companyid) {
      return { code: -2, msg: "未知的站点" };
    }
    try {
      var data = await this.service.findOneByCode(code, req.companyid);
      return { code: 1, data: data };
    } catch (error) {
      return { code: -200, msg: "操作失败" };
    }

  }

  async findOneById(obj, req) {
    var id = obj.id;
    if (!id) {
      return { code: -1, msg: "产品id参数错误" }
    }
    try {
      var rd = await this.service.findById(id);
      return { code: 1, data: rd };
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "查询商机信息findOneById异常error",
        op: "base/controller/impl/serviceitemCtl.js",
        content: e.stack,
        clientIp: ""
      });
      return { code: -100, msg: "获取产品失败" };
    }
  }
  //获取推荐产品(6条)
  async findByCompany(gobj, pobj, req){
    try {
      var companyId = req.companyid || "";
      var hostname = req.hostname;
      //按照hostname去查找公司站点信息
      if(companyId==""){
        var companytmp = await this.companyS.findOne({ domainname: hostname, isEnabled: true });
        companyId=companytmp.id;
      }
      var lists = await this.service.findByCompany(companyId) 
      if (lists.count == 0){
        var lists = await this.service.findByCompany("1")
      }
      return system.getResult2(lists);
    } catch (e) {
      logCtl.error({
        optitle: "获取推荐产品错误===error",
        op: "/controller/impl/serviceitemCtl.js/findByCompany",
        content: "obj=" + JSON.stringify(pobj) + "，error=" + e.stack,
        clientIp: ""
      });
      return system.getResult2(null);
  }
 }
}
module.exports = ServiceitemCtl;
// var test = new ServiceitemCtl();
// test.findByCompany(null,null,null).then(function(d){
//   console.log("ddddddddddddddddddddddddddddddddddddddddd");
//   console.log(d);
// })
