const system=require("../../system");
const ServiceBase=require("../sve.base");
const fs=require("fs");
var excel = require('exceljs');
const uuidv4 = require('uuid/v4');
var path= require('path');
class TaskService extends ServiceBase{
  constructor(){
     super(ServiceBase.getDaoName(TaskService));
     //this.appDao=system.getObject("db.appDao");
     this.taskManager=system.getObject("db.taskManager");
     this.emailClient=system.getObject("util.mailClient");
     this.personTaxDao=system.getObject("db.individualincometaxDao");
     this.ossClient=system.getObject("util.ossClient");
  }
  //写文件并上传到阿里云,返回上传的路径
  async writexls(wb,sharecode){
    var that=this;
    var uuid=uuidv4();
    var u=uuid.replace(/\-/g,"");
    var fname="zc_"+u+".xlsx";
    var filepath="/tmp/"+fname;
    var promise=new Promise((resv,rej)=>{
      wb.xlsx.writeFile(filepath).then(async function(d) {
              var rtn=await that.ossClient.upfile(fname,filepath);
              fs.unlink(filepath,function(err){});
              return  resv(rtn);
      }).catch(function(e){
        return rej(e);
      });
    });
    return promise;
  }
  //读取模板文件
  async readxls(){
    var promise=new Promise((resv,rej)=>{
          var workbook = new excel.Workbook();
          workbook.properties.date1904 = true;
          var bpth=path.normalize(path.join(__dirname, '../'));
          workbook.xlsx.readFile(bpth+"/tmpl/tmpl.xlsx")
            .then(function() {
              return resv(workbook);
          }).catch(function(e){
              return rej(e);
          });
    });
    return promise;
  }
  async buildworkbook(taxCalcList){
     var workbook = await this.readxls();
     var sheet = workbook.getWorksheet(1);
     sheet.columns = [
         { header: '年度', key: 'statisticalYear', width: 10 },
         { header: '月份', key: 'statisticalMonth', width: 10 },
         { header: '员工姓名', key: 'employeeName', width: 10 },
         { header: '本月税前薪资', key: 'preTaxSalary', width: 18 },
         { header: '累计税前薪资', key: 'accupreTaxSalary', width: 18 },
        //  { header: '五险一金比例', key: 'insuranceAndFund', width: 18, outlineLevel: 1 },
         { header: '本月五险一金', key: 'insuranceAndFund', width: 18, outlineLevel: 1 },
         { header: '累计五险一金', key: 'accuinsuranceAndFund', width: 18, outlineLevel: 1 },
         { header: '子女教育', key: 'childrenEducation', width: 10 },
         { header: '继续教育', key: 'continuingEducation', width: 10 },
         { header: '房贷利息', key: 'interestExpense', width: 10 },
         { header: '住房租金', key: 'housingRent', width: 10 },
         { header: '赡养老人', key: 'supportElderly', width: 10 },
         { header: '大病医疗', key: 'illnessMedicalTreatment', width: 10 },
         { header: '专项扣除合计', key: 'specialDeduction', width: 10 },
         { header: '累计已扣专项', key: 'accuSpecialDeduction', width: 18, outlineLevel: 1 },
         { header: '累计已纳个税', key: 'accuPersonalIncomeTax', width: 18 },
         { header: '累计免征额', key: 'accuExemptionAmount', width: 10 },
         { header: '适用税率', key: 'taxRate', width: 10 },
         { header: '速算扣除', key: 'deductionNumber', width: 10 },
         { header: '本月应纳个税', key: 'personalIncomeTax', width: 18 },
         { header: '本月税后薪资', key: 'postTaxSalary', width: 18, outlineLevel: 1 }
        //  （累计税前薪资-累计五险一金-累计免征额-累计已扣专项）*税率-速算扣除-累计已纳个税=本月应纳个税
     ];
     taxCalcList.forEach(r=>{
        sheet.addRow(r);
     });
     return workbook;
  }
  async makerpt(qobj){
    var self=this;
    return this.db.transaction(async t=>{
        const sharecode=qobj.sharecode;
        const email=qobj.email;
        //按照sharecode获取单位某次个税计算
        var taxCalcList=await this.personTaxDao.model.findAll({where:{shareOnlyCode:sharecode},transaction:t});
        var sheetNameSufix="个税汇总表";
        if(taxCalcList && taxCalcList.length>0){
          var year=taxCalcList[0].statisticalYear;
          var month=taxCalcList[0].statisticalMonth;
          sheetNameSufix=year+month+sheetNameSufix;
        }
        var wb=await this.buildworkbook(taxCalcList);
        //生成excel
        var result=await this.writexls(wb,sharecode);
        //异步不等待发送邮件给
        var html='<a href="'+result.url+'">'+sheetNameSufix+'</a>'
        self.emailClient.sendMsg(email,sheetNameSufix,null,html,null,null,[]);
        //发送手机短信

        //写到按咋回哦sharecode，修改下载的url

        return result.url;
    });
  }
  async create(qobj){
    var self=this;
    return this.db.transaction(async t=>{
        var task=await  this.dao.create(qobj,t);
        //发布任务事件
        var action="new";
        var taskClassName=task.taskClassName;
        var exp=task.taskexp;
        var msg=action+"_"+taskClassName+"_"+exp;
        await self.taskManager.newTask(msg);
        await self.taskManager.publish("task","newtask");
        return task;
    });
  }
  async restartTasks2(qobj){
    return this.restartTasks(qobj);
  }
  async restartTasks(qobj){
    var self=this;
    var rtn={};
    var tasks=await this.dao.model.findAll({raw:true});
    //清空任务列表
    await this.taskManager.clearlist();
    for(var i=0;i<tasks.length;i++){
      var tmpTask2=tasks[i];
      try {
        (async (tmpTask,that)=>{
          var action="new";
          var taskClassName=tmpTask.taskClassName;
          var exp=tmpTask.taskexp;
          var msg=action+"_"+taskClassName+"_"+exp;
          // await that.taskManager.newTask(msg);
          // await that.taskManager.publish("task","newtask");
          await that.taskManager.addTask(taskClassName,exp);
        })(tmpTask2,self);
      } catch (e) {
        rtn=null;
      }
    }
    return rtn;
  }
  async delete(qobj){
    var self=this;
    return this.db.transaction(async t=>{
        var task= await this.dao.model.findOne({where:qobj});
        await  this.dao.delete(task,qobj,t);
        //发布任务事件
        var action="delete";
        var taskName=task.taskClassName;
        var exp=task.taskexp;
        var msg=action+"_"+taskName;
        //发布任务，消息是action_taskClassName
        await this.taskManager.publish("task",msg,null);
        return task;
    });
  }
}
module.exports=TaskService;
