const system=require("../../system");
const ServiceBase=require("../sve.base");
const uuidv4 = require('uuid/v4');
const fs=require("fs");
const xlsx = require('node-xlsx')

class EjobrosterService extends ServiceBase{
  constructor(){
     super(ServiceBase.getDaoName(EjobrosterService));
     this.restClient = system.getObject("util.restClient");

     this.ecompanyDao = system.getObject("db.ecompanyDao");
     this.ejobDao = system.getObject("db.ejobDao");
  }

  async saveRoster(userId, ossurl) {
    var result = await this.parseRoster(userId, ossurl);
    if(result.code == 0) {
      return result;
    }

    if(!result.data) {
      return {code : 0,msg:"excel文件内容为空"};
    }
    for(var item of result.data) {
      var o = await this.findOne({ecompany_id: item.ecompany_id, ejob_id: item.ejob_id, mobile: item.mobile});
      if(o) {
        continue;
      }
      this.create(item);
    }
    return result;
  }

  async parseRoster(userId, ossurl) {
    var result = {
      code : 0,
      msg:"",
      data : [],
    };
    
    var dataList = [];
    var filePath = "/tmp/ejob_roster_" + userId + ".xlsx";
    try {
      await this.restClient.execDownload("'" + ossurl + "'", filePath);

      var sheets = xlsx.parse(filePath);
      fs.unlinkSync(filePath);
      

      if(!sheets || sheets.length == 0) {
        result.msg = "名单excel为空";
        return result;
      }

      var sheet = sheets[0];
      if(!sheet || !sheet.data || sheet.data.length == 0) {
        result.msg = "名单无内容行";
        return result;
      }

      var rows = sheet.data;
      var companyNames = [];
      var jobNames = [];
      var datalist = [];

      var unique = [];

      for (var idx in rows) {
        if(idx == 0) {
          continue;
        }

        var cells = rows[idx];
        if(cells.length == 0) {
          continue;
        }
        if(cells.length < 6) {
          result.msg = "人员名单数据不完整，请检查excel第" + idx + "行";
          return result;
        }
        var ecompany_name = this.trim(cells[0]);
        var ejob_name = this.trim(cells[1]);
        var userName = this.trim(cells[2]);
        var mobile = this.trim(cells[3]);
        var personsSign = this.trim(cells[4]);
        var bankno = this.trim(cells[5]);

        var u = ecompany_name + "_@_" + ejob_name + "_@_" + mobile;
        if(unique.indexOf(u) >= 0) {
          continue;
        }
        unique.push(u);

        if(!ecompany_name) {
          result.msg = "excel第" + idx + "行，公司名称错误";
          return result;
        }

        if(!ejob_name) {
          result.msg = "excel第" + idx + "行，职位名称错误";
          return result;
        }

        if(!mobile) {
          result.msg = "excel第" + idx + "行，手机号码错误";
          return result;
        }
        if(!personsSign) {
          result.msg = "excel第" + idx + "行，身份证号错误";
          return result;
        }
        if(!bankno) {
          result.msg = "excel第" + idx + "行，银行卡号错误";
          return result;
        }
        if(companyNames.indexOf(ecompany_name) == -1) {
          companyNames.push(ecompany_name);
        }

        if(jobNames.indexOf(ejob_name) == -1) {
          jobNames.push(ejob_name);
        }

        datalist.push({
          url: ossurl,
          ecompany_name: ecompany_name,
          ejob_name: ejob_name,
          userName: userName,
          mobile: mobile,
          personsSign: personsSign,
          bankno: bankno,
        });
      }

      if(datalist.length == 0) {
        result.msg = "excel数据不完整";
        return result;
      }

      var companyMap = await this.ejobDao.findMapByRosterBiz(companyNames, jobNames);

      for(var idx in datalist) {
        var data = datalist[idx];

        var job = companyMap[data.ecompany_name + "___" + data.ejob_name];
        if(!job) {
          result.msg = "excel第" + (Number(idx) + 1) + "行错误，【" + data.ecompany_name + "（" + data.ejob_name + "）职位】在系统中不存在，请检查公司名称和职位名称" ;
          return result;
        }
        data.ejob_id = job.id;
        data.ecompany_id = job.ecompany_id;
      }

      result.code = 1;
      result.data = datalist;
      return result;
    } catch (error) {
      console.log(error.stack);
      result.msg = "您的网络忙， 请稍后重试";
      return result;
    }
  }

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

    var where = {};

    if (params.userName) {
      whereObj.userName = {
        [this.db.Op.like]: "%" + params.userName + "%"
      };
    }

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

    if (params.edu) {
      where.edu = params.edu;
    }
    if (params.identityType) {
      where.identityType = params.identityType;
    }
    if (params.personsSign) {
      where.personsSign = params.personsSign;
    }
    if (params.bankno) {
      where.bankno = params.bankno;
    }

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

    var attributes = ["id","ecompany_id","ecompany_name","ejob_id","ejob_name","userName","mobile","personsSign","bankno","created_at"];

    var page = await this.getPageList(currentPage, pageSize, where, orderby, attributes);
    if (page && page.rows) {
      for (var row of page.rows) {
        this.handleDate(row, ["created_at"]);
      }
    }
    return page;
  }
}

module.exports = EjobrosterService;
