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 updatePhone(id,mobile){
    var self = this;
    return await this.db.transaction(async function (t) {
      var updateRes = await self.dao.model.update({"mobile":mobile},{where:{id:id},transaction:t});
      return updateRes;
    });
  }
  //订单创建
  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 modifySubmitTransferMaterail(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: "ModifySubmitTransferMaterail",
    reqbody: {
      BizId: obj.ali_bizid,
      BuyerBusinessLicense: obj.buyer_businesslicense,
      BuyerIdCard: obj.buyer_idcard,
      RegistrationCert: obj.tm_cert_url,
      Notarization: obj.notarization_url + "," + obj.transfer_cert_url,
      SellerBusinessLicense: obj.seller_businesslicense,
      SellerIdCard: obj.seller_idcard,
      SellerProxy: obj.seller_proxy,
      SellerApply: obj.seller_apply,
      Complete: true,
      Name: obj.buyer_name,
      Addr: obj.buyer_address,
      CardType: obj.user_type,
      CardNo: obj.cardno,
      ContactName: obj.contact_name,
      ContactMobile: parseInt(obj.contact_mobile),
      ContactEmail: obj.contact_email
    }
  }
  var result = await this.aliclient(sobj,'POST')
  console.log(result);
  return result;
  // return {Success:false,msg:""}
}

  //尾款支付---调取阿里云查询后修改订单
  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: "参数异常"
      }
    }
    //先存储到库里
    await this.dao.update(obj)
    var BizId = obj.ali_bizid;
    var obj = {
      action: "ReceivedTransferMaterail",
      reqbody: {
        BizId: BizId,
        Note:!obj.remark?"":obj.remark,
        BuyerBusinessLicense:buildurl(obj.buyer_businesslicense),
        BuyerIdCard:buildurl(obj.buyer_idcard),
        RegistrationCert:buildurl(obj.tm_cert_url),
        Notarization:buildurl(obj.notarization_url),
        SellerBusinessLicense:buildurl(obj.seller_businesslicense),
        SellerIdCard:buildurl(obj.seller_idcard),
        SellerProxy:buildurl(obj.seller_proxy),
        BuyersCardType:obj.user_type=="ent"?"1":"2",
        SellerBusinessLicenseTranslation:buildurl(obj.buyer_businesslicense_en),
        BuyerBusinessLicenseTranslation:buildurl(obj.seller_businesslicense_en),
        AssigneeProxy:buildurl(obj.buyer_proxy),
        CardType:obj.seller_type=="ent"?"1":"2",
      }
    }
    var rtn = await this.aliclient(obj,"POST")
    console.log(obj)
    console.log(rtn)
    return rtn;
  }

  //服务商递交到商标局
  async submittedtransfermaterail(obj) {
    if (!obj.ali_bizid) {
      return {
        status: "-1",
        msg: "参数异常"
      }
    }

    if(!obj.transfer_receive_ack){
      return {
        status: "-1",
        msg: "参数异常：商标局回执不能为空"
      }
    }

    // if(!obj.seller_proxy){
    //   return {
    //     status: "-1",
    //     msg: "参数异常：受让人委托书不能为空"
    //   }
    // }

    const entity = await this.findById(obj.id);
    // 只有当前流程状态等于 阿里云审核通过 时，才允许提交官方
    if(entity.transfer_status != 'PASS_ALIYUN_VERIFY'){
      return {
        status: "-1",
        msg: "流程状态等于 阿里云审核通过 时，才允许提交官方"
      }
    }

    const transfer_receive_ack = buildurl(obj.transfer_receive_ack)
   // const seller_proxy = buildurl(obj.seller_proxy)

    var BizId = obj.ali_bizid;
    var obj = {
      action: "SubmittedTransferMaterail",
      reqbody: {
        BizId: BizId,
        TransferOsskey: transfer_receive_ack, // 商标局回执 add
       // AssigneeProxy: seller_proxy, // 受让人委托书 add
      }
    }
    var rtn =  await this.aliclient(obj);
    console.log(rtn);
    return rtn;
  }

  //商标局受理
  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:"交易失败"
   */
  //BUYER_PROVIDE_MATERIAL理解为确认买家已经提供了资料(阿里那边应该是审核中了)
  //"MATERIALS_TO_BE_SUBMITTED":"待服务商重新提交资料"-26,
  //"PASS_ALIYUN_VERIFY":"阿里云审核通过"-25,

  async uppaymentstatus() {
    var selsql = "select * from trade_transfer where transfer_status='PROVIDE_MATERIAL' or transfer_status='BUYER_EXPRESS' or transfer_status='BUYER_PROVIDE_MATERIAL' or transfer_status='MATERIALS_TO_BE_SUBMITTED'";
    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);
          }
        }
        if (aliorderindex > -1 && aliorder[aliorderindex].BuyerStatus == 26) {
          var upd = await this.dao.model.update({ transfer_status: "MATERIALS_TO_BE_SUBMITTED",aliorder_status:26 }, { where: { ali_bizid: transferinfo.ali_bizid } });
          if (!upd) {
            faillist.push(transferinfo.ali_bizid);
          }
        }
        if (aliorderindex > -1 && aliorder[aliorderindex].BuyerStatus == 25) {
          var upd = await this.dao.model.update({ transfer_status: "PASS_ALIYUN_VERIFY",aliorder_status:25 }, { where: { ali_bizid: transferinfo.ali_bizid } });
          if (!upd) {
            faillist.push(transferinfo.ali_bizid);
          }
        }
      }
    }
    return {
      status: 0,
      msg: "成功",
      data: faillist
    }
  }

  //阿里调用测试
  async queryAuditStateFromAli(){
    var obj = {
      action: "QueryTradeProduceList",
      reqbody:{
        pageSize:100,
        BuyerStatus:25
      }
    }
    var tradeinfo = await this.aliclient(obj);
    return tradeinfo
  }

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

// (async ()=>{
//   let rs=await new TradetransferService().queryAuditStateFromAli()
//   console.log(JSON.stringify(rs.Data.TradeProduces))
// })()