const system = require("../../system");
const ServiceBase = require("../sve.base");
const moment = require("moment");
class EjobapplyService extends ServiceBase {
  constructor() {
    super(ServiceBase.getDaoName(EjobapplyService));
    this.usereaccountDao = system.getObject("db.usereaccountDao");
    this.smsClient = system.getObject("util.smsClient");
    this.ecompanyDao = system.getObject("db.ecompanyDao");
    this.ejobDao = system.getObject("db.ejobDao");
    this.emessageDao = system.getObject("db.emessageDao");
    this.ecompanyeventDao = system.getObject("db.ecompanyeventDao");
  }

  async info(id) {
    var apply = await this.dao.model.findOne({
      where: {
        id: id
      },
      raw: true
    });
    if (apply) {
      apply.eaccount = await this.usereaccountDao.getById(apply.usereaccount_id);
      // apply.ejob = await this.ejobDao.findById(apply.ejob_id);
    }
    return apply;
  }

  async notifyInterView(id, interviewTime) {
    var obj = await this.getApplyAll(id);
    var apply = obj.apply;
    if (!apply) {
      return 0;
    }
    var ejob = obj.ejob;
    if (!ejob) {
      return 0;
    }
    var ecompany = obj.ecompany;
    if (!ecompany) {
      return 0;
    }
    var eaccount = obj.eaccount;
    if (!eaccount || !/^1[23456789]\d{9}$/.test(eaccount.mobile)) {
      return 0;
    }

    apply.notifyTimes = Number(apply.notifyTimes || 0) + 1;
    await apply.save();

    // 7.通知面试：xxx（名字）您好，您于2019年04月03日申请的国美电器有限公司的促销员职位已通过初试，请于2019年04月10日前往朝阳区鹏润大厦进行面试，有问题请致电939473（公司电话）。
    var message = eaccount.userName + "您好，您于" + moment(apply.created_at).format("YYYY年MM月DD日") + "申请的" + ecompany.name + "的" + ejob.name + "职位已通过初试，请于" + interviewTime + "前往" + ejob.addr + "进行面试";
    if (ecompany.contractMobile && ecompany.telephone) {
      message = message + "，有问题请致电" + ecompany.contractMobile + "或" + ecompany.telephone + "。";
    } else if(!ecompany.contractMobile && ecompany.telephone) {
      message = message + "，有问题请致电" + ecompany.telephone + "。";
    } else if(ecompany.contractMobile && !ecompany.telephone) {
      message = message + "，有问题请致电" + ecompany.contractMobile + "。";
    } else {
      message = message + "。"
    }
    this.smsClient.sendMsg(eaccount.mobile, message);
  }

  async stat(params) {
    var sql = "SELECT COUNT(1) AS num FROM `c_ejob_apply` WHERE 1 = 1 ";
    if (params.ecompany_id) {
      sql = sql + " AND ecompany_id = :ecompany_id ";
    }
    if (params.begin) {
      sql = sql + " AND created_at >= :begin ";
    }
    if (params.end) {
      sql = sql + " AND created_at <= :end ";
    }
    if (params.statuses) {
      sql = sql + " AND `status` IN (:statuses) ";
    }
    var list = await this.customQuery(sql, params);

    if (!list || list.length == 0) {
      return 0;
    }
    return list[0].num || 0;
  }

  async pageUserByCondition(params) {
    var currentPage = Number(params.currentPage || 1);
    var pageSize = Number(params.pageSize || 10);

    var startRow = (currentPage - 1) * pageSize;

    var countSql = [];
    countSql.push("SELECT COUNT(DISTINCT t1.usereaccount_id) AS total FROM c_ejob_apply t1 ");
    countSql.push("INNER JOIN p_user_eaccount t2 ON t2.id = t1.usereaccount_id ");
    countSql.push("WHERE 1 = 1 ");

    var listSql = [];
    listSql.push("SELECT ");
    listSql.push("GROUP_CONCAT(t1.ejob_id) AS jobIds, t2.id, t2.mobile, t2.userName, t2.personsSign, t2.bankno, t2.email, ");
    listSql.push("t2.sex, t2.sexName, t2.identity, t2.identityName, t2.age, t2.height, t2.edu, t2.eduName, t2.adv, ");
    listSql.push("t2.experience, t2.created_at, t2.user_id FROM c_ejob_apply t1 ");
    listSql.push("INNER JOIN p_user_eaccount t2 ON t2.id = t1.usereaccount_id ");
    listSql.push("WHERE 1 = 1 ");

    if (params.ecompany_id) {
      countSql.push(" AND t1.ecompany_id = :ecompany_id ");
      listSql.push(" AND t1.ecompany_id = :ecompany_id");
    }

    if (params.applyStatuses) {
      countSql.push(" AND t1.status IN (:applyStatuses) ");
      listSql.push(" AND t1.status IN (:applyStatuses) ");
    }

    if(params.applyId) {
      countSql.push(" AND t1.id = :applyId ");
      listSql.push(" AND t1.id = :applyId ");
    }

    if(params.userName) {
      countSql.push(" AND t2.userName LIKE :userNameLike ");
      listSql.push(" AND t2.userName LIKE :userNameLike ");
      params.userNameLike = "%" + params.userName +"%"
    }
    if(params.mobile) {
      countSql.push(" AND t2.mobile = :mobile ");
      listSql.push(" AND t2.mobile = :mobile ");
    }
    if(params.identityType) {
      countSql.push(" AND t2.identityType = :identityType ");
      listSql.push(" AND t2.identityType = :identityType ");
    }
    if(params.sex) {
      countSql.push(" AND t2.sex = :sex ");
      listSql.push(" AND t2.sex = :sex ");
    }
    if(params.edu) {
      countSql.push(" AND t2.edu = :edu ");
      listSql.push(" AND t2.edu = :edu ");
    }
    if(params.age) {
      countSql.push(" AND t2.age = :age ");
      listSql.push(" AND t2.age = :age ");
    }
    if(params.height) {
      countSql.push(" AND t2.height = :height ");
      listSql.push(" AND t2.height = :height ");
    }

    listSql.push(" GROUP BY t1.usereaccount_id ORDER BY t2.id DESC ");
    listSql.push(" LIMIT " + startRow +  ", " + pageSize + " ");

    var countrs = await this.customQuery(countSql.join(" "), params);

    if(!countrs || countrs.length == 0 || !countrs[0].total) {
      return {
        count: 0,
        rows: []
      };
    }
    var total = countrs[0].total;

    var list = await this.customQuery(listSql.join(" "), params);

    var jobIds = [];
    for (var row of list) {
      var jobIdArr = (row.jobIds || "").split(",");
      if(jobIdArr.length > 0) {
        for(var jid of jobIdArr) {
          jobIds.push(jid);
        }
      }
    }

    var jobMap = await this.ejobDao.findMapByIds(jobIds, " id, name ");

    for (var row of list) {
      this.handleDate(row, ["audit_at", "apply_at", "sign_at", "cancel_at"]);
      var jobIdArr = (row.jobIds || "").split(",");
      if(jobIdArr.length > 0) {
        var nameArr = [];
        for(var jid of jobIdArr) {
          var ejob = jobMap["id_" + jid];
          if(ejob && ejob.name && nameArr.indexOf(ejob.name) == -1) {
            nameArr.push(ejob.name);
          }
        }
        row.jobNames = nameArr.join("、");
      }
    }
    return {count: total, rows: list};
  }

  async pageByCondition(params) {
    var currentPage = Number(params.currentPage || 0);
    var pageSize = Number(params.pageSize || 10);

    var where = {};

    if (params.userName || params.mobile || params.identityType || params.sex || params.edu || params.age || params.height) {
      var userParams = {
        userName: params.userName || "",
        mobile: params.mobile || "",
        identityType: params.identityType || "",
        sex: params.sex || "",
        edu: params.edu || "",
        age: params.age || "",
        height: params.height || "",
      }
      if (params.ecompany_id || params.ejob_id) {
        var accountIds = await this.dao.findAccountIds(params.ecompany_id, params.ejob_id);
        if (!accountIds || accountIds.length == 0) {
          return {
            count: 0,
            rows: []
          };
        }
        userParams.ids = accountIds;
      }
      var usereaccountIds = await this.usereaccountDao.idsByCondition(userParams);
      if (!usereaccountIds || usereaccountIds.length == 0) {
        return {
          count: 0,
          rows: []
        };
      }
      where.usereaccount_id = {
        [this.db.Op.in]: usereaccountIds
      };
    }

    if (params.ecompany_id) {
      where.ecompany_id = params.ecompany_id;
    }

    if (params.ejob_id) {
      where.ejob_id = params.ejob_id;
    }

    if (params.applyStatus) {
      where.status = params.applyStatus;
    }

    if(params.applyId) {
      where.id = params.applyId;
    }

    this.addWhereTime(where, 'created_at', params.applyBegin, params.applyEnd, true);
    this.addWhereTime(where, 'sign_at', params.signBegin, params.signEnd, true);
    this.addWhereTime(where, 'audit_at', params.auditBegin, params.auditEnd, true);
    this.addWhereTime(where, 'cancel_at', params.cancelBegin, params.cancelEnd, true);

    var orderby = [
      ["id", 'desc']
    ];

    var attributes = ["id", "ecompany_id", "ejob_id", "econtract_id", "user_id", "usereaccount_id", "status",
      "statusName", "audit_at", "auditRemark", "notifyTimes", "apply_at", "sign_at", "cancel_at", "created_at"
    ];

    var page = await this.getPageList(currentPage, pageSize, where, orderby, attributes);
    if (page && page.rows) {
      await this.setEaccount(page.rows);
      if(params.needJob) {
        await this.setJob(page.rows);
      }
      for (var row of page.rows) {
        this.handleDate(row, ["audit_at", "apply_at", "sign_at", "cancel_at"]);
      }
    }
    return page;
  }

  async getApplyAll(id) {
    var result = {};
    var apply = await this.findById(id);
    if (!apply) {
      return result;
    }
    result.apply = apply;
    result.ejob = await this.ejobDao.findById(apply.ejob_id);
    result.ecompany = await this.ecompanyDao.findById(apply.ecompany_id);
    result.eaccount = await this.usereaccountDao.getById(apply.usereaccount_id);
    return result;
  }

  async setEaccount(list) {
    if (!list || list.length == 0) {
      return;
    }

    var ids = [];
    for (var item of list) {
      ids.push(item.usereaccount_id);
    }
    var attrs = " `id`, `mobile`, `userName`, `email`, `sex`, `sexName`, `identity`, `identityName`, `age`, `height`, `edu`, `eduName`, `adv` ";
    var accountMap = await this.usereaccountDao.findMapByIds(ids, attrs);

    for (var item of list) {
      item.eaccount = accountMap["id_" + item.usereaccount_id];
    }
  }

  async setJob(list) {
    if (!list || list.length == 0) {
      return;
    }

    var ids = [];
    for (var item of list) {
      ids.push(item.ejob_id);
    }
    var attrs = " `id`, `name` ";
    var jobMap = await this.ejobDao.findMapByIds(ids, attrs);

    for (var item of list) {
      item.ejob = jobMap["id_" + item.ejob_id];
    }
  }

  async audit(id, auditStatus, auditRemark) {
    var obj = await this.getApplyAll(id);
    var apply = obj.apply;
    if (!apply || apply.status != '0') {
      return 0;
    }
    var ejob = obj.ejob;
    if (!ejob) {
      return 0;
    }
    var ecompany = obj.ecompany;
    if (!ecompany) {
      return 0;
    }
    var eaccount = obj.eaccount;
    if (!eaccount || !/^1[23456789]\d{9}$/.test(eaccount.mobile)) {
      return 0;
    }
    // 【薪必果】您于2019年04月03日申请的促销员职位已成功，请尽快前往小程序进行签约。／【薪必果】您于2019年04月03日申请的促销员职位由于xx未成功，可尽快前往薪必果小程序申请相似职位。
    var message = "【薪必果】您于" + moment(apply.created_at).format("YYYY年MM月DD日") + "申请的" + ecompany.name + "的" + ejob.name + "职位";

    if(auditStatus == '1') {
      apply.status = auditStatus;
      apply.statusName = "待签约";
      apply.audit_at = new Date();
      message = message + "已成功，请尽快前往小程序进行签约。";
    } else if(auditStatus == "6") {
      apply.status = auditStatus;
      apply.statusName = "已驳回";
      apply.audit_at = new Date();
      apply.auditRemark = auditRemark || "";
      message = message + "由于" + apply.auditRemark + "未成功，可尽快前往薪必果小程序申请相似职位。";
    } else {
      return 0;
    }
    await apply.save();
    this.smsClient.sendMsg(eaccount.mobile, message);

    this.ecompanyeventDao.doBiz(apply.id, 1);
    return 1;
  }

  async addMessage(applyId, title, actionName) {
    var apply = await this.findById(applyId);
    if(!apply) {
      return;
    }

    var ejob = await this.ejobDao.findById(apply.ejob_id);
    if(!ejob) {
      return;
    }
    var ecompany = await this.ecompanyDao.findById(apply.ecompany_id);
    if(!ecompany || !ecompany.user_id) {
      return;
    }
    var account = await this.usereaccountDao.findById(apply.usereaccount_id);
    if(!account) {
      return;
    }

    if(ecompany.user_id) {
      var created_at = moment(ejob.created_at).format("YYYY-MM-DD HH:mm:ss");
      var msg = account.userName + "已" + actionName + "您" + created_at + "发布的【" + ejob.name + "】";
      await this.emessageDao.create({
        user_id : ecompany.user_id,
        type : 5,
        title : title,
        read : 0,
        content : msg
      });
    }
  }

  async getIdsByStatus(statusList) {
    var result = [];
    if(!statusList || statusList.length == 0) {
      return result;
    }

    var sql = "SELECT id FROM `c_ejob_apply` WHERE status IN (:statusList) ";
    var list = await this.customQuery(sql, {statusList: statusList});
    if(list) {
      for(var item of list) {
        result.push(item.id);
      }
    }
    return result;
  }
}

module.exports = EjobapplyService;