var system = require("../../system")
var settings = require("../../../config/settings");
const CtlBase = require("../ctl.base");
const uuidv4 = require('uuid/v4');
const uiconfig = system.getUiConfig2(settings.wxconfig.appId);
class EpartnerupgradeauditCtl extends CtlBase {
  constructor() {
    super(CtlBase.getServiceName(EpartnerupgradeauditCtl));
    this.userSve = system.getObject("service.userSve");

    this.epartnerSve = system.getObject("service.epartnerSve");
  }

  async auditList(queryobj, qobj, req) {
    qobj.raw = true;
    var rs = await this.findAndCountAll(queryobj, qobj, req);

    // 补全合伙人数据
    if (!rs || !rs.data || !rs.data.rows) {
      return rs;
    }

    var partnerIds = [];
    for (var row of rs.data.rows) {
      if (row.epartner_id) {
        partnerIds.push(row.epartner_id);
      }
    }

    var partnerMap = await this.epartnerSve.findMapByIds(partnerIds);
    for (var row of rs.data.rows) {
      row.epartner = partnerMap["id_" + row.epartner_id];
      if(row.epartner && row.epartner.reg_at) {
        row.epartner.reg_at = new Date(row.epartner.reg_at).Format("yyyy-MM-dd hh:mm");
      }
    }
    return rs;
  }


  async pass(queryobj, qobj, req) {
    var ids = qobj.ids || [];
    for (var id of ids) {
      try {
        var audit = await this.service.findById(id);
        if (!audit) {
          return system.getErrResult2("审核信息不存在");
        }
        if (audit.auditStatus != '0') {
          return system.getErrResult2("该信息已审核");
        }

        var epartner = await this.epartnerSve.findById(audit.epartner_id);
        if (!epartner) {
          return system.getErrResult2("合伙人不存在");
        }

        epartner.partnerType = audit.targetType;
        epartner.partnerTypeName = audit.targetTypeName;

        audit.auditStatus = '1';
        audit.auditStatusName = '审核通过';
        audit.audit_id = req.session.user.id;
        audit.audit_at = new Date();

        await epartner.save();
        await audit.save();
      } catch (error) {
        console.error(error);
      }
    }

    return system.getResult2("1");
  }

  async reject(queryobj, qobj, req) {
    var ids = qobj.ids || [];

    for (var id of ids) {
      try {
        var audit = await this.service.findById(id);
        if (!audit) {
          return system.getErrResult2("审核信息不存在");
        }
        if (audit.auditStatus != '0') {
          return system.getErrResult2("该信息已审核");
        }

        var epartner = await this.epartnerSve.findById(audit.epartner_id);
        if (!epartner) {
          return system.getErrResult2("合伙人不存在");
        }

        audit.auditStatus = '2';
        audit.auditStatusName = '审核驳回';
        audit.audit_id = req.session.user.id;
        audit.audit_at = new Date();

        await audit.save();
      } catch (error) {
        console.error(error);
      }
    }
    return system.getResult2('1');
  }

}
module.exports = EpartnerupgradeauditCtl;