const system = require("../../../system");
const ServiceBase = require("../../sve.base");
var settings = require("../../../../config/settings");
var RPCClient = require('@alicloud/pop-core').RPCClient;
var OSS = require('ali-oss');
const crypto = require('crypto');
var moment = require("moment");
class TradetransferService extends ServiceBase {
  constructor() {
    super("transfer", ServiceBase.getDaoName(TradetransferService));
  }

  //订单创建
  async createtransfer(obj) {
    if (!obj.BizId) {
      return {
        "errorCode": "error",
        "errorMsg": "订单号不能为空",
        "module": { "orderNumber": "" },
        "requestId": obj.requestid,
        "success": false
      }
    }
    if (!obj.UserName) {
      return {
        "errorCode": "error",
        "errorMsg": "用户不能为空",
        "module": { "orderNumber": "" },
        "requestId": obj.requestid,
        "success": false
      }
    }
    if (!obj.Mobile) {
      return {
        "errorCode": "error",
        "errorMsg": "用户手机号不能为空",
        "module": { "orderNumber": "" },
        "requestId": obj.requestid,
        "success": false
      }
    }
    if (!obj.RegisterNumber) {
      return {
        "errorCode": "error",
        "errorMsg": "注册号不能为空",
        "module": { "orderNumber": "" },
        "requestId": obj.requestid,
        "success": false
      }
    }
    if (!obj.Classification) {
      return {
        "errorCode": "error",
        "errorMsg": "大类不能为空",
        "module": { "orderNumber": "" },
        "requestId": obj.requestid,
        "success": false
      }
    }
    if (!obj.Price) {
      return {
        "errorCode": "error",
        "errorMsg": "价格不能为空",
        "module": { "orderNumber": "" },
        "requestId": obj.requestid,
        "success": false
      }
    }
    var transferinfo = await this.findOne({ ali_bizid: obj.BizId });
    if (transferinfo) {
      return {
        "status": 2,
        "msg": "交付单已存在",
        "data": {
          "orderNo": obj.fq_ordernum,
          "channelServiceNo": obj.BizId,
          "channelParams": {}
        },
        "requestid": obj.requestid
      }
    } else {
      var source = {
        tm_number: obj.RegisterNumber,
        user_name: obj.UserName,
        ali_bizid: obj.BizId,
        mobile: obj.Mobile,
        price: obj.Price,
        ncl_one: obj.Classification,
        fq_ordernum: obj.fq_ordernum
      }
      var rtn = await this.create(source);
      if (rtn) {
        return {
          "status": 0,
          "msg": "success",
          "data": {
            "orderNo": obj.fq_ordernum,
            "channelServiceNo": obj.BizId,
            "channelParams": {}
          },
          "requestid": obj.requestid
        }
      } else {
        return {
          "status": -1,
          "msg": "error",
          "data": {
            "orderNo": obj.fq_ordernum,
            "channelServiceNo": obj.BizId,
            "channelParams": {}
          },
          "requestid": obj.requestid
        }
      }

    }
  }
  //订单查询
  async ordersel(obj) {
    if (!obj.BizId) {
      return {
        "errorCode": "error",
        "errorMsg": "订单号不能为空",
        "module": { "orderId": "", "orderStatus": "" },
        "requestId": obj.requestid,
        "success": false
      }
    }

    var transferinfo = await this.findOne({ ali_bizid: obj.BizId });
    if (transferinfo) {
      return {
        "errorCode": "OK",
        "errorMsg": "",
        "module": { "orderId": transferinfo.fq_ordernum, "orderStatus": transferinfo.aliorder_status },
        "requestId": obj.requestid,
        "success": true
      }
    } else {
      return {
        "errorCode": "error",
        "errorMsg": "订单不存在",
        "module": { "orderId": "", "orderStatus": "" },
        "requestId": obj.requestid,
        "success": false
      }
    }

  }

  /*
  返回20位业务订单号
  prefix：业务前缀
  */
  async getBusUid(prefix) {
    prefix = (prefix || "");
    if (prefix) {
      prefix = prefix.toUpperCase();
    }
    var prefixlength = prefix.length;
    var subLen = 8 - prefixlength;
    var uidStr = "";
    if (subLen > 0) {
      uidStr = await this.getUidInfo(subLen, 60);
    }
    var timStr = moment().format("YYYYMMDDHHmm");
    return prefix + timStr + uidStr;
  }

  //订单关闭
  async orderclose(obj) {
    if (!obj.BizId) {
      return {
        "errorCode": "error",
        "errorMsg": "订单号不能为空",
        "requestId": obj.requestid,
        "success": false
      }
    }
    var transferinfo = await this.findOne({ ali_bizid: obj.BizId });
    if (transferinfo) {
      transferinfo = transferinfo.dataValues;
      if (transferinfo.transfer_status == "CLOSE_ORDER_REFUND") {
        return {
          "errorCode": "OK",
          "errorMsg": "",
          "requestId": obj.requestid,
          "success": true
        }
      } else {
        transferinfo.transfer_status = "CLOSE_ORDER_REFUND";
        transferinfo.aliorder_status = "11";
        await this.update(transferinfo);
        return {
          "errorCode": "OK",
          "errorMsg": "",
          "requestId": obj.requestid,
          "success": true
        }
      }
    } else {
      return {
        "errorCode": "error",
        "errorMsg": "订单不存在",
        "requestId": obj.requestid,
        "success": false
      }
    }
  }

  //业务员分配
  async fenpeiowner(obj) {
    if (!obj.BizId) {
      return {
        "errorCode": "error",
        "errorMsg": "订单号不能为空",
        "requestId": obj.requestid,
        "success": false
      }
    }
    var transferinfo = await this.findOne({ ali_bizid: obj.BizId });
  }


  //订单确认
  async confirmorder(obj) {
    if (!obj.ali_bizid) {
      return {
        status: "-1",
        msg: "参数异常"
      }
    }
    var BizId = obj.ali_bizid;
    var obj = {
      action: "ConfirmOrder",
      reqbody: {
        BizId: BizId
      }
    }
    try {
      var result = await this.aliclient(obj)
      return result;
    } catch (error) {
      console.log(error)
    }

  }

  //取消订单
  async refuseorder(obj) {
    if (!obj.ali_bizid) {
      return {
        status: "-1",
        msg: "参数异常"
      }
    }
    var BizId = obj.ali_bizid;
    var obj = {
      action: "RefuseOrder",
      reqbody: {
        BizId: BizId
      }
    }
    var rtn = await this.aliclient(obj)
    console.log(rtn)
    return rtn;
  }

  //补充材料
  async supplymaterail(obj) {
    obj.buyer_businesslicense = obj.buyer_businesslicense == null ? null : obj.buyer_businesslicense.split("com//")[1];
    obj.buyer_idcard = obj.buyer_idcard == null ? null : obj.buyer_idcard.split("com//")[1];
    obj.seller_businesslicense = obj.seller_businesslicense == null ? null : obj.seller_businesslicense.split("com//")[1];
    obj.seller_idcard = obj.seller_idcard == null ? null : obj.seller_idcard.split("com//")[1];
    obj.seller_proxy = obj.seller_proxy == null ? null : obj.seller_proxy.split("com//")[1];
    obj.tm_cert_url = obj.tm_cert_url == null ? null : obj.tm_cert_url.split("com//")[1];
    obj.seller_apply = obj.seller_apply == null ? null : obj.seller_apply.split("com//")[1];
    obj.transfer_cert_url = obj.transfer_cert_url == null ? null : obj.transfer_cert_url.split("com//")[1];
    obj.notarization_url = obj.notarization_url == null ? null : obj.notarization_url.split("com//")[1];
    obj.user_type = obj.user_type == "person" ? 2 : 1;
    var sobj = {
      action: "SupplyMaterail",
      reqbody: {
        BizId: obj.ali_bizid,
        ContactName: obj.contact_name,
        ContactMobile: parseInt(obj.contact_mobile),
        ContactEmail: obj.contact_email,
        CardNo: obj.cardno,
        Complete: true,
        UserType: obj.user_type,
        BuyerAddress: obj.buyer_address,
        BuyerBusinessLicense: obj.buyer_businesslicense,
        BuyerName: obj.buyer_name,
        BuyerIdCard: obj.buyer_idcard,
        SellerBusinessLicense: obj.seller_businesslicense,
        SellerIdCard: obj.seller_idcard,
        SellerProxy: obj.seller_proxy,
        RegistrationCert: obj.tm_cert_url,
        SellerApply: obj.seller_apply,
        Notarization: obj.notarization_url + "," + obj.transfer_cert_url
      }
    }
    console.log(sobj);
    var result = await this.aliclient(sobj)
    return result;
  }

  //尾款支付---调取阿里云查询后修改订单
  async querytradeproducelist(obj) {
    if (!obj.ali_bizid) {
      return {
        status: "-1",
        msg: "参数异常"
      }
    }
    var BizId = obj.ali_bizid;
    var obj = {
      action: "QueryTradeProduceList",
      BizId: BizId

    }
    var tradeinfo = await this.aliclient(obj);
    return tradeinfo;
  }

  //服务商邮寄材料给用户
  async posttransfermatereial(obj) {
    if (!obj.ali_bizid) {
      return {
        status: "-1",
        msg: "参数异常"
      }
    }
    if (!obj.logistics) {
      return {
        status: "-1",
        msg: "参数异常"
      }
    }
    var BizId = obj.ali_bizid;
    var obj = {
      action: "PostTransferMaterial",
      reqbody: {
        BizId: BizId,
        Logistics: obj.logistics
      }
    }
    var result = await this.aliclient(obj)
    return result;

  }

  //用户盖章后邮寄服务商
  async receivedtransfermaterail(obj) {
    if (!obj.ali_bizid) {
      return {
        status: "-1",
        msg: "参数异常"
      }
    }
    var BizId = obj.ali_bizid;
    var obj = {
      action: "ReceivedTransferMaterail",
      reqbody: {
        BizId: BizId
      }
    }
    var rtn = await this.aliclient(obj)
    console.log(rtn)
    return rtn;
  }

  //服务商递交到商标局
  async submittedtransfermaterail(obj) {
    if (!obj.ali_bizid) {
      return {
        status: "-1",
        msg: "参数异常"
      }
    }
    var BizId = obj.ali_bizid;
    var obj = {
      action: "SubmittedTransferMaterail",
      reqbody: {
        BizId: BizId
      }
    }
    return await this.aliclient(obj);
  }

  //商标局受理
  async acceptedtransfermaterail(obj) {
    if (!obj.ali_bizid) {
      return {
        status: "-1",
        msg: "参数异常"
      }
    }
    var obj = {
      action: "AcceptedTransferMaterail",
      reqbody: {
        BizId: obj.ali_bizid
      }
    }
    var rtn = await this.aliclient(obj)
    console.log(rtn)
    return rtn;
  }

  //商标局核准通过
  async approvedtransfer(obj) {
    if (!obj.ali_bizid) {
      return {
        status: "-1",
        msg: "参数异常"
      }
    }
    var obj = {
      action: "ApprovedTransfer",
      reqbody: {
        BizId: obj.ali_bizid
      }
    }
    var rtn = await this.aliclient(obj)
    console.log(rtn)
    return rtn;
  }

  //商标局核准不通过
  async refusetransfer(obj) {
    if (!obj.ali_bizid) {
      return {
        status: "-1",
        msg: "参数异常"
      }
    }
    var obj = {
      action: "RefuseTransfer",
      reqbody: {
        BizId: obj.ali_bizid
      }
    }
    var rtn = await this.aliclient(obj)
    console.log(rtn)
    return rtn;
  }

  //完成交易成功
  async tradesuccess(obj) {
    if (!obj.ali_bizid) {
      return {
        status: "-1",
        msg: "参数异常"
      }
    }
    var obj = {
      action: "TradeSuccess",
      reqbody: {
        BizId: obj.ali_bizid
      }
    }
    var rtn = await this.aliclient(obj)
    console.log(rtn)
    return rtn;
  }

  //交易失败
  async tradefail(obj) {
    if (!obj.ali_bizid) {
      return {
        status: "-1",
        msg: "参数异常"
      }
    }
    var obj = {
      action: "TradeFail",
      reqbody: {
        BizId: obj.ali_bizid
      }
    }
    var rtn = await this.aliclient(obj)
    console.log(rtn)
    return rtn;
  }

  //买卖家沟通记录
  async writecommunicationlog(obj) {
    var obj = {
      action: "WriteCommunicationLog",
      reqbody: {
        BizId: obj.ali_bizid,
        note: obj.note
      }
    }
    var rtn = await this.aliclient(obj)
    console.log(rtn)
    return rtn;
  }

  //获取签名
  async generateuploadfilepolicy(obj) {
    var self = this;;
    var gobj = {
      action: "GenerateUploadFilePolicy",
      reqbody: { FileType: "ATTORNEY" }
    }
    if (obj.BizId) {
      gobj["reqbody"] = { BizId: BizId, FilyType: "PARTNER_SYNC_FILE" };
    }
    return await self.aliclient(gobj);
  }

  async uppaymentstatus() {
    var selsql = "select * from trade_transfer where transfer_status='PROVIDE_MATERIAL'";
    var transferinfos = await this.dao.customQuery(selsql);
    var obj = {
      action: "QueryTradeProduceList"
    }
    var tradeinfo = await this.aliclient(obj);
    if (!tradeinfo && tradeinfo.Data.TradeProduces.length > 0) {
      return {
        status: -1,
        msg: "阿里订单查询失败",
        data: null
      }
    }
    var aliorder = tradeinfo.Data.TradeProduces.length;
    var faillist = [];
    if (transferinfos) {
      for (let i = 0; i < transferinfos.length; i++) {
        var transferinfo = transferinfos[i];
        var aliorderindex = aliorder.findIndex(f => f.BizId == transferinfo.ali_bizid)
        if (aliorderindex > -1 && aliorder[aliorderindex].BuyerStatus == 10) {
          var upd = await this.dao.model.update({ transfer_status: "PAY_OVER" }, { where: { ali_bizid: transferinfo.ali_bizid } });
          if (!upd) {
            faillist.push(transferinfo.ali_bizid);
          }
        }
      }
    }
    return {
      status: 0,
      msg: "成功",
      data: faillist
    }
  }

}
module.exports = TradetransferService;
