var system = require("../../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../../config/settings");
const CtlBase = require("../../ctl.base");
const logCtl = system.getObject("web.common.oplogCtl");

var cacheBaseComp = null;
class TradetransferCtl extends CtlBase {
  constructor() {
    super("transfer", CtlBase.getServiceName(TradetransferCtl));
    this.postfile = system.getObject("util.restClient");
    this.aliApiClient = system.getObject('util.aliApiClient');

  }
  // {
  //    tid:"xxxx",
  //    log:{
  //       "dateStr":"",
  //        "timeStr":"",
  //        "yw":"",
  //        "content":""
  //     }
  //  }

  async updatePhone(p,q,req){
    if(!p.id){
      return system.getResultFail(-1,"id不能为空");
    }

    if(!p.phone){
      return system.getResultFail(-1,"手机号不能为空");
    }

    if(p.phone.length!=11){
      return system.getResultFail(-1,"手机号长度必须为11位");
    }

    if(!p.phone.startsWith("1")){
      return system.getResultFail(-1,"不是有效的手机号");
    }

    try{
      var traninfo = await this.service.findById(p.id);
      if(traninfo){
        if(traninfo.mobile&&traninfo.mobile.length==11){
          return system.getResultFail(-1,"手机号已存在，不允许修改");
        }
        var res = await this.service.updatePhone(p.id,p.phone);
        return system.getResult(res);
      }else{
        return system.getResultFail(-1,"服务单为空");
      }
    }catch (e) {
      console.log(e)
      return system.getResultFail(-1,"修改手机号异常");
    }
  }

  async aliDoubleCall(p,q,req){
    if(!p.aliBizId){
        return system.getResultFail(-1,"服务单号不能为空");
    }

    // 1.获取可用外呼号码列表
    var queryAvailabelPhoneResult = await this.aliApiClient.queryAvailabelNumbers();
    if(queryAvailabelPhoneResult.status == 0){
      if(!queryAvailabelPhoneResult.data||queryAvailabelPhoneResult.data.length==0){
        console.log('获取到的可用外呼列表为空')
        return system.getResultFail(-1,"呼叫失败。获取到的可用外呼列表为空");
      }

      console.log(queryAvailabelPhoneResult.data)

      // // 2.发起双呼
      var startCallParams = {
        "bizType": "TM_TRADE",
        "skillType":2,
        "bizId":p.aliBizId,
        "caller":settings.aliDoubleCallCaller(),
        "callCenterNumber":queryAvailabelPhoneResult.data[0]
      };
      var startCallResult = await this.aliApiClient.startBackToBackCall(startCallParams);
      if(startCallResult.status == 0){
        return system.getResultSuccess(null,"呼叫成功");
      }else{
        return system.getResultFail(-1,"呼叫失败，"+startCallResult.msg);
      }

    }else{
        console.log('获取可用外呼号码列表失败。原因：',queryAvailabelPhoneResult.msg)
        return system.getResultFail(-1,"获取可用外呼号码列表失败。原因："+queryAvailabelPhoneResult.msg);
    }
    // // 1.获取可用外呼号码列表
    // var rtn = await this.execClient.execPostWithAppkey({
    //   "actionType": "queryAvailabelNumbers",
    //   "actionBody": {
    //     "bizType": "TM_TRADE"
    //   }
    // }, settings.centerChannelUrl()+"api/action/aliyunapi/springBoard");
    // if(rtn){
    //   var result = JSON.parse(rtn.stdout)
    //   if(result.status ==0){
    //     // 可用外呼号码不为空
    //     if(result.data&&result.data.length>0){
    //         var availabelPhoneNumber = result.data[0]
    //         console.log(availabelPhoneNumber)
    //
    //         // 2.发起双呼
    //
    //
    //
    //     }else{
    //         console.log('获取可用外呼号码列表为空',rtn.stdout)
    //         return system.getResultFail(-1,"未获取到可用外呼号码列表。");
    //     }
    //   }else{
    //     console.log('获取可用外呼号码列表失败。原因:',rtn.stdout)
    //     return system.getResultFail(-1,"获取可用外呼号码列表失败，原因:"+rtn.stdout);
    //   }
    // }else{
    //   console.log('获取可用外呼号码列表失败，请求未响应',rtn)
    //   return system.getResultFail(-1,"获取可用外呼号码列表失败，请求未响应");
    // }
  }

  async track(p,q,req){
    console.log(p)
    //获取当前日期
    //获取当前时间

    p.logdata.log.dateStr=new Date().toLocaleDateString()
    p.logdata.log.timeStr=new Date().toLocaleTimeString()
    p.logdata.log.yw=req.session.user.userName
    let update=await this.service.addTrackLog(p.logdata)
    return system.getResultSuccess(update,"ok");
  }
  async submit(p, q, req) {
    if (req && req.session && req.session.user) {
      p.onlyCode = req.session.user.unionId;
    }
    if (req.codepath) {
      p.codepath = req.codepath;
    }
    var result = null;
    try {
      if (p.transfer_status == "CONFIRM_ORDER") {
        p.aliorder_status = "1",
          result = await this.service.confirmorder(p);
        console.log(result)
      }
      if (p.transfer_status == "CLOSE_ORDER_ONLY") {
        p.aliorder_status = "11",
          result = await this.service.refuseorder(p)
      }
      if (p.transfer_status == "PROVIDE_MATERIAL") {
        p.aliorder_status = "3",
          result = await this.service.supplymaterail(p)
      }
      if (p.transfer_status == "BUYER_EXPRESS") {
        p.aliorder_status = "5",
          result = await this.service.posttransfermatereial(p)
      }
      if (p.transfer_status == "BUYER_PROVIDE_MATERIAL") {
        p.aliorder_status = "6",
          result = await this.service.receivedtransfermaterail(p)
      }
      if (p.transfer_status == "SUBMIT_TO_SBJ") {
        p.aliorder_status = "7",
          result = await this.service.submittedtransfermaterail(p)
      }
      if (p.transfer_status == "SBJ_ACCEPT") {
        p.aliorder_status = "8",
          result = await this.service.acceptedtransfermaterail(p)
      }

      if (p.transfer_status == "SBJ_SUCCESS") {
        p.aliorder_status = "8",
          result = await this.service.approvedtransfer(p)
      }
      if (p.transfer_status == "SBJ_FAIL") {
        p.aliorder_status = "８",
          result = await this.service.refusetransfer(p)
      }

      if (p.transfer_status == "TRANSFER_SUCCESS") {
        p.aliorder_status = "12",
          result = await this.service.tradesuccess(p)
      }
      if (p.transfer_status == "TRANSFER_FAIL") {
        p.aliorder_status = "10",
          result = await this.service.tradefail(p)
      }
      if (p.transfer_status == "RefuseOrder") {
        p.aliorder_status = "10",
          result = await this.service.tradefail(p)
      }
      if (result && result.Success) {
        var rd = await this.service.update(p);
        return system.getResult(rd);
      } else {
        return system.getResult(null, "阿里请求失败");
      }

    } catch (error) {
      return system.getResult(null, "请求异常");
    }

  }

  async findone(p, q, req) {
    var traninfo = await this.service.findOne({ ali_bizid: p.ali_bizid });
    return { data: traninfo.dataValues, status: 0, msg: "操作成功" }
  }

  //获取签名
  async generateuploadfilepolicy(p, q, req) {
    var self = this;;
    var gobj = {
      action: "GenerateUploadFilePolicy",
      reqbody: { FileType: "LEGAL_NOTICE" }
    }
    if (p.mtype && p.mtype == 'json') {
      gobj.reqbody.FileType = 'PARTNER_SYNC_FILE';
    }
    try {
      var rst = await self.service.aliclient(gobj);
      console.log(rst)
      var source = {
        OSSAccessKeyId: rst.AccessId,
        policy: rst.EncodedPolicy,
        Signature: rst.Signature,
        Bucket: 'trade-mark-user-upload',
        url: "https://trade-mark-user-upload.oss-cn-beijing.aliyuncs.com",
        filedir: rst.FileDir
      }
      if (p.mtype && p.mtype == 'json') {
        source.url = "https://partner-sync-file.oss-cn-beijing.aliyuncs.com";
        source.Bucket = "partner-sync-file";
      }
      console.log(source)
      return source;
    } catch (e) {
      console.log(e)
    }

  }

  //更新沟通记录
  async updateCommunicationLog(p, q, req){
    var self = this;
    if(!p.ali_bizid){
      return system.getResult(null, "请求异常");
    }
    try {
      var rst = await self.service.writecommunicationlog(p);
      console.log(rst)
      return { status: 0, msg: "成功", data: {ali_bizid : p.ali_bizid} };
    } catch (e) {
      return system.getResult(null, "请求异常");
    }
  }

}
module.exports = TradetransferCtl;

