var system = require("../../system")
var settings = require("../../../config/settings");
const CtlBase = require("../ctl.base");
const uuidv4 = require('uuid/v4');
const moment = require("moment");
class EcompanyCtl extends CtlBase {
  constructor() {
    super(CtlBase.getServiceName(EcompanyCtl));

    this.regionareaSve = system.getObject("service.regionareaSve");
    this.userSve = system.getObject("service.userSve");
    this.epartnerSve = system.getObject("service.epartnerSve");
    this.ejobSve = system.getObject("service.ejobSve")

    this.ecompanyeventSve = system.getObject("service.ecompanyeventSve");
    this.eintentionSve = system.getObject("service.eintentionSve");
    this.etemplateSve = system.getObject("service.etemplateSve");

    this.ecompanybpoSve = system.getObject("service.ecompanybpoSve");

    this.esettleSve = system.getObject("service.esettleSve");

  }

  async getByName(queryobj, qobj, req) {}

  async validMyName(queryobj, qobj, req) {
    var user = req.session.user;
    var loginCompany = req.session.ecompany;
    var ecompany = await this.service.findOne({
      name: qobj.name
    });

    if(loginCompany && ecompany && loginCompany.id != ecompany.id) {
      return system.getErrResult2("您输入的公司名称已被认证, 如需申诉请联系客服");
    }

    if (!ecompany || !ecompany.user_id || ecompany.user_id == user.id) {
      return system.getResult2(1);
    }
    return system.getErrResult2("您输入的公司名称已被认证, 如需申诉请联系客服");
  }

  async myCompany(queryobj, qobj, req) {
    var user = req.session.user;
    var ecompany = req.session.ecompany;

    if (ecompany) {
      return system.getResult2(ecompany);
    }

    if (user) {
      ecompany = await this.service.findOne({
        user_id: user.id
      });
      if (ecompany) {
        req.session.ecompany = ecompany;
        return system.getResult2(ecompany);
      }
    }
    return system.getErrResult2("无认证公司信息");
  }

  async mysave(queryobj, qobj, req) {
    try {
      console.log(queryobj, "--------------------------queryobj---------------");
      console.log(qobj, "--------------------------qobj---------------");
      var old = null;
      if (qobj.id) {
        old = await this.service.findById(qobj.id);
      }
      console.log(old, "--------------------------old---------------");

      var rtn = null;
      if (old) { //修改
        console.log("edit++++++++++++++++++++++++++++++++++++");
        rtn = await this.service.update(qobj);
      } else { //新增
        console.log("new++++++++++++++++++++++++++++++++++++");
        rtn = await this.service.create(qobj);
      }

      // 调用e签宝接口生成accountid
      return system.getResult2(rtn, null);
    } catch (e) {
      console.log("-----------------------------e");
      console.log(e);
      return {
        code: -1
      }
    }
  }

  async allList(queryobj, qobj, req) {
    var params = {};

    var loginUser = req.session.user;
    var roles = loginUser.Roles || [];
    var isZC = false;
    for(var r of roles) {
      if(r.code == 'zcry' || r.code == 'zcgl') {
        isZC = true;
        break;
      }
    }
    if(!loginUser.isAdmin && !isZC) {
      if(!req.session.myIds || req.session.myIds.length == 0) {
        return system.getResult2({count: 0, rows: []});
      }
      params.ownerIds = req.session.myIds;
    }
    return await this.list(queryobj, qobj, req, params);
  }

  async myList(queryobj, qobj, req) {
    var params = {
      owner_id: req.session.user.id
    }
    return await this.list(queryobj, qobj, req, params);
  }

  async list(queryobj, qobj, req, params) {
    // 1待审核 2通过 3驳回
    // "proxyAuditStatus" : {"0":"待审核","1":"审核通过","2":"审核驳回"},
    if (!qobj.search) {
      qobj.search = {};
    }
    var auditType;
    if (params) {
      if (params.owner_id) {
        qobj.ownerIds = [params.owner_id];
      } else if(params.ownerIds) {
        qobj.ownerIds = params.ownerIds;
      }
    }
    qobj.raw = true;
    var rs = await super.findAndCountAll(queryobj, qobj, req);

    if (rs && rs.data && rs.data.rows) {
      var ownerIds = [];
      for (var row of rs.data.rows) {
        if (row.updated_at) {
          row.updated_at = new Date(row.updated_at).Format("yyyy-MM-dd hh:mm");
        }
        if (row.created_at) {
          row.created_at = new Date(row.created_at).Format("yyyy-MM-dd hh:mm");
        }
        if (row.updated_at) {
          row.updated_at = new Date(row.updated_at).Format("yyyy-MM-dd hh:mm");
        }

        if (row.owner_id) {
          ownerIds.push(row.owner_id);
        }
      }

      var usermap = await this.userSve.findMapByIds(ownerIds);
      if (ownerIds.length > 0) {
        for (var row of rs.data.rows) {
          if (row.owner_id) {
            row.owner = usermap["id_" + row.owner_id];
          }
        }
      }
    }
    return rs;
  }

  async custsave(queryobj, qobj, req) {
    try {
      var ecompany = null;
      let id = qobj.id;
      if (id) {
        ecompany = await this.service.findById(id);
      }
      var loginUser = req.session.user;

      var pcode = "";
      var ccode = "";
      qobj.cityName = await this.regionareaSve.findNameByCode(qobj.cityCode);

      var ccarr = qobj.cityCode.split("_");
      if (ccarr.length > 0) {
        pcode = ccarr[0];
      }
      if (ccarr.length > 1) {
        ccode = ccarr[1];
      }

      var repeat = await this.service.findOne({
        name: qobj.name
      });

      if (repeat) {
        if (!ecompany) {
          return system.getErrResult2("该公司已被其他人录入");
        }
        if (ecompany.id != repeat.id) {
          return system.getErrResult2("该公司已被其他人录入");
        }
      }

      var intention = await this.eintentionSve.findOne({name: qobj.name});
      if(intention && loginUser.id != intention.owner_id) {
        return system.getErrResult2("该公司已被其他人录入");
      }

      if (ecompany) {
        //修改
        ecompany.name = qobj.name;
        ecompany.credit_code = qobj.credit_code;
        ecompany.bank = qobj.bank;
        ecompany.bankno = qobj.bankno;
        ecompany.contractName = qobj.contractName;
        ecompany.contractMobile = qobj.contractMobile;
        ecompany.ecompanyLevel = qobj.ecompanyLevel;
        ecompany.ecompanySourceType = qobj.ecompanySourceType;
        ecompany.credit_code = qobj.credit_code;
        ecompany.cityCode = qobj.cityCode;
        ecompany.cityName = qobj.cityName;
        ecompany.pcode = pcode;
        ecompany.ccode = ccode;
        if(qobj.nameA) {
          ecompany.nameA = qobj.nameA;
        }

        ecompany = await ecompany.save();
      } else {

        ecompany = {};
        ecompany.name = qobj.name;
        ecompany.credit_code = qobj.credit_code;
        ecompany.bank = qobj.bank;
        ecompany.bankno = qobj.bankno;
        ecompany.contractName = qobj.contractName;
        ecompany.contractMobile = qobj.contractMobile;
        ecompany.ecompanyLevel = qobj.ecompanyLevel;
        ecompany.ecompanySourceType = qobj.ecompanySourceType;
        ecompany.cityCode = qobj.cityCode;
        ecompany.cityName = qobj.cityName;
        ecompany.pcode = pcode;
        ecompany.ccode = ccode;
        ecompany.nameA = qobj.nameA;

        // 所属人关系
        ecompany.owner_id = req.session.user.id;
        if (req.session.partner) {
          var epartner = await this.epartnerSve.findById(req.session.partner.id)
          ecompany.epartner_id = epartner.id;
          ecompany.partnerType = epartner.partnerType;
          ecompany.isBenefit = true;
        }
        console.log("new++++++++++++++++++++++++++++++++++++");
        ecompany = await this.service.savebpo(ecompany);
        if (!ecompany) {
          return system.getErrResult2("保存失败, 请稍后重试");
        }
      }
      return system.getResult2(ecompany, null);
    } catch (e) {
      console.log(e);
      return {
        code: -1
      }
    }
  }
  async authsave(queryobj, qobj, req) {
    try {
      var user = req.session.user;
      var ecompany = req.session.ecompany;

      var form = qobj.ecompany;
      var nameCompany = await this.service.findOne({  
        name: form.name
      });

      if (ecompany) {
        if(nameCompany && ecompany.id != nameCompany.id) {
          return system.getErrResult2("该公司名称已被其他人认证");
        }
        ecompany = await this.service.findById(ecompany.id);
        if(!ecompany.user_id) {
          ecompany.user_id = user.id;
        }
        this.setAuthCompany(ecompany, form);
        await ecompany.save();
        this.setAuthEvent(ecompany, user);
        req.session.ecompany = ecompany;
        return system.getResult2(ecompany);
      } else {
        ecompany = nameCompany;
      }

      if (ecompany) {
        if(!ecompany.user_id || ecompany.user_id == user.id) {
          ecompany.user_id = user.id;
          this.setAuthCompany(ecompany, form);
          await ecompany.save();
          req.session.ecompany = ecompany;
          this.setAuthEvent(ecompany, user);
          return system.getResult2(ecompany);
        }
        return system.getErrResult2("该公司名称已被认证, 如需申诉请联系客服");
      }
      ecompany = {};
      this.setAuthCompany(ecompany, form);
      ecompany.user_id = user.id;
      ecompany = await this.service.savebpo(ecompany);
      req.session.ecompany = ecompany;

      return system.getResult2(ecompany);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("保存失败");
    }
  }

  setAuthEvent(ecompany, user) {
    if(ecompany.jdAuthStatus != 1) {
      var now = moment().format("YYYY-MM-DD HH:mm:ss");
      var content = ecompany.name + "于" + now + "申请企业认证";
      var ecompanyEvent = {
        type: 2,
        biz_id: ecompany.id,
        content: content,
        status: false,
        ecompany_id: -1,
        user_id: user.id,
      };
      this.ecompanyeventSve.create(ecompanyEvent);
    }
  }

  setAuthCompany(ecompany, form) {
    ecompany = ecompany || {};
    ecompany.addr = form.addr || "";
    ecompany.intro = form.intro || "";
    ecompany.contractName = form.contractName || "";
    ecompany.contractMobile = form.contractMobile || "";
    ecompany.telephone = form.telephone || "";
    ecompany.email = form.email || "";
    if(ecompany.jdAuthStatus != 1) {
      ecompany.logo = form.logo || "";
      ecompany.name = form.name || "";
      ecompany.nature = form.nature || "";
      ecompany.industry = form.industry || "";
      ecompany.businessLicense = form.businessLicense || "";
      ecompany.jdAuthApplyTime = new Date();
      ecompany.jdAuthStatus = '0';
      ecompany.jdAuthStatusName = '待认证';
    }
  }

  async signList(queryobj, qobj, req) {
    var params = qobj.search;
    try {
      var page = await this.service.signPage(params);
      return system.getResult2(page);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    } 
  }

  async signSave(queryobj, qobj, req) {
    try {
      var mtchIdStr = qobj.mtchIds;
      var mtchResult = await this.buildMtchs(qobj.mtchIds);
      if(mtchResult.code === 0) {
        return system.getErrResult2(mtchResult.msg);
      }

      var ecompany = null;
      if (qobj.id) {
        ecompany = await this.service.findById(qobj.id);
      }
      var rtn = null;
      if (ecompany) { //修改
        ecompany.name = qobj.name;
        ecompany.encryptkey = qobj.encryptkey || "";
        ecompany.posturl = qobj.posturl || "";
        ecompany.isEnabled = qobj.isEnabled;
        ecompany.owner_id = qobj.owner_id;
        await ecompany.save();
      } else { //新增
        var ecompany = {};
        ecompany.owner_id = req.session.user.id;
        ecompany.name = qobj.name;
        ecompany.encryptkey = qobj.encryptkey || "";
        ecompany.posturl = qobj.posturl || "";
        ecompany.isEnabled = qobj.isEnabled;
        ecompany.owner_id = qobj.owner_id;
        ecompany = await this.service.create(ecompany);
      }

      await this.ecompanybpoSve.saveCompanybpo(ecompany.id, mtchResult.data);

      return system.getResult2(ecompany, null);
    } catch (e) {
      console.log("-----------------------------e");
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

  async buildMtchs(mtchIdStr) {
    var result = {
      code : 1
    };
    var mtchIds = [];
    for(var mtchId of (mtchIdStr || "").split(",")) {
      if(mtchId && mtchId.trim()) {
        mtchIds.push(mtchId.trim());
      }
    }

    // 组织
    if(!mtchIds || mtchIds.length == 0) {
        return result;
    }

    // 获取bpo系统
    var mtchMap = await this.esettleSve.findByMtchIds(mtchIds);

    var bpos = [];

    var errMtchIds = [];
    for(var mtchId of mtchIds) {
      var mtchItem = mtchMap["id_" + mtchId];
      if(!mtchItem) {
        errMtchIds.push(mtchId);
      } else {
        bpos.push({
          mtchId: mtchId,
          mainId: mtchItem.mainId,
          companyName: mtchItem.companyName,
        });
      }
    }

    if(errMtchIds.length > 0) {
      result.code = 0;
      result.msg = "商户ID【" + errMtchIds.join("、") + "】不存在";
      return result;
    }

    result.data = bpos;
    return result;
   }


  async mySignList(queryobj, qobj, req) {
    var params = qobj.search;
    if(!req.session.myIds || req.session.myIds.length == 0) {
      params.ownerIds = [req.session.user.id];
    } else {
      params.ownerIds = req.session.myIds;
    }

    try {
      var page = await this.service.signPage(params);
      return system.getResult2(page);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    } 
  }


  async mySignSave(queryobj, qobj, req) {
    try {
      var ecompany = null;
      if (qobj.id) {
        ecompany = await this.service.findById(qobj.id);
      }
      var rtn = null;
      if (ecompany) { //修改
        ecompany.name = qobj.name;
        ecompany.encryptkey = qobj.encryptkey || "";
        ecompany.posturl = qobj.posturl || "";
        ecompany.isEnabled = qobj.isEnabled;
        ecompany.owner_id = req.session.user.id;
        await ecompany.save();
      } else { //新增
        var ecompany = {};
        ecompany.name = qobj.name;
        ecompany.encryptkey = qobj.encryptkey || "";
        ecompany.posturl = qobj.posturl || "";
        ecompany.isEnabled = qobj.isEnabled;
        ecompany.owner_id = req.session.user.id;
        ecompany = await this.service.create(ecompany);
      }

      return system.getResult2(ecompany, null);
    } catch (e) {
      console.log("-----------------------------e");
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

  async validName(queryobj, qobj, req) {
    var old;
    if(qobj.id) {
      old = await this.service.findById(qobj.id);
      if(old.name == qobj.name) {
        return system.getResult2(1);
      }
    }

    var intention = await this.eintentionSve.findOne({name:qobj.name});
    if(intention) {
      if(!qobj.owner_id) {
        return system.getErrResult2("该客户已被" + (intention.owner_name || "") + "录入为意向客户，请先录入归属人员后再次验证");
      } else if(qobj.owner_id != intention.owner_id) {
        return system.getErrResult2("该客户已被" + (intention.owner_name || "") + "录入为意向客户");
      } else {

      }
    }

    var ecompany = await this.service.findOne({name: qobj.name});
    if(old && ecompany) {
      var user = await this.userSve.findById(ecompany.owner_id);
      var nickName = "直营人员";
      if(user) {
        nickName = user.nickName;
      }
      return system.getErrResult2("该客户已被" + nickName + "录入");
    }

    if(ecompany) {
      var user = await this.userSve.findById(ecompany.owner_id);
      var nickName = "直营人员";
      if(user) {
        nickName = user.nickName;
      }
      return system.getErrResult2("该客户已被" + nickName + "录入");
    }

    return system.getResult2(1);
  }

  async authList(queryobj, qobj, req) {
    var params = qobj.search;
    this.doTimeCondition(params, ["applyBegin", "applyEnd", "authBegin", "authEnd"]);
    try {
      var page = await this.service.authPage(params);
      return system.getResult2(page);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    } 
  }

  async info(queryobj, qobj, req) {
    var id = qobj.id;
    try {
      var info = await this.service.getInfo(id);
      if(info) {
        var bpos = await this.ecompanybpoSve.findByECompanyId(id) || [];
        var mtchIds = [];
        for(var bpo of bpos) {
          mtchIds.push(bpo.mtchId);
        }
        info.mtchIds = mtchIds.join(",");

        if(info.owner_id) {
          info.owner = await this.userSve.findById(info.owner_id);
        }
        if(info.created_at) {
          info.created_at = moment(info.created_at).format("YYYY-MM-DD HH:mm:ss");
        }

        if(info.jdAuthApplyTime) {
          info.jdAuthApplyTime = moment(info.jdAuthApplyTime).format("YYYY-MM-DD HH:mm:ss");
        }

        if(info.jdAuthTime) {
          info.jdAuthTime = moment(info.jdAuthTime).format("YYYY-MM-DD HH:mm:ss");
        }
      }
      return system.getResult2(info);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    } 
  }

  async companyInfo(queryobj, qobj, req) {
    var id = qobj.id;
    try {
      var info = await this.service.getCompany(id) || {};
      return system.getResult2(info);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

  async wxsignCompany(queryobj, qobj, req) {
    var id = qobj.id;
    try {
      var info = await this.service.getCompany(id) || {};
      var etemplate = await this.etemplateSve.findOne({ecompany_id: id});
      if(etemplate) {
        info.nameA = etemplate.nameA;
      }
      return system.getResult2(info);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

  async jdAuth(queryobj, qobj, req) {
    try {
      var user = req.session.user;
      if (!user) {
        return system.getErrResult2('登录状态过期, 请刷新页面重新登录');
      }

      var id = Number(qobj.id);
      var rs = await this.service.jdAuth(id, qobj.auditStatus, this.trim(qobj.auditRemark), user.id);
      if(rs == -1) {
        return system.getErrResult2("企业不存在");
      }

      if(rs == -2) {
        return system.getErrResult2("认证失败, 企业已被认证");
      }

      if(rs == -3) {
        return system.getErrResult2("请填写驳回原因");
      }
      return system.getResult2(1);
    } catch (e) {
      console.log(e);
      return system.getErrResult2("您的网络不稳, 请稍后重试");
    }
  }

  async suggest(queryobj, qobj, req) {
    var name = this.trim(qobj.name);
    if(!name) {
      return system.getResult2([])
    }
    var ids = [];
    if(qobj.ismy) {
      ids.push(req.session.user.id);
    }
    
    var list = await this.service.suggest(name, ids);
    return system.getResult2(list);
  }
 
}
module.exports = EcompanyCtl;