const system=require("../../../system");
const ServiceBase=require("../../sve.base")
const settings=require("../../../../config/settings")
class RptTypeService extends ServiceBase{
  constructor(){
     super("rpt",ServiceBase.getDaoName(RptTypeService));
     this.redisClient=system.getObject("util.redisClient");
  }
  async saveRptHistory(hs){
    var self=this;
    return this.db.transaction(async t=>{
        var hisarray=[];
        var rptid=hs.rptid;
        var batchid=hs.batchid;
        var batch=await this.db.models.uploadbatch.findById(batchid);
        var hisdata=hs.hisdata;
        var rptdate=hs.rptdate;
        var rptcode=hs.rptcode;
        hisdata.forEach(hd=>{
          var h={
            companycode:batch.companycode,
            companyname:batch.companyname,
            timetypecode:batch.timetypecode,
            batchdate:batch.batchdate,
            dateym:rptdate,
            rpttypecode:rptcode,
            position:hd.position,
            valstr:hd.valstr,
            desc:hd.desc,
            uploadrpt_id:rptid,
            uploadbatch_id:batchid,
          };
          hisarray.push(h);
        });
        await self.db.models.rpthistory.bulkCreate(hisarray,{transaction:t});
        //每保存一次历史数据，就是处理完成一个任务中的一个报表
        var  currentval= await self.redisClient.decr("batch"+batchid);
        console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+currentval);
        if(currentval==0){
              await self.redisClient.rpush("riskmq",JSON.stringify({
                key:new Date().toLocaleString(),
                content:{
                  batchCode:batchid+"",
                  taxTypeCode:batch.taxtypecode,
                  accountTypeCode:batch.accountstandardcode,
                  taxCode:batch.companycode
                }
              
          }));
          console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>sended...........");
          await self.redisClient.delete("batch"+batchid);
          //改变批的状态为解析完毕
          batch.batchstatuscode="calc";
          await batch.save();
        }
        return {};
    });
  }
  async queryStatus(bs){
     return this.db.models.uploadbatch.findAll({where:{
          id:{
            [this.db.Op.in]: bs
          }
      }});
  }
  async queryReport(batchid){
    var batch=await this.db.models.uploadbatch.findById(batchid);
     var rs=await this.db.models.result.findAll({where:{"BatchNo":batchid},attributes:["indexName","status"],raw:true});
     var tmp={};
     rs.forEach((item=>{
         tmp[item.indexName]=Number(item.status);
     }));
     var rptdata=await this.apiCallWithoutAk("http://fkrptresult-service/gsb/api/report",tmp);
     if(rptdata){
        var rtn={
          batchdate:batch.batchdate,
          rptdate:batch.updated_at,
          companyName:batch.companyname,
          taxCode:batch.companycode,
          results:rptdata,
          };
          return rtn;
     }else{
         return null;
     }
  
  }
  async saveRpt(upinfo){
    return this.db.transaction(async t=>{
         //构建批量对象
          var company={
              code:upinfo.companyTaxNum,
              name:upinfo.companyName,
          }
          var comp=await this.db.models.company.findOne({where:{code:upinfo.companyTaxNum}});
          if(!comp){
            comp=await this.db.models.company.create(company,{transaction:t});
          }
          var batchobj={
            batchdate:upinfo.date,
            companyname:upinfo.companyName,
            companycode:upinfo.companyTaxNum,
            name:upinfo.companyName+"_"+upinfo.date+"_"+upinfo.accountingType,
            batchstatuscode:"parserpt",
            taxtypecode:upinfo.valueAddedTax,
            timetypecode:upinfo.dateType,
            accountstandardcode:upinfo.accountingType,
            company_id:comp.id,
          }
          //保存批量
          var batchtemp=await this.db.models.uploadbatch.create(batchobj,{transaction:t});
          var rptresult=[];
          Object.keys(upinfo).forEach(k=>{
              {
                if(k.indexOf("Report")>=0){
                  var rpts=upinfo[k];
                  rpts.forEach(rpt=>{
                      var rptupload={
                        companyname:upinfo.companyName,
                        companycode:upinfo.companyTaxNum,
                        rpttypecode:rpt.code,
                        timetypecode:upinfo.dateType,
                        urlpath:rpt.url,
                        rptdate:rpt.date,
                        company_id:comp.id,
                        uploadbatch_id:batchtemp.id,
                      }
                      rptresult.push(rptupload);
                      
                  });
                }
             }
          });
          //保存报表
        await this.db.models.uploadrpt.bulkCreate(rptresult,{transaction:t});
        var lstspts=await this.db.models.uploadrpt.findAll({where:{uploadbatch_id:batchtemp.id},transaction:t});
        //保存当前批的报表数量到缓存，每保存一次历史，计数减1，当计数变为0时，改变批状态，给康发送消息，
        await this.redisClient.set("batch"+batchtemp.id,lstspts.length);
        try{
          lstspts.forEach(async (rpt)=>{
            await this.redisClient.notifyConsume("k8stask","docurls",rpt.id+"~"+batchtemp.id+"~"+rpt.rptdate+"~"+rpt.rpttypecode+"~"+rpt.urlpath);
          });
        }catch(e){
          //需要记录要清理的批号历史数据
        }
        return batchtemp;
    });
  }
}
module.exports=RptTypeService;

