var system = require("../../system")
var settings = require("../../../config/settings");
const CtlBase = require("../ctl.base");
const uuidv4 = require('uuid/v4');
var moment = require('moment');
const Sequelize = require('sequelize');
const uiconfig = system.getUiConfig2(settings.wxconfig.appId);
class EpartnerCtl extends CtlBase {
  constructor() {
    super(CtlBase.getServiceName(EpartnerCtl));
    this.Op = Sequelize.Op;

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

    this.epartneradvSve = system.getObject("service.epartneradvSve");
    this.regionareaSve = system.getObject("service.regionareaSve");

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

    this.ecompanySve = system.getObject("service.ecompanySve");
    this.esettlecommissionSve = system.getObject("service.esettlecommissionSve");
    this.esettleSve = system.getObject("service.esettleSve");
  }

  async info(queryobj, qobj, req) {
    let user = req.session.user;
    user.department = req.session.department;
    var result = {
      user: user,
      epartner: req.session.partner,
    }
    return system.getResult2(result);
  }

  async updatePwd(queryobj, qobj, req) {
    var getOldPwd = qobj.oldPwd;
    var getNewPwd = qobj.newPwd;
    var getConfPwd = qobj.confPwd;

    if (getNewPwd != getConfPwd) {
      return system.getErrResult2("两次输入密码不一致!");
    }

    var user = await this.userSve.findById(req.session.user.id);
    if (user.password != super.encryptPasswd(getOldPwd)) {
      return system.getErrResult2("当前密码输入有误!");;
    }

    user.password = super.encryptPasswd(getNewPwd);
    await user.save();
    return system.getResult2(1);
  }

  async apply(queryobj, qobj, req) {
    var userName = super.trim(qobj.userName);
    var mobile = super.trim(qobj.mobile);
    var city = super.trim(qobj.city);
    var advList = qobj.advList || [];
    if (!userName) {
      return system.getErrResult2("请输入姓名");
    }
    if (userName.length > 20) {
      return system.getErrResult2("姓名不能超过20个字");
    }
    if (!mobile) {
      return system.getErrResult2("请输入手机号");
    }
    if (!/^1[23456789]\d{9}$/.test(mobile)) {
      return system.getErrResult2("手机号格式不正确");
    }

    if (city.length > 20) {
      return system.getErrResult2("城市太长了");
    }
    var epartner = await this.userSve.findPartnerUser(mobile)
    if (epartner) {
      return system.getErrResult2("您已经提交申请, 请耐心等待审核");
    }
    var puser = await this.userSve.findOne({
      userName: mobile
    });
    if (puser) {
      return system.getErrResult2("您的手机号已注册");
    }

    epartner = {
      nickName: userName,
      userName: mobile,
      mobile: mobile,
      city: city,
      partnerSourceType: '0',
      partnerSourceTypeName: '自然流量',
      partnerType: '0',
      partnerTypeName: '初级',
      intro: "",
      subCount: 0,
      dealCount: 0,
      audit_id: 0,
      owner_id: 0,
      auditStatus: '0',
      auditStatusName: '待审核',
      audit_id: 0,
      isEnabled: 1,
      advNames: advList.join(",")
    }

    var rs = await this.service.create(epartner);
    if (rs) {
      var id = rs.id;
      if (advList.length > 0) {
        for (var adv of advList) {
          this.epartneradvSve.create({
            epartner_id: id,
            name: adv
          });
        }
      }
    }
    return system.getResult2(1);
  }

  async mysave(queryobj, qobj, req) {
    try {
      var epartner = null;
      let id = qobj.id;
      if (id) {
        epartner = await this.service.findById(id);
      }
      var loginUser = req.session.user;
      var repeatUser = await this.userSve.findPartnerUser(qobj.userName);

      var pcode = "";
      var ccode = "";
      if (qobj.cityCode) {
        qobj.city = 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];
        }
      }

      if (epartner) {
        //修改
        console.log("edit++++++++++++++++++++++++++++++++++++");
        if (repeatUser && epartner.user_id != repeatUser.id) {
          return system.getErrResult2("合伙人账户已存在, 请修改后再提交");
        }
        epartner.nickName = qobj.nickName;
        epartner.mobile = qobj.mobile;
        epartner.partnerUserType = qobj.partnerUserType;
        epartner.city = qobj.city;
        epartner.cityCode = qobj.cityCode;
        epartner.pcode = pcode;
        epartner.ccode = ccode;
        epartner = await epartner.save();
        if (repeatUser) {
          repeatUser.nickName = qobj.nickName;
          repeatUser.mobile = qobj.mobile;
          repeatUser.userName = qobj.userName;
          repeatUser.save();
        }

      } else {
        var userRoles = loginUser.Roles || [];
        var roles = [];
        if (userRoles) {
          for (var ur of userRoles) {
            roles.push(ur.code);
          }
        }
        // 验证手机号是否存在
        if (repeatUser) {
          return system.getErrResult2("合伙人账户已存在, 请修改后再提交");
        }

        epartner = {
          nickName: qobj.nickName,
          userName: qobj.userName,
          mobile: qobj.mobile,
          partnerUserType: qobj.partnerUserType,
          city: qobj.city,
          cityCode: qobj.cityCode,
          pcode: pcode,
          ccode: ccode,
          partnerType: '1',
          partnerTypeName: '初级',
          intro: "",
          subCount: 0,
          dealCount: 0,
          audit_id: 0,
          owner_id: 0,
          auditStatus: '0',
          auditStatusName: '待审核',
          audit_id: 0,
          isEnabled: 1,
          advNames: ""
        }

        if (roles.indexOf("partner") > -1) {
          // 一级合伙人，通过一级合伙人分裂开发的合伙人，为2级。
          epartner.partnerSourceType = '1';
          epartner.partnerSourceTypeName = "合伙人上级";
          epartner.partnerLevel = '2';
          epartner.partnerLevelName = '二级';
          epartner.sourceId = loginUser.id;
          if (req.session.partner) {
            epartner.sourcePartnerId = req.session.partner.id;
          }
        } else {
          epartner.partnerSourceType = '2';
          epartner.partnerSourceTypeName = "市场人员";
          epartner.partnerLevel = '1';
          epartner.partnerLevelName = '一级';
          epartner.sourceId = loginUser.id;
        }

        console.log("new++++++++++++++++++++++++++++++++++++");
        epartner = await this.service.create(epartner);
      }

      return system.getResult2(epartner, null);
    } catch (e) {
      console.log(e);
      return {
        code: -1
      }
    }
  }

  async allList(queryobj, qobj, req) {
    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.sourceIds = req.session.myIds;
    }

    return await this.list(queryobj, qobj, req, {});
  }

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


  async toauditList(queryobj, qobj, req) {
    return await this.list(queryobj, qobj, req, {
      auditType: 1
    });
  }

  async passList(queryobj, qobj, req) {
    return await this.list(queryobj, qobj, req, {
      auditType: 2
    });
  }

  async rejectList(queryobj, qobj, req) {
    return await this.list(queryobj, qobj, req, {
      auditType: 3
    });
  }

  async list(queryobj, qobj, req, params) {
    // 1待审核 2通过 3驳回
    // "proxyAuditStatus" : {"0":"待审核","1":"审核通过","2":"审核驳回"},
    if (!qobj.search) {
      qobj.search = {};
    }
    var auditType;
    if (params) {
      if (params.auditType) {
        qobj.search.auditStatus = (params.auditType - 1).toString();
      }
    }

    var cityCode = qobj.search.cityCode;
    if (cityCode && cityCode.trim()) {
      delete qobj.search['cityCode'];

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


    var customizedWhereObj = {};
    var sourceUserName = qobj.search.sourceUserName;
    if (sourceUserName && sourceUserName.trim()) {
      delete qobj.search['sourceUserName'];
      // p_user
      var sourceIds = await this.userSve.idsLikeNickName(sourceUserName);
      if (sourceIds.length == 0) {
        return system.getResult2({
          "count": 0,
          "rows": []
        });
      }

      // c_epartner
      var sourcePartnerIds = await this.service.idsLikeNickName(sourceUserName);
      if (sourcePartnerIds.length == 0) {
        return system.getResult2({
          "count": 0,
          "rows": []
        });
      }

      customizedWhereObj[this.Op.or] = [{
          sourceId: {
            [this.Op.in]: sourceIds
          }
        },
        {
          sourcePartnerId: {
            [this.Op.in]: sourcePartnerIds
          }
        }
      ];

      qobj.customizedWhereObj = customizedWhereObj;
    }

    qobj.raw = true;
    var rs = await super.findAndCountAll(queryobj, qobj, req);

    if (rs && rs.data && rs.data.rows) {
      var userIds = [];
      var sourcePartnerIds = [];
      for (var row of rs.data.rows) {
        if (row.reg_at) {
          row.reg_at = new Date(row.reg_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.sourceId) {
          userIds.push(row.sourceId);
        }
        if (row.sourcePartnerId) {
          sourcePartnerIds.push(row.sourcePartnerId);
        }
      }

      var usermap = await this.userSve.findMapByIds(userIds);
      var partnermap = await this.service.findMapByIds(sourcePartnerIds);

      for (var row of rs.data.rows) {
        if (row.reg_at) {
          row.reg_at = new Date(row.reg_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");
        }
        row.sourceUserName = "";
        if (row.sourceId) {
          row.sourceUser = usermap["id_" + row.sourceId];
          row.sourceUserName = row.sourceUser ? row.sourceUser.nickName : "";
        }

        if (row.sourcePartnerId) {
          row.sourcePartner = partnermap["id_" + row.sourcePartnerId];
          row.sourceUserName = row.sourcePartner ? row.sourcePartner.nickName : "";
        }
      }
    }
    return rs;
  }

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

    for (var id of ids) {
      try {
        await this.service.auditPass(id, req.session.user.id);
      } 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 epartner = await this.service.findById(id);
        if (epartner.auditStatus != '0') {
          return system.getErrResult2("该合伙人已审核");
        }

        epartner.audit_id = req.session.user.id;
        epartner.auditStatus = '2';
        epartner.auditStatusName = '审核驳回';
        await epartner.save();
      } catch (error) {
        console.error(error);
      }
    }

    return system.getResult2('1');
  }

  async upgrade(queryobj, qobj, req) {
    var user = req.session.user;
    var id = user.id;

    var roles = user.Roles || [];
    var roleCodes = [];
    for (var role of roles) {
      roleCodes.push(role.code);
    }
    if (roleCodes.indexOf("partner") == -1) {
      return system.getErrResult2("您还不是合伙人");
    }

    var epartner = await this.service.findOne({
      user_id: id
    });
    if (!epartner) {
      return system.getErrResult2("您还不是合伙人");
    }

    var targetType = '';
    var targetName = '';
    var currentType = epartner.partnerType;
    var currentName = epartner.partnerTypeName;

    if (currentType == '2') {
      return system.getErrResult2("您已经是最高级合伙人了");
    } else if (currentType == '0') {
      if (epartner.dealCount < 2) {
        return system.getErrResult2("您需要成功提成两个客户,才可以申请成为中级合伙人");
      }
      targetType = "1";
      targetName = "中级";
    } else if (currentType == '1') {
      if (epartner.dealCount < 4) {
        return system.getErrResult2("您需要成功提成四个客户,才可以申请成为高级合伙人");
      }
      targetType = "2";
      targetName = "高级";
    }
    var audit = await this.epartnerupgradeauditSve.findOne({
      epartner_id: epartner.id,
      auditStatus: '0'
    });
    if (audit) {
      return system.getErrResult2("您已经提交申请成为" + audit.targetTypeName + "合伙人审核, 请耐心等待");
    }

    audit = {
      nickName: epartner.nickName,
      mobile: epartner.mobile,
      epartner_id: epartner.id,
      sourceType: currentType,
      sourceTypeName: currentName,
      targetType: targetType,
      targetTypeName: targetName,
      auditStatus: '0',
      auditStatusName: '待审核',
      audit_id: 0
    }

    await this.epartnerupgradeauditSve.create(audit);
    return system.getResult2('1');
  }

  async mystat(queryobj, qobj, req) {
    var id = req.session.user.id;
    var whereObj = {
      user_id: id
    };

    var b, e;
    if (qobj.beginTime) {
      b = moment(qobj.beginTime).format("YYYY-MM-DD") + " 00:00:00";
    }

    if (qobj.endTime) {
      e = moment(qobj.endTime).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
    }

    if (b && e) {
      whereObj.pay_complete_time = {
        [this.Op.between]: [b, e]
      };
    } else if (b && !e) {
      whereObj.pay_complete_time = {
        [this.Op.gte]: b
      };
    } else if (!b && e) {
      whereObj.pay_complete_time = {
        [this.Op.lte]: e
      };
    }

    // 我的客户
    var myCompanyCount = await this.ecompanySve.findCount({
      where: {
        owner_id: id
      }
    });
    // 我的合伙人
    var myPartnerCount = await this.service.findCount({
      where: {
        sourceId: id
      }
    });
    // 我的客户提成
    whereObj.commissionSource = '0';
    var myCompanyCommssionCount = await this.esettlecommissionSve.findSum('commission', {
      where: whereObj
    });
    // 我的合伙人提成
    whereObj.commissionSource = '1';
    var myPartnerCommssionCount = await this.esettlecommissionSve.findSum('commission', {
      where: whereObj
    });

    var result = {
      myCompanyCount: myCompanyCount,
      myPartnerCount: myPartnerCount,
      myCompanyCommssionCount: system.f2y(myCompanyCommssionCount),
      myPartnerCommssionCount: system.f2y(myPartnerCommssionCount),
    };

    return system.getResult2(result);
  }

  async totalstat(queryobj, qobj, req) {
    var id = req.session.user.id;
    var whereObj = {};
    var roles = req.session.user.Roles || [];
    if(!req.session.user.isAdmin && roles.indexOf("Manager") == -1 && roles.indexOf("") == -1
        && roles.indexOf("zcgl") == -1 && roles.indexOf("qdgl") == -1 && roles.indexOf("ptgl") == -1) {
      return system.getResult2({auth: false});
    }
    var b, e;
    if (qobj.beginTime) {
      b = moment(qobj.beginTime).format("YYYY-MM-DD") + " 00:00:00";
    }

    if (qobj.endTime) {
      e = moment(qobj.endTime).add(1, "months").subtract(1, 'days').format("YYYY-MM-DD") + " 23:59:59";
    }

    if (b && e) {
      whereObj.pay_complete_time = {
        [this.Op.between]: [b, e]
      };
    } else if (b && !e) {
      whereObj.pay_complete_time = {
        [this.Op.gte]: b
      };
    } else if (!b && e) {
      whereObj.pay_complete_time = {
        [this.Op.lte]: e
      };
    }

    // 总发薪额
    var totalAmt = await this.esettleSve.findSum('amt', {
      where: whereObj
    });
    // 总服务费
    var totalSericeTax = await this.esettleSve.findSum('service_tax', {
      where: whereObj
    });
    // 总客户提成
    whereObj.commissionSource = '0';
    var totalCompanyCommssionCount = await this.esettlecommissionSve.findSum('commission', {
      where: whereObj
    });
    // 总合伙人提成
    whereObj.commissionSource = '1';
    var totalPartnerCommssionCount = await this.esettlecommissionSve.findSum('commission', {
      where: whereObj
    });

    var result = {
      auth: true,
      totalAmt: system.f2y(totalAmt),
      totalSericeTax: system.f2y(totalSericeTax),
      totalCompanyCommssionCount: system.f2y(totalCompanyCommssionCount),
      totalPartnerCommssionCount: system.f2y(totalPartnerCommssionCount),
    };
    return system.getResult2(result);
  }

  async suggest(queryobj, qobj, req) {
    var name = this.trim(qobj.name);
    if (!name) {
      return system.getResult2([])
    }

    var list = await this.service.suggest(name);
    return system.getResult2(list);
  }
}
module.exports = EpartnerCtl;