var system = require("../../system")
var settings = require("../../../config/settings");
const CtlBase = require("../ctl.base");
const uuidv4 = require('uuid/v4');

class EcompanycontractCtl extends CtlBase {
  constructor() {
    super(CtlBase.getServiceName(EcompanycontractCtl));
    this.cacheManager = system.getObject("db.cacheManager");
    this.excelClient = system.getObject("util.excelClient");
    this.ecompanySve = system.getObject("service.ecompanySve");
    this.epartnerSve = system.getObject("service.epartnerSve");

  }  

  async findAndCountAll(queryobj, obj, req) {
    var codepath = req.codepath;
    if (codepath.indexOf("ecompanycontractall") > 0) {

    } else {  
      obj.search.user_id = req.session.user.id;
    }
    obj.raw = "true";
    var apps = await super.findAndCountAll(queryobj, obj, req);
    if(apps && apps.data && apps.data.rows && apps.data.rows.length > 0) {
      var epartnerIds = [];
      for(var item of apps.data.rows) {
        if(item.epartner_id) {
          epartnerIds.push(item.epartner_id);
        }
      }
      if(epartnerIds.length > 0) {
        var epartnerMap = await this.epartnerSve.findMapByIds(epartnerIds);

        for(var item of apps.data.rows) {
          item.epartner = epartnerMap["id_" + item.epartner_id] || {};
          console.log(item);
        }
      }
    }
    return apps;
  }

  async saveContract(queryobj,qobj,req){
    var getNo = await this.service.findOne({contractNo: qobj.contractNo});
    //1.添加合同
    if(getNo) {
      return system.getErrResult2("合同编号已经存在");
    }
    qobj.epartner_id = qobj.epartner_id || 0;
    if(qobj.epartner_id) {
      var epartner = await this.epartnerSve.findById(qobj.epartner_id);
      qobj.user_id = epartner.user_id;
    }

    var rd = await this.service.create(qobj);
    //2.添加子公司
    var getSubNames = qobj.names;
    for (var item in getSubNames) {
      var compName = getSubNames[item]['subname'];
      if(getSubNames[item]['isExists'] == 0){
        var newEcompany = {
          name: compName,       
          nameA: qobj.nameA || "智信云（天津）科技有限公司",   
          ecompanycontract_id: rd.id,
          owner_id: rd.user_id || 0,
          epartner_id : qobj.epartner_id || 0,
        };
       await this.ecompanySve.savebpo(newEcompany);
      }
    }
    return system.getResult2(rd,null);
  }

  //我的合同中的新增（修改合同中的userId）
  async updateUserId(queryobj,qobj,req){
    var result = {
      code: 0,
      msg:'合同编号不存在'
    }; 

    var companyContract = await this.service.findOne({contractNo: qobj.contractNo});
    //1.合同编号是否存在
    if(!companyContract) {
      return result;
    }else{
      if(companyContract.user_id != 0){
        result.msg = "合同编号已分配";
        return result;
      }
    }
       
    
    //2.修改数据
    companyContract.user_id = req.session.user.id;
    await companyContract.save();
    result.code =1;      
    result.msg = "添加成功";
    return result;    
  }

  async assignContract(queryobj,qobj,req){
    var id = Number(this.trim(qobj.contractId)) || 0;
    var epartner_id = Number(this.trim(qobj.epartner_id)) || 0;
    
    try {
      var rs = await this.service.assignContract(id, epartner_id);
      if(rs) {
        return system.getErrResult2(rs);
      }
      return system.getResult2(1);
    } catch (error) {
      console.log(error.stack);
    }
    return system.getErrResult2("分配失败");
  }

  async compInfo(queryobj,qobj,req){
    var result = {
      code: 0,
      contract:'',
      ecompany: [],
    }; 

    //1.获取合同信息
    var getCont = await this.service.findOne({id: qobj.id});
    
    if(getCont){
      //2.获取合同关联的公司集合
      var getComp = await this.ecompanySve.companyBycontrId(qobj.id);
      
      result.code = 1;
      result.contract = getCont;
      result.ecompany = getComp;
      if(getCont.epartner_id) {
        result.epartner = await this.epartnerSve.findById(getCont.epartner_id) || {};
      } else {
        result.epartner = {};
      }
      return result;
    }
    
    return result;
  }

  async parseExcel(queryobj, obj, req) {
    var result = {
      code: 0,
      data: [],
    }; 
    var compNames = [];
    try {      
      var rs = await this.excelClient.readExcel(req.session.user.id, obj.nameUrl);      
      if (rs.code == 1) {
        var rows = rs.data;
        for (var item in rows) {
          var compName = rows[item];
          var isExists = await this.ecompanySve.isExistsCompanyName(compName);          
          compNames.push(compName + "-" + isExists);
        }
        result.code = 1;
        result.data = compNames;
        return system.getResult2(result);
      }else{
        return system.getResult2(result);
      }      
    } catch (error) {
      console.log(error.stack);
      return result;
    }
  }
}
module.exports = EcompanycontractCtl;