const system = require("../../../system");
const crypto = require('crypto');
var settings = require("../../../../config/settings");
const AppServiceBase = require("../../app.base");
class CenterorderService extends AppServiceBase {
  constructor() {
    super();
    this.centerOrderUrl = settings.centerOrderUrl();
    this.execClient = system.getObject("util.execClient");
    this.aliclient = system.getObject("util.aliyunClient");
    this.cacheManager = system.getObject("db.common.cacheManager");
    this.utilsOrderSve = system.getObject("service.utilsSve.utilsOrderSve");
    this.utilsPushSve = system.getObject("service.utilsSve.utilsPushSve");
    this.utilsTmAliyunSve = system.getObject("service.utilsSve.utilsTmAliyunSve");//测试用
  };
  //调用center-order 
  async reqCenterOrderApi(pobj, reqUrl) {
    var url = this.centerOrderUrl + "action/icapi/springBoard";
    if (reqUrl) {
      var url = this.centerOrderUrl + reqUrl;
    }
    var rtn = await this.execClient.execPost(pobj, url);
    var data = JSON.parse(rtn.stdout);
    return data;
  }

  //--------------------------阿里IC---start--------------------------------------------------------
  //提交公司注册方案
  async submitProgramme(pobj) {
    var res = await this.reqCenterOrderApi(pobj);
    if (res && res.status == 0 && res.data && res.data.needinfo && res.data.needsolution) {
      var needinfo = res.data.needinfo;//需求信息
      var needsolution = res.data.needsolution;//方案信息
      var ab = pobj.actionBody;
      if (typeof (ab.solutionContent) == "string") {
        ab.solutionContent = JSON.parse(ab.solutionContent);
      }
      //推送数据至阿里
      var bizType = needinfo.channelTypeCode;//业务类型里
      var pushObj = {
        intentionBizId: needinfo.channelNeedNo, bizType: bizType, solution: JSON.stringify(ab.solutionContent.solution)
      };
      var self = this;
      //推送方案
      this.pushSubmitSolution(pushObj, needsolution.solutionNo, pobj.appInfo, self);
      // this.aliclient.reqbyget({action:"SubmitSolution",reqbody:pushObj}).then(pushRes=>{
      //   if(pushRes && pushRes.status==0 && pushRes.data){
      //     var resData = pushRes.data;
      //     var reqObj2 = {
      //       actionType:"receiveProgrammeNo",
      //       actionBody:{
      //         solutionNo:needsolution.solutionNo,
      //         solutionBizId:resData.SolutionBizId
      //       }
      //     };
      //     self.reqCenterOrderApi(reqObj2);//保存渠道方案id
      //   }
      // });
      //推送需求小记
      if (needinfo.pushflag && needinfo.pushflag == 1) {//推送标志 值为1推送需求小记
        var pushObj2 = {
          intentionBizId: needinfo.channelNeedNo, note: "创建方案"
        };
        this.aliclient.reqbyget({ action: "SubmitIntentionNote", reqbody: pushObj2 });
      }
    }
    return system.getResultSuccess();
  }
  //推送方案
  async pushSubmitSolution(pushObj, solutionNo, appInfo, self) {
    var pushRes = await self.aliclient.reqbyget({ action: "SubmitSolution", reqbody: pushObj });
    if (pushRes && pushRes.status == 0 && pushRes.data) {
      var resData = pushRes.data;
      var reqObj2 = {
        actionType: "receiveProgrammeNo",
        appInfo: appInfo,
        actionBody: {
          solutionNo: solutionNo,
          solutionBizId: resData.SolutionBizId
        }
      };
      var a = await self.reqCenterOrderApi(reqObj2);//保存渠道方案id
      return a;
    }
  }
  //服务商方案作废
  async abolishProgramme(pobj) {
    var res = await this.reqCenterOrderApi(pobj);
    if (res && res.status == 0 && res.data && res.data.channelSolutionNo) {
      //推送数据至阿里
      var pushObj = {
        solutionBizId: res.data.channelSolutionNo, note: pobj.actionBody.note || ""
      };
      this.aliclient.reqbyget({ action: "RejectSolution", reqbody: pushObj })
    }
    return res;
  }

  //支付回调
  async paySuccess(pobj) {
    var actionBody = pobj.actionBody;
    if (!pobj.actionBody.orderNo) {
      return system.getResult(null, "orderNo不能为空");
    }
    if (!actionBody.orderPrice) {
      return system.getResult(null, "orderPrice不能为空");
    }
    if (!actionBody.phone) {
      return system.getResult(null, "phone不能为空");
    }

    if (pobj.actionBody.companyName) {
      if (!actionBody.city) {
        return system.getResult(null, "city不能为空");
      }
      if (!actionBody.companyCategory) {
        return system.getResult(null, "companyCategory不能为空");
      }
      if (!actionBody.orgType) {
        return system.getResult(null, "orgType不能为空");
      }
      if (!actionBody.industryType) {
        return system.getResult(null, "industryType不能为空");
      }
      if (!actionBody.scope) {
        return system.getResult(null, "scope不能为空");
      }
      pobj.actionBody.regType = "ali.companyreg"
    } else if (pobj.actionBody.park) {
      if (!actionBody.productType) {
        return system.getResult(null, "productType不能为空");
      }
      pobj.actionBody.regType = "ali.companyreg_cloud"
    } else {
      return system.getResult(null, "参数异常");
    }
    var sobj = {
      actionType: "getaliicProduce",
      actionBody: pobj.actionBody,
      appInfo: pobj.appInfo,
      actionProcess: pobj.actionProcess
    }

    var url = settings.centerAppUrl() + "action/opProduct/springBoard";
    var rtn = await this.execClient.execPost(sobj, url);
    if (!rtn || !rtn.stdout) {
      return system.getResultFail(-5010, "产品查询失败");
    }
    var data = JSON.parse(rtn.stdout);
    if (data.status != 0) {
      return system.getResultFail(-5010, "产品查询失败");
    }
    pobj.actionBody = data.data;
    // var needNo="";

    // if(solutiondata.data){
    //   needNo=solutiondata.data.channelNeedNo;
    // }
    pobj.actionBody.totalSum = pobj.actionBody.orderPrice;
    pobj.actionBody.payTotalSum = pobj.actionBody.orderPrice;
    pobj.actionBody.quantity = 1;
    pobj.actionBody.channelOrder = {
      channelServiceNo: pobj.actionBody.orderNo,
      channelOrderNo: pobj.actionBody.orderNo,
      orderStatus: 2
    }
    var orderrtn = await this.utilsOrderSve.addOrder(pobj, pobj.actionBody);
    if (orderrtn.status != 0) {
      if (orderrtn.status == -1) {
        return system.getResultSuccess(null, "订单已经创建");
      }
      return system.getResultFail(-5012, "订单创建失败");
    }
    if (orderrtn.data) {
      pobj.actionBody.orderNo = orderrtn.data.orderNo
    }
    if (pobj.actionBody.solutionBizId) {
      pobj.actionBody.channelSolutionNo = pobj.actionBody.solutionBizId;
      pobj.actionType = "receiveSolutionPayInfo";
    } else {
      pobj.actionType = "createSolutionByOrder";
    }
    var url = settings.centerOrderUrl() + "action/icapi/springBoard";
    var solutionrtn = await this.execClient.execPost(pobj, url);
    if (!solutionrtn || !solutionrtn.stdout) {
      return system.getResultFail(-5011, "方案查询失败");
    }
    var solutiondata = JSON.parse(solutionrtn.stdout);
    if (solutiondata.status != 0) {
      return system.getResultFail(-5011, "方案查询失败");
    }
    if (solutiondata.data && solutiondata.data.channelNeedNo) {
      pobj.actionBody.needId = solutiondata.data.channelNeedNo;
    }
    if (solutiondata.status == 0) {
      pobj.actionBody.orderNo = pobj.actionBody.channelOrder.channelOrderNo;
      this.utilsPushSve.aliBusiness2Fq(pobj, "pushOrderBusiness");
    }
    return system.getResultSuccess();
  }

  async icppaysuccess(pobj) {

    var sobj = {
      actionType: "getaliicpProduce",
      // actionBody: { typeCode: itemResult.data.channelTypeCode, province: itemResult.data.province },
      actionBody: { typeCode: pobj.actionBody.channelTypeCode, province: pobj.actionBody.province },
      appInfo: pobj.appInfo,
      actionProcess: pobj.actionProcess
    }

    var url = settings.centerAppUrl() + "action/opProduct/springBoard";
    var rtn = await this.execClient.execPost(sobj, url);
    if (!rtn || !rtn.stdout) {
      return system.getResultFail(-5010, "产品查询失败");
    }
    var data = JSON.parse(rtn.stdout);
    if (data.status != 0) {
      return system.getResultFail(-5010, "产品查询失败");
    }
    // pobj.actionBody = data.data;
    pobj.actionBody.orderNo = pobj.actionBody.bizId;
    pobj.actionBody.totalSum = data.data.price;
    pobj.actionBody.orderPrice = data.data.price;
    pobj.actionBody.payTotalSum = data.data.price;
    pobj.actionBody.payCode = data.data.payCode;
    pobj.actionBody.channelItemCode = data.data.channelItemCode;
    pobj.actionBody.quantity = 1;
    pobj.actionBody.channelOrder = {
      channelServiceNo: pobj.actionBody.orderNo,
      channelOrderNo: pobj.actionBody.orderNo,
      orderStatus: 2
    }
    var orderrtn = await this.utilsOrderSve.addOrder(pobj, pobj.actionBody);
    if (orderrtn.status != 0) {
      if (orderrtn.status == -1) {
        return system.getResultSuccess(null, "订单已经创建");
      }
      return system.getResultFail(-5012, "订单创建失败");
    }
    if (orderrtn.data) {
      pobj.actionBody.orderNo = orderrtn.data.orderNo
    }

    pobj.actionType = "receiveSolutionPayInfo";
    var url = settings.centerOrderUrl() + "action/icapi/springBoard";
    var solutionrtn = await this.execClient.execPost(pobj, url);
    if (!solutionrtn || !solutionrtn.stdout) {
      return system.getResultFail(-5011, "方案查询失败");
    }
    var solutiondata = JSON.parse(solutionrtn.stdout);
    if (solutiondata.status != 0) {
      return system.getResultFail(-5011, "方案查询失败");
    }
    if (solutiondata.data && solutiondata.data.channelNeedNo) {
      pobj.actionBody.needId = solutiondata.data.channelNeedNo;
    }
    if(pobj.actionBody.channelItemCode=='5'){
      pobj.actionBody.regType="ali.icp";
    }else if(pobj.actionBody.channelItemCode=='7'){
      pobj.actionBody.regType="ali.edi";
    }
    if (solutiondata.status == 0) {
      pobj.actionBody.orderNo = pobj.actionBody.channelOrder.channelOrderNo;
      this.utilsPushSve.aliBusiness2Fq(pobj, "paySuccess");
    }
    return system.getResultSuccess();
  }
  //--------------------------阿里IC---end--------------------------------------------------------

  //--------------------------阿里ICP---start--------------------------------------------------------
  //提交公司注册方案
  async submitIcpProgramme(pobj) {
    var res = await this.reqCenterOrderApi(pobj, "action/icpapi/springBoard");
    if (res && res.status == 0 && res.data && res.data.needinfo && res.data.needsolution) {
      var needinfo = res.data.needinfo;//需求信息
      var needsolution = res.data.needsolution;//方案信息
      var ab = pobj.actionBody;
      if (typeof (ab.solutionContent) == "string") {
        ab.solutionContent = JSON.parse(ab.solutionContent);
      }
      if (typeof (needsolution.solutionContent) == "string") {
        needsolution.solutionContent = JSON.parse(needsolution.solutionContent);
      }
      var solution = needsolution.solutionContent.solution;
      //推送数据至阿里
      var bizType = needinfo.channelTypeCode;//业务类型里
      var pushObj = {
        IntentionBizId: needinfo.channelNeedNo,
        CompanyName: solution.CompanyName, IcpType: solution.IcpType, CompanyAddress: solution.CompanyAddress,
        Area: solution.Area, Note: solution.Note
      };
      var self = this;
      //推送方案
      this.pushIcpSolution(pushObj,needsolution.solutionNo,pobj.appInfo,self);
      return system.getResultSuccess();
    }
    return res;
  }
  //推送ICP方案
  async pushIcpSolution(pushObj, solutionNo, appInfo, self) {
    //推送方案信息
    var pushRes = await self.aliclient.reqbyget({ action: "SubmitIcpSolution", reqbody: pushObj, apiVersion: "2019-05-08" });
    if (pushRes && pushRes.status == 0 && pushRes.data) {
      var resData = pushRes.data;
      if (resData.BizId) {
        var reqObj2 = {
          actionType: "receiveProgrammeNo",
          appInfo: appInfo,
          actionBody: {
            solutionNo: solutionNo,
            solutionBizId: resData.BizId
          }
        };
        var a = await self.reqCenterOrderApi(reqObj2);//保存渠道方案id
        if (a && a.status == 0) {
          //推送方案确认信息
          await self.aliclient.reqbyget({action:"ConfirmIntention",reqbody:{BizId:pushObj.IntentionBizId},apiVersion:"2019-05-08"});
        }
      }
    }
  }
  //材料链接转换
  async materialUrlConversion(pobj) {
    // if(!pobj || !pobj.actionBody || !pobj.actionBody.material){
    //   return pobj;
    // }
    // var material = pobj.actionBody.material;
    // if(material.PartnerBusinessLicense){//营业执照
    //   var aliPartnerBusinessLicense = await this.utilsTmAliyunSve.getAliOssFileUrl("trade-mark-user-upload", pobj, this.utilsTmAliyunSve.aliOssFileType.BUSINESS_LICENSE, material.PartnerBusinessLicense, rpcParam);
    // }
  }
  //icp材料提交
  async submitIcpMaterial(pobj) {
    // pobj = await this.materialUrlConversion(pobj);
    var res = await this.reqCenterOrderApi(pobj, "action/icpapi/springBoard");
    if (res && res.status == 0 && res.data) {
      var needsolution = res.data;//方案信息
      var ab = pobj.actionBody;
      if (typeof (ab.material) == "string") {
        ab.material = JSON.parse(ab.material);
      }
      var material = ab.material;
      //推送数据至阿里 
      var BizId = ab.BizId;//⽅案业务ID
      var pushObj = {
        "BizId": BizId,
        "Domain": material.Domain,
        "CorporateName": material.CorporateName,
        "IncludeForeignInvestment": material.IncludeForeignInvestment,
        "PartnerBusinessLicense": material.PartnerBusinessLicense,
        "PartnerIdCardList": material.PartnerIdCardList,
        "PartnerDomainCertificate": material.PartnerDomainCertificate,
        "PartnerPreviewOtherList": material.PartnerPreviewOtherList || [],
        "PartnerPlan": material.PartnerPlan || "",
        "PartnerForeignInvestment": material.PartnerForeignInvestment || "",
        "PartnerLaw": material.PartnerLaw || "",
        "PartnerStampOtherList": material.PartnerStampOtherList || [],
        "PartnerSignOtherList": material.PartnerSignOtherList || [],
        "PartnerSignAndStampOtherList": material.PartnerSignAndStampOtherList || []
      };
      var self = this;
      //推送方案材料
      self.aliclient.reqbyget({action:"SavePartnerSubmitMaterial",reqbody:pushObj,apiVersion:"2019-05-08"});
      return system.getResultSuccess();
    }
    return res;
  }
  //icp通知状态变更
  async acceptIcpPartnerNotification(pobj) {
    var res = await this.reqCenterOrderApi(pobj, "action/icpapi/springBoard");
    if (res && res.status == 0 && res.data) {
      var ab = pobj.actionBody;
      //推送数据至阿里
      // var pushObj = res.data;
      var pushObj = {
        BizId:res.data.BizId,
        OfficialFileURL:res.data.OfficialFileURL,
        ApplicationStatus:res.data.ApplicationStatus
      };
      //推送方案
      this.aliclient.reqbyget({action:"AcceptPartnerNotification",reqbody:pushObj,apiVersion:"2019-05-08"});
      return system.getResultSuccess();
    }
    return res;
  }
  //服务商icp方案关闭
  async abolishIcpProgramme(pobj) {
    var res = await this.reqCenterOrderApi(pobj, "action/icpapi/springBoard");
    if (res && res.status == 0 && res.data) {
      var needsolution = res.data;//方案信息
      var ab = pobj.actionBody;
      if (typeof (ab.material) == "string") {
        ab.material = JSON.parse(ab.material);
      }
      //推送数据至阿里
      var pushObj = {
        BizId: ab.BizId, Note: ab.Note
      };
      //关闭方案
      this.aliclient.reqbyget({action:"CloseIcpProduce",reqbody:pushObj,apiVersion:"2019-05-08"});
      return system.getResultSuccess();
    }
    return res;
  }
  //--------------------------阿里ICP---end--------------------------------------------------------
  //LOGO场景接口服务
  async downloadlogoscene(pobj){
    var reqUrl = "http://123.57.217.203:4724/api/downloadscene";//"http://ailogo-service/api/downloadscene";
    var obj = pobj.actionBody;
    if(!obj.title){
      return system.getResult(null,"品牌名称不能为空");
    }
    if(!obj.id){
      return system.getResult(null,"品牌id不能为空");
    }
    var rtn = null;
    try {
      rtn = await this.execClient.execPost(obj, reqUrl);
      var res = JSON.parse(rtn.stdout);
      return res;
    }catch (e) {
      return system.getResult(null,"获取logo场景异常");
    }
  }
  //换一批logo
  async changelogo(pobj){
    var reqUrl = "http://123.57.217.203:4724/api/changelogo";
    var obj = pobj.actionBody;
    if(!obj.title){
      return system.getResult(null,"品牌名称不能为空");
    }
    if(!obj.profession){
      return system.getResult(null,"行业名称不能为空");
    }
    if(!obj.description){
      obj.description="";
    }
    var rtn = null;
    try {
      rtn = await this.execClient.execPost(obj, reqUrl);
      var res = JSON.parse(rtn.stdout);
      return res;
    }catch (e) {
      return system.getResult(null,"获取logo异常");
    }
  }
  //生成logo
  async singlelogo(pobj){
    var reqUrl = "http://123.57.217.203:4724/api/singlelogo";
    var obj = pobj.actionBody;
    if(!obj.title){
      return system.getResult(null,"品牌名称不能为空");
    }
    // if(!obj.subtitle){
    //   return system.getResult(null,"品牌标语不能为空");
    // }
    if(!obj.profession){
      return system.getResult(null,"行业名称不能为空");
    }
    if(!obj.description){
      obj.description="";
    }
    var rtn = null;
    try {
      rtn = await this.execClient.execPost(obj, reqUrl);
      var res = JSON.parse(rtn.stdout);
      if(res && res.status==0 && res.data){
        return res;//system.getResultSuccess(res.data);
      }else{
        return system.getResult(null,"生成logo操作失败");
      }
      
    }catch (e) {
      return system.getResult(null,"生成logo操作异常");
    }
  }
}
module.exports = CenterorderService;
// var task = new CenterorderService();
// var pobj={
//   "actionType":"submitProgramme",
//   "actionBody":{
//       "needNo":"I20200323132918000001",
//       "solutionContent":'{"bizType":"esp.companyreg","solution":{"companyName":"北京联大共享科技有限公司","city":"北京市","area":"朝阳区","companyCategory":"内资小规模","companyType":"集团","orgType":"有限公司","industryType":"科技类","scope":"测试经营范围","remark":"方案备注测试方案"},"notes":"","totalSum":""}',
//       "createUserId":177,
//       "channelNeedNo":"I20200323132918000001",
//       "solutionNo":"NS2020032315041UIBzq",
//       "status":"dqr"
//   },
//   "appInfo":{
//       "id":17,
//       "app_hosts":"gsbweb.qifu.gongsibao.com",
//       "app_code":"gsbweb",
//       "app_name":"公司宝官网web应用",
//       "uapp_id":"22",
//       "uapp_key":"201912141625",
//       "uapp_secret":"8cbb846776874167b5c7e01cd0116c66",
//       "contact_name":"宋毅",
//       "contact_mobile":"15010929366",
//       "contact_email":null,
//       "is_enabled":1,
//       "is_sign":0,
//       "pay_type":"10",
//       "delivery_type":"10",
//       "created_at":"2020-03-11T22:13:48.000Z",
//       "version":0,
//       "token":"d23241c188814e12af41d7c9032712d3"
//   },
//   "actionProcess":"gsbweb",
//   "userInfo":{
//       "id":177,
//       "uapp_id":22,
//       "channel_userid":"13075556693",
//       "channel_username":"13075556693",
//       "channel_nickname":"庄冰",
//       "open_id":null,
//       "head_url":null,
//       "mobile":"13075556693",
//       "org_name":"汉唐集团",
//       "org_path":"",
//       "email":"",
//       "is_admin":0,
//       "is_super":0,
//       "is_enabled":1,
//       "userpin":"c49330125e0445019d1ea5acfcb41927"
//   }
// };
// var self = task;
// var pushObj = {
//   status:0,
//   data:{
//       "RequestId":"771F6CB6-9FA0-4DE7-AB49-8B41B0F5D45D",
//       "ErrorMsg":"",
//       "ErrorCode":"",
//       "SolutionBizId":"S20200323174838000001",
//       "Success":true
//   }
// };
// var appInfo={
//   "id":17,
//   "app_hosts":"gsbweb.qifu.gongsibao.com",
//   "app_code":"gsbweb",
//   "app_name":"公司宝官网web应用",
//   "uapp_id":"22",
//   "uapp_key":"201912141625",
//   "uapp_secret":"8cbb846776874167b5c7e01cd0116c66",
//   "contact_name":"宋毅",
//   "contact_mobile":"15010929366",
//   "contact_email":null,
//   "is_enabled":1,
//   "is_sign":0,
//   "pay_type":"10",
//   "delivery_type":"10",
//   "created_at":"2020-03-11T22:13:48.000Z",
//   "version":0,
//   "token":"d23241c188814e12af41d7c9032712d3"
// };
//推送方案
// task.pushSubmitSolution(pushObj,"NS202003231748T0zBlC",appInfo,self).then(d=>{
//   console.log(d,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
// })
// 提方案-SubmitSolution
// 作废方案-RejectSolution
// 提需求小记-SubmitIntentionNote
// 查需求小记-ListIntentionNote