var system = require("../../../system");
const http = require("http");
const uuidv4 = require('uuid/v4');
const querystring = require('querystring');
const sha235 = require("sha256");
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const moment = require('moment');
const System = require("../../../system");
const toFtClient = require("../../../utils/toFtClient");
const appconfig = system.getSysConfig();
const { getResult } = require("../../../system");
class DeliverybillCtl extends CtlBase {
  constructor() {
    super("bizchance", CtlBase.getServiceName(DeliverybillCtl));
    this.logService = system.getObject("service.bizchance.statuslogSve");
    this.cacheManager = system.getObject("db.common.cacheManager");
    this.fitaxschemeService = system.getObject("service.bizchance.fitaxschemeSve");
    this.bizoptService = system.getObject("service.bizchance.bizoptSve");
  }

  /**
   * 交付单列表、交付单记录列表
   * @param {*} pobj 
   * @param {*} qobj 
   * @param {*} req 
   */
  async findAndCountAll(pobj, qobj, req) {
    const rs = await this.service.findAndCountAll(pobj);
    let result = [];
    for (let val of rs.results.rows) {
      let { id, delivery_code, service_address, delivery_info, created_at, updated_at, delivery_status, delivery_man_name } = val;
      result.push({
        deliveryId: id,                     // id
        deliveryNumber: delivery_code,      // 交付单编号        
        companyName: delivery_info.companyName,// 企业名称
        taxpayerType: delivery_info.taxpayerType, //纳税人类型 1 一般；2 小规模
        areaType: delivery_info.areaType, //区域类型 city-城市
        area: service_address,              // 服务 地区 编码
        companyBizType: delivery_info.companyType,// 公司类型  1-商贸型；2-服务型；3-特殊行业；4-其他
        contactsName: delivery_info.contactsName,// 联系人
        contactsPhone: delivery_info.contactsPhone,// 联系电话
        owner: delivery_man_name,//所属人
        deliveryStatus: delivery_status,    // 交付单状态 
        setupStatus: delivery_info.setupStatus || System.SERVERSESTATUS.NOTSETUP,//建账状态 notsetup | setup
        createdAt: created_at,
        updatedAt: updated_at,
        setupAt: (delivery_info.setupInfo && delivery_info.setupInfo.time) || delivery_info.serviceStartTime || null
      });
    }
    rs.results.rows = result;
    return system.getResult(rs);
  }

  /**
   * 处理 是否成单
   * @param {*} pobj 
   * @param {*} qobj 
   * @param {*} req 
   */
  async updateOrderStatus(pobj, qobj, req) {
    try {
      if (!pobj.deliverId) {
        throw new Error("deliverId 不能为空");
      }
      if (![true, false].includes(pobj.orderStaus)) {
        throw new Error("orderStaus 不能为空且为Boolean值");
      }
      if (pobj.orderStaus === true) {
        if (!pobj.setupAt) {
          throw new Error("成单时建账时间不能为空");
        }
      }
      if (pobj.orderStaus === false) {
        if (!pobj.note) {
          throw new Error("不成单时备注不能为空");
        }
      }
      const rs = await this.service.updateOrderStatus(pobj);
      return system.getResult(rs);
    } catch (err) {
      return system.getResult(null, err.message)
    }
  }

  /**
   * 建立账单
   * @param {*} pobj 
   * @param {*} qobj 
   * @param {*} req 
   */
  async setupBill(pobj, qobj, req) {
    try {
      if (!pobj.deliverId) {
        throw new Error("deliverId 不能为空");
      }
      if (!pobj.contactsName || !pobj.time || !pobj.accountingType || !pobj.taxpayerType || (!pobj.supplier && pobj.supplier != 0)) {
        throw new Error("参数不能为空");
      }
      const rs = await this.service.setupBill(pobj);
      return system.getResult(rs);
    } catch (err) {
      return system.getResult(null, err.message)
    }
  }

  /**
   * 交付单详情
   * @param {*} pobj 
   * @param {*} qobj 
   * @param {*} req 
   */
  async deliverInfo(pobj, qobj, req) {
    try {
      if (!pobj.deliverId) {
        throw new Error("deliverId 不能为空");
      }
      const rs = await this.service.deliverInfo(pobj);
      return system.getResult(rs);
    } catch (err) {
      return system.getResult(null, err.message)
    }
  }

  /**
   * 分配人
   * @param {*} pobj 
   * @param {*} qobj 
   * @param {*} req 
   */
  async distributionPerson(pobj, qobj, req) {
    try {
      if (!Array.isArray(pobj.numbers) || pobj.numbers.length <= 0) {
        throw new Error("numbers 为数组 且 不能为空");
      }
      if (!pobj.nickName) {
        throw new Error("nickName 不能为空");
      }
      if (!pobj.userId) {
        throw new Error("userId 不能为空");
      }
      if (!pobj.opCode) {
        throw new Error("opCode 不能为空");
      }
      if (![system.FLOWCODE.BIZ, system.FLOWCODE.DELIVERY].includes(pobj.type)) {
        throw new Error("type 不合规");
      }
      const rs = await this.service.distributionPerson(pobj);
      return system.getResult(rs);
    } catch (err) {
      return system.getResult(null, err.message)
    }
  }

  /**
   * 获取交付商信息
   * @param {*} pobj 
   * @param {*} qobj 
   * @param {*} req 
   */
  async getChannelCompany(pobj, qobj, req) {
    try {
      const rs = await toFtClient.getChannelCompany();
      return system.getResult(rs.map(item => {
        return {
          id: item.id,
          name: item.name
        }
      }));
    } catch (err) {
      return system.getResult(null, err.message)
    }
  }

  // 创建融易算服务实例
  async insertInfo(mobj, qobj, req) {
    console.log('mobj--------------------------------', mobj);
    try {
      var pobj = mobj.actionBody;
      var cachestr = sha235(JSON.stringify(pobj));
      var cacheInfo = await this.cacheManager["TxCache"].getCache(cachestr);
      if (cacheInfo && cacheInfo != 'undefined') {
        return {
          "status": 1, //1代表成功，否则失败
          "msg": "已处理成功!",
          "data": "",
          "requestId": ""
        }
      }
      else {
        var obj = {};
        obj.delivery_code = pobj.orderId + "_book";
        obj.source_number = "tx";
        if (pobj.solutionBizId) {
          obj.scheme_number = pobj.solutionBizId+"_book";
          var scheme = await this.fitaxschemeService.findInfoByBizid({ "bizId": pobj.solutionBizId });
          if (scheme) {
            obj.demand_code = scheme.demand_code;
            //根据需求编号获取业务员信息
            var bizopt = await this.bizoptService.findInfoByDemandCode({ "demand_code": obj.demand_code });
            if (bizopt) {
              obj.salesman_opcode = bizopt.salesman_opcode;
              obj.salesman_id = bizopt.salesman_id;
              obj.salesman_name = bizopt.salesman_name;
              obj.salesman_phone = bizopt.salesman_phone;
              obj.delivery_man_opcode = bizopt.salesman_opcode;
              obj.delivery_man_id = bizopt.salesman_id;
              obj.delivery_man_name = bizopt.salesman_name;

            }

          }
        }
        obj.product_code = "bookkeeping";
        obj.product_name = "代帐服务";
        obj.service_address = pobj.area;
        obj.delivery_status = "received";
        obj.facilitator_id = "10";
        obj.facilitator_name = "公司宝";
        obj.source_name = "tencentCloud";
        pobj.contactsPhone = pobj.contactMobile;
        delete pobj.contactMobile;
        if (pobj.taxpayerType == 1) {
          pobj.taxpayerType = "generalTaxpayer";
          pobj.taxpayerName = "一般纳税人";

        }
        else if (pobj.taxpayerType == 2) {
          pobj.taxpayerType = "smallScaleTaxpayer";
          pobj.taxpayerName = "小规模纳税人";
        }
        obj.delivery_info = pobj;
        obj.biz_id = pobj.bizId;
        var buInfo = await this.service.insertInfo(obj);
        if (buInfo) {
          await this.cacheManager["TxCache"].cache(cachestr, JSON.stringify({ cachestr: cachestr }), 180);//插入redis缓存
          return {
            "status": 1, //1代表成功，否则失败
            "msg": "处理成功!",
            "data": buInfo,
            "requestId": ""
          }
        }
        else {
          return system.getResultFail(buInfo);
        }
      }
    }
    catch (err) {
      return system.getResult(null, err.message)
    }
  }

  //更新融易算服务实例
  async updateServer(mobj, qobj, req) {
    console.log("更新融易算服务实例参数--------------------------",JSON.stringify(mobj));
    try {
      var pobj = mobj.actionBody;
      var cachestr = sha235(JSON.stringify(pobj));
      var cacheInfo = await this.cacheManager["TxCache"].getCache(cachestr);
      if (cacheInfo && cacheInfo != 'undefined') {
        return {
          "status": 1, //1代表成功，否则失败
          "msg": "已处理成功!",
          "data": "",
          "requestId": ""
        }
      } else {
        if (pobj.contactMobile && pobj.contactMobile != 'undefined') {
          pobj.contactsPhone = pobj.contactMobile;
          delete pobj.contactMobile;
        }
        pobj.contactsName = pobj.contactName;
        delete pobj.contactName;
        pobj.companyType = pobj.companyBizType;
        delete pobj.companyBizType;
        pobj.creditCode = pobj.uscc;
        delete pobj.uscc;
        if (pobj.taxpayerType == 1) {
          pobj.taxpayerType = "generalTaxpayer";
          pobj.taxpayerName = "一般纳税人";

        }
        else if (pobj.taxpayerType == 2) {
          pobj.taxpayerType = "smallScaleTaxpayer";
          pobj.taxpayerName = "小规模纳税人";
        }
        var obj = {
          "delivery_code": pobj.orderId + "_book",
          "delivery_info": pobj,
          "biz_id": pobj.bizId
        };
        const rs = await this.service.updateServer(obj);
        console.log("更新融易算服务返回结果--------------------------",JSON.stringify(rs));
        if (rs) {
          await this.cacheManager["TxCache"].cache(cachestr, JSON.stringify({ cachestr: cachestr }), 180);//插入redis缓存
          return {
            "status": 1, //1代表成功，否则失败
            "msg": "处理成功!",
            "data": rs,
            "requestId": ""
          }
        } else {
          console.log("更新融易算服务返回结果更新失败--------------------------");
          return system.getResultFail("更新失败!");
        }
      }
    }
    catch (err) {
      console.log("更新融易算服务返回错误结果--------------------------",error);
      return system.getResult(null, err.message)
    }
  }



  //根据bizId查询deliverybill表中的所有信息
  async getInfo(pobj, qobj, req) {
    try {
      if (!pobj.bizId) {
        throw new Error("bizId 不能为空");
      }
      const rs = await this.service.getInfo(pobj);
      //console.log("got message");
      return system.getResult(rs);
    } catch (err) {
      return system.getResult(null, err.message)
    }
  }

  //服务状态变更通知
  async notifyServiceStatusChange(pobj, qobj, req) {
    console.log("融易算服务状态变更通知参数--------------------------",JSON.stringify(pobj));
    let ab = pobj.actionBody;
    if (!ab.requestId || ab.requestId == "undefined") {
      return system.getResultFail(-1, "请求id不能为空");
    }
    if (!ab.bizId || ab.bizId == "undefined") {
      return system.getResultFail(-1, "服务实例编号不能为空");
    }
    if (!ab.status || ab.status == "undefined") {
      return system.getResultFail(-1, "服务状态不能为空");
    }

    try {
      let cacheStr = sha235(JSON.stringify(ab));
      let cacheInfo = await this.cacheManager["TxCache"].getCache(cacheStr);
      if (cacheInfo && cacheInfo !== "undefined") {
        return {
          "status": 1,
          "msg": "已处理成功",
          "data": cacheInfo,
          "requestId": ab.requestId,
        };
      } else {
        // 变更服务状态
        let whereObj = { biz_id: ab.bizId };
        let rtn = await this.service.findOne(whereObj);
        console.log("融易算服务状态变更通知返回结果--------------------------",JSON.stringify(rtn));
        if (!rtn) {
          return system.getResultFail(-1, "未知服务信息");
        }
        let deliveryInfo = {};
        Object.assign(deliveryInfo, rtn.delivery_info, {
          "serviceStartTime": ab.serviceStartTime,
          "serviceEndTime": ab.serviceEndTime,
        });
        let upObj = {
          delivery_status: ab.status,
          delivery_info: deliveryInfo,
        };
        await rtn.update(upObj, { where: whereObj });
        // 将变更结果插入到redis中
        await this.cacheManager["TxCache"].cache(cachestr, JSON.stringify({ cachestr: cachestr }), 180);
        return {
          "status": 1,
          "msg": "处理成功",
          "data": rtn,
          "requestId": ab.requestId
        };
      }
    }
    catch (err) {
      console.log("融易算服务状态变更通知返回错误结果--------------------------",error);
      return system.getResultError(err);
    }
  }

  //接收票据快递单号
  async receivePaperPost(pobj, qobj, req) {
    console.log("融易算接收票据快递单号参数--------------------------",JSON.stringify(pobj));
    var deliverInfo = await this.service.getInfo({ "bizId": pobj.bizNo });
    if (deliverInfo) {
      var param = {
        companyId: deliverInfo.deliveryBillInfo.deliveryInfo.setupInfo.supplier,//租户信息
        customerName: deliverInfo.deliveryBillInfo.vftClientId,//客户信息（帐套）
        sign: "",//签名
        postWay: "2",
        currentPeriod: pobj.actionBody.accountDate,
        courierNumber: pobj.actionBody.expressNum
      }
      param.sign = await toFtClient.postToFtBySign("/customerReceiveBill/addCusReceiveBill", param.companyId);
      var rc = this.getObject("util.execClient");
      var reqUrl = settings.ftConfig.url + "/customerReceiveBill/addCusReceiveBill";
      var result = await rc.execPost(param, reqUrl);
      var j = JSON.parse(result.stdout);
      console.log("融易算接收票据快递单号返回结果--------------------------",JSON.stringify(j));
      if (j.status == 1) {
        return system.getResult(result);
      }
      else {
        console.log("融易算接收票据快递单号错误------------------------");
        return system.getResultError("接收票据快递单号错误!");
      }
    }
    else {
      console.log("融易算接收票据快递单号错误------------------------没有交付单信息");
      return system.getResultError("没有交付单信息");
    }




  }
  
  async testPaperPostConfirm(obj){
    console.log("testCloseProposal-------------------");
    return { 
        "requestId": "d51aa427-738f-4bed-b48d-282da0a74432", 
        "status":1,
        "success": true, 
        "errorCode": 0,
        "errorMsg": "ok",
        "data": { 
        } 
    } 
  }

  //票据快递情况反馈
  async confirmPaperPost(pobj, qobj, req) {
    console.log("融易算接收票据快递情况反馈参数--------------------------",JSON.stringify(pobj));
    var deliverInfo = await this.service.findByClientId({ "vftClientId": pobj.customer_id });
    if (deliverInfo) {
      var param = {
        "bizNo": pobj.customer_id,//需要根据客户id获取服务示例号 
        "accountDate": pobj.current_period,
        "status": pobj.status,
        "errorStatus": -1
      }
      if (pobj.remark) {
        param.remark = pobj.remark;
        if (pobj.remark.includes("进销项发票不全")) {
          param.errorStatus = 1;
        }
      }
      var pushObj = {
        //"pushUrl": this.rysUrl + "service/paperPost/confirm",
        "pushUrl": this.rysUrl + "/web/bizchance/deliverybillCtl/testPaperPostConfirm",
        "actionType": "confirm",
        "messageBody": param,
        "headData": {
          'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTg0MzQ2ODcsImlzcyI6InJFRVN6TU5ZUlM2RnBWNnZlY09vdExPNWdPcUNXSmFQIiwiaWF0IjoxNTk4NDMxMDg3fQ.isQ40HqHHfJ-rTsUQOhRIdu4XCitZU-AfzeqSH4kPbQ',
          'XAPPKEY': 'f6b59b74-f943-4735-bb86-e05d6b7fd78e',
          'Source': 'GSB'
        },
        "requestId": uuidv4()
      }
      return system.queueOper(pushObj);
    }
    else {
      console.log("融易算接收票据快递情况反馈------------------------没有交付单信息");
      return system.getResultError("没有交付单信息");
    }
  }

  async testfeedback(obj){
    console.log("testCloseProposal-------------------");
    return { 
        "requestId": "d51aa427-738f-4bed-b48d-282da0a74432", 
        "status":1,
        "success": true, 
        "errorCode": 0,
        "errorMsg": "ok",
        "data": null
    } 
  }

}
module.exports = DeliverybillCtl;