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));
    this.dingClient = system.getObject("util.dingClient");
  }

  //订单创建
  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) {
        let content = `商标有新订单：注册号【${obj.RegisterNumber}】`;
        this.dingClient.tmNotify(content)
        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 =buildurl(obj.buyer_businesslicense)
    obj.buyer_idcard =buildurl(obj.buyer_idcard)
    obj.seller_businesslicense =buildurl(obj.seller_businesslicense)
    obj.seller_idcard =buildurl(obj.seller_idcard)
    obj.seller_proxy =buildurl(obj.seller_proxy)
    obj.tm_cert_url =buildurl(obj.tm_cert_url)
    obj.seller_apply =buildurl(obj.seller_apply)
    obj.transfer_cert_url =buildurl(obj.transfer_cert_url)
    obj.notarization_url =buildurl(obj.notarization_url)
    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 writecommunicationlog2(obj) {
  var obj = {
    action: "WriteCommunicationLog",
    reqbody: {
      BizId: obj.ali_bizid,
      note: obj.note
    }
  }
  var rtn = await this.aliclient(obj)
  console.log(rtn)
  return rtn;
}
  // {
  //   "dateStr":"",
  //   "timeStr":"",
  //   "yw":"",
  //   "content":""
  // }
  async addTrackLog(obj){
    var self=this;
    let tid=obj.tid;//如果是来自租户界面的修改
    let log=obj.log;
    let strlog=JSON.stringify(log)
    return  this.db.transaction(async function (t) {
      let logupdate=await self.dao.model.findOne({where:{id:tid},transaction:t});
      if(logupdate.tracklog!=""){
        strlog+="|"+logupdate.tracklog
      }
      await self.dao.model.update({"tracklog":strlog},{where:{id:tid},transaction:t});
      //调用阿里的接口进行交易记录的上传
      let obj={
        ali_bizid: logupdate.ali_bizid,
        note: log.content
      }
      let rn =await self.writecommunicationlog2(obj)
      if(!rn){
        console.log(logupdate.ali_bizid,"日志到阿里出错....")
        throw new Error("阿里上传日志错误")
      }else{
        console.log(rn)
      }

      logupdate=await self.dao.model.findOne({where:{id:tid},transaction:t});
      return logupdate;
    });

  }
  //买卖家沟通记录
  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);
  }

  /**
   * 买家状态 BuyerStatus
   0:"预付款已支付"
   1:"用户已取消订单"
   2:"服务商已确认订单"
   3:"合作方拒绝订单"
   10:"合作方已提交转让文件"
   11:"用户已支付尾款，已确认资料"
   20:"合作方已邮寄转让文件，用户待接收"
   21:"用户已邮寄转让资料"
   22:"阿里云资料已收到"
   23:"审核资料"
   30:"递交到商标局"
   31:"商标局已接收"
   32:"转让失败"
   33:"转让成功"
   40:"交易成功"
   41:"交易失败"
   */
  async uppaymentstatus() {
    var selsql = "select * from trade_transfer where transfer_status='PROVIDE_MATERIAL' or transfer_status='BUYER_EXPRESS'";
    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;
    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 == 11) {
          var upd = await this.dao.model.update({ transfer_status: "PAY_OVER" }, { where: { ali_bizid: transferinfo.ali_bizid } });
          if (!upd) {
            faillist.push(transferinfo.ali_bizid);
          }
        }
        if (aliorderindex > -1 && aliorder[aliorderindex].BuyerStatus == 22) {
          var upd = await this.dao.model.update({ transfer_status: "MATERIAL_PROVIDE" }, { where: { ali_bizid: transferinfo.ali_bizid } });
          if (!upd) {
            faillist.push(transferinfo.ali_bizid);
          }
        }
      }
    }
    return {
      status: 0,
      msg: "成功",
      data: faillist
    }
  }

}
function buildurl(url){
  if (url && url.indexOf("com/") > -1){
    return url.split("com/")[1]
  }
  return url
}
module.exports = TradetransferService;