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

class TcompanytaxocrService extends ServiceBase {
  constructor() {
    super("tax", ServiceBase.getDaoName(TcompanytaxocrService));

    this.tcompanytaxitemDao = system.getObject("db.tax.tcompanytaxitemDao");

    this.ocr_url = "http://43.247.184.92:9002/gsb/ocr/ocrtable";
  }

  async sendImg(limit) {
    let ocrIds = await this.dao.findUnSendIds(limit);
    if(!ocrIds || ocrIds.length == 0) {
      return;
    }

    for(let ocrObj of ocrIds) {
      let ocr = await this.dao.findById(ocrObj.id);
      try {
        let data = {
          "taxOcrId": 1,
          "tax_img": ocr.tax_img,
        };
        // 张云飞接口
        let res = await axios({
          method: 'post',
          url: this.ocr_url,
          data: data
        });
        if(!res.data || !res.data.data) {
          break;
        }
        await this.saveOcrItems(ocr, res.data.data);
        ocr.isSend = true;
        ocr.isOCR = true;
        ocr.ocr_time = new Date();
        await ocr.save();
        console.log(ocrObj.id);
      } catch (error) {
        console.log(error);
      }
    }
  }

  async saveOcrItems(ocr, itemList) {
    if(!ocr) {
      return;
    }

    let items = [];
    for(let obj of itemList) {
      if(!obj.idNo) {
        continue;
      }

      items.push({
        companyId: ocr.companyId,
        taxId: ocr.taxId,
        taxOcrId: ocr.id,
        month: ocr.month,
        month_date: ocr.month_date,
        idName: obj.idName,
        idNo: obj.idNo,
        incomeTax: obj.incomeTax,
        actualAmt: obj.actualAmt,
        grant_time: obj.grant_time,
        imagepath: obj.imagepath,
        locations: JSON.stringify(obj.locations)
      });
    }

    await this.tcompanytaxitemDao.delByTaxOcrId(ocr.id);
    await this.tcompanytaxitemDao.bulkCreate(items);

    ocr.isOCR = true;
    ocr.ocr_time = new Date();
    await ocr.save();
    return system.getResultSuccess();
  }
}
module.exports = TcompanytaxocrService;
