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 EsettlecommissionCtl extends CtlBase {
  constructor() {
    super(CtlBase.getServiceName(EsettlecommissionCtl));
    this.userSve = system.getObject("service.userSve");
    this.epartnerSve = system.getObject("service.epartnerSve");
  }


  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: []});
      }
      qobj.userIds = req.session.myIds;
    }
    
    return await this.list(queryobj, qobj, req, params);
  }

  async myList(queryobj, qobj, req) {
    qobj.userIds = [req.session.user.id]
    return await this.list(queryobj, qobj, req, {});
  }

  async list(queryobj, qobj, req, params) {
    // if (!params) {
    //   return null;
    // }

    if (!qobj.search) {
      qobj.search = {};
    }

    // if (params) {
    //   if (params.user_id) {
    //     qobj.search.user_id = params.user_id;
    //   }
    // }
    qobj.raw = true;
    var rs = await super.findAndCountAll(queryobj, qobj, req);

    if (rs && rs.data && rs.data.rows) {
      var epartnerIds = [];

      system.f2y4list(rs.data.rows, ["amt","service_tax","commission"], "¥ ");
      for (var row of rs.data.rows) {
        if(row.epartner_id) {
          epartnerIds.push(row.epartner_id);
        }
        if (row.pay_complete_time) {
          row.pay_complete_time = new Date(row.pay_complete_time).Format("yyyy-MM-dd hh:mm:ss");
        }
      }

      var partnerMap = await this.epartnerSve.findMapByIds(epartnerIds);
      for (var row of rs.data.rows) {
        if(row.epartner_id) {
          row.epartner = partnerMap["id_" + row.epartner_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;
  }
}
module.exports = EsettlecommissionCtl;