const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");

/**
 * 供人信息
 */
class LabourService extends ServiceBase {
  constructor() {
    super("operator", ServiceBase.getDaoName(LabourService));
    this.usersDao = system.getObject("db.operator.usersDao");
    this.userlabourDao = system.getObject("db.operator.userlabourDao");
  }

  async SaveLabourInfo(params) {//添加或更新招聘信息
    var id = params.id;
    var labour;
    if (id) {
      labour = await this.dao.findById(id);
      labour.labour_type = params.labour_type;
      labour.labour_count = params.labour_count;
      labour.age_range = params.age_range;
      labour.sex_ratio = params.sex_ratio;
      labour.labour_address = params.labour_address;
      labour.report_date = params.report_date;
      labour.work_address = params.work_address;
      labour.situation_memo = params.situation_memo;
      labour.phone_no = params.phone_no;
      labour.user_id = params.user_id;
      labour.publish_date = params.publish_date;
      labour.pic_path = params.pic_path;
      labour = await labour.save();
      labour = await this.dao.findById(id);
    } else {
      labour = await this.dao.create(params);
    }

    return system.getResultSuccess(labour);
  }

  async findAllList(obj) {//获取全部供人信息，返回符合条件的列表
    var pageSize = obj.page_size || 10;
    var currentPage = obj.current_page || 1;
    try {
      var sqlwhere = {
        order: [["publish_date", 'desc']],
        limit: pageSize,
        offset: (currentPage - 1) * pageSize,
        raw: true
      };
      var list = await this.dao.model.findAndCountAll(sqlwhere) || [];
      return system.getResult(list);
    } catch (e) {
      console.log(e);
      return system.getResult(null, "操作失败");
    }
  }

  async findListByUserid(obj) {//获取userid供人信息，返回符合条件的列表
    if (!obj.user_id) {
      return system.getResult(null, "参数错误!");
    }
    var user_id = obj.user_id;
    var pageSize = obj.page_size || 10;
    var currentPage = obj.current_page || 1;
    try {
      var sqlwhere = {
        where: {user_id: user_id},
        order: [["publish_date", 'desc']],
        limit: pageSize,
        offset: (currentPage - 1) * pageSize,
        raw: true
      };
      var list = await this.dao.model.findAndCountAll(sqlwhere) || [];
      return system.getResult(list);
    } catch (e) {
      console.log(e);
      return system.getResult(null, "操作失败");
    }
  }

  async findlabourByWhere(obj) {//根据条件获取招工信息
    var pageSize = obj.page_size || 10;
    var currentPage = obj.current_page || 1;
    var user_id = Number(obj.userId);
    var where = {};
    if (obj.id) {
      where.id = obj.id;
    }
    if (obj.user_id) {
      where.user_id = obj.user_id;
    }
    if (obj.phone_no) {
      where.phone_no = obj.phone_no;
    }
    if (obj.labour_type && obj.labour_type != "全部") {
      where.labour_type = obj.labour_type;
    }
    if (obj.work_address && obj.work_address != "全部") {
      where.work_address = obj.work_address;
    }
    if (obj.cur_status && obj.cur_status != "全部") {
      where.cur_status = obj.cur_status;
    }

    try {
      var sqlwhere = {
        where: where,
        order: [["publish_date", 'desc']],
        limit: pageSize,
        offset: (currentPage - 1) * pageSize,
        raw: true
      };
      var list = await this.dao.model.findAndCountAll(sqlwhere) || [];
      if (list) {
        await this.setUserInfo(list.rows);

        let labourIds = await this.userlabourDao.findLabourIdsByUserId(user_id) || [];
        for (var item of list.rows) {
          item.showNotify = labourIds.indexOf(item.id) == -1;
          if (item.showNotify && item.phone_no) {
            item.phone_no = item.phone_no.replace(/^(\d{3})\d{4}(\d{0,10})$/, "$1****$2");
          }
        }
      }
      return system.getResult(list);
    } catch (e) {
      console.log(e);
      return system.getResult(null, "操作失败");
    }
  }

  async notifyInterview(obj) {
    let id = Number(obj.id);
    let user_id = Number(obj.userId);
    let recruit_id = Number(obj.recruit_id);

    // 查询用户
    let labour = await this.dao.findById(id);
    if(!labour) {
      return system.getResult(null, "人才不存在");
    }

    let userLabour = {
      user_id: user_id,
      labour_id: id,
      recruit_id: recruit_id,
      labour_user_id: labour.user_id,
      ecid: 0,
      apply_stauts: "20",
      interview_time: new Date(),
      contract_url: "",
    };
    userLabour = await this.userlabourDao.create(userLabour);
    return userLabour;
  }

  async updatestatus(obj) {//更新状态信息
    try {
      var whereobj = {where: {id: obj.id}};
      var setobj = {};
      setobj.cur_status = obj.cur_status;
      if (obj.cur_status == "展示中") {
        setobj.cur_type = 1;
      } else if (obj.cur_status == "已下架") {
        setobj.cur_type = 2;
      } else if (obj.cur_status == "已过期") {
        setobj.cur_type = 3;
      } else if (obj.cur_status == "审核未通过") {
        setobj.cur_type = 4;
      }

      var self = this;
      var v = await this.db.transaction(async function (t) {
        await self.dao.updateByWhere(setobj, whereobj, t);
      });

      return 1;
    } catch (e) {
      console.log(e);
      return 0;
    }
  }

  /**
   * 删除用户下制定 招聘或这是供招信息记录
   * @param {*} params
   */
  async RemRecOrLob(params) {
    try {
      let res = await this.dao.model.destroy({
        where: {
          id: params.id,
          user_id: params.userId
        }
      });
      return system.getResult(res);
    } catch (error) {
      return system.getResult(-1, `系统错误 错误信息 ${error}`);
    }
  }

  async setUserInfo(rows) {
    if (!rows || rows.length == 0) {
      return;
    }
    var ids = [];
    for (var row of rows) {
      ids.push(row.user_id);
    }
    var map = await this.usersDao.findUserInfoByids(ids);
    for (var row of rows) {
      row.userInfo = map[row.user_id] || {};
    }
  }
}

module.exports = LabourService;

// var tesk = new LabourService();
// var par = {
//   id:1,
//   cur_type:1
// };
// tesk.updatestatus(par).then(function(result){
//   console.log((result));
// }).catch(function(e){
//   console.log(e);
// });
