const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require('../../../../config/settings')
class TrademarkcaseService extends ServiceBase {
  constructor() {
    super("rejreex", ServiceBase.getDaoName(TrademarkcaseService))
    this.restClient = system.getObject("util.restClient")
    this.tkurl = settings.qftkurl()
    this.qfurl = settings.qifuurl()
    this.queueurl = settings.queueUrl()
  }

  async createOrUpdate (params) {
    let isOrder = undefined
    if (params.orderId) {
      isOrder = await this.dao.findOne({ orderId: params.orderId })
    }
    if (isOrder) {
      params.id = isOrder.id
      // this.pushQf(params.id)
      return await this.dao.update(params)
    } else {
      params.recDate = new Date()
      if (params.id) {
        let statusArr = ["待完善材料", "待审核", "申请递交中"]
        let dt = await this.dao.findOne({ id: params.id })
        if (statusArr.indexOf(dt.tradeStatus) != -1) {
          params.rejStatus = '待提报'
        }
        if (params.askForData && params.askForData.rmLicense) {
          if (statusArr.indexOf(dt.tradeStatus) != -1) {
            params.caStatus = "待提报"
          }
        }
        if (params.usccode && params.applicant && params.applicant.applicantName && Object.keys(params.applicant).length == 1) {
          let sql = ""
          if (dt.applicant) {
            sql = `UPDATE tmrejask_info SET applicant=json_set(applicant, '$.applicantName', "${params.applicant.applicantName}"), ${params.tradeType ? `tradeType=${params.tradeType}` : ""}, ${params.usccode ? `usccode="${params.usccode}"` : ""}, ${params.agentName ? `agentName="${params.agentName}"` : ""}, ${params.askforId ? `askforId="${params.askforId}"` : ""} WHERE id = ${params.id};`
          } else {
            sql = `UPDATE tmrejask_info SET applicant=json_object(applicant, '$.applicantName', "${params.applicant.applicantName}"), ${params.tradeType ? `tradeType=${params.tradeType}` : ""}, ${params.usccode ? `usccode="${params.usccode}"` : ""}, ${params.agentName ? `agentName="${params.agentName}"` : ""}, ${params.askforId ? `askforId="${params.askforId}"` : ""} WHERE id = ${params.id};`
          }
          return await this.dao.customExecAddOrPutSql(sql);
          // this.pushQf(params.id)
        } else {
          let res = await this.dao.update(params)
          if (params.tradeStatus) {
            if (['待完善材料', '已接单'].indexOf(params.tradeStatus) == -1) {
              this.pushQf(params.id)
            }
          }
          return res
        }
      } else {
        if (params.askForData && params.askForData.rmLicense) {
          params.caStatus = "待提报"
        }
        if (!params.caseId) {
          params.caseId = `CS${new Date().getTime()}ae${Math.floor(Math.random() * 100)}`
        }
        // this.pushQf(params.orderId, 'od')
        return await this.dao.create(params)
      }
    }
  }

  async createOffical (data) {
    let res = await this.dao.update(data)
    this.pushOff(data.id)
    return res
  }

  async getCase (id) {
    let query = {
      where: {
        caseId: id
      }
    }
    let result = await this.dao.model.findOne(query)
    return result
  }

  async getCaseList (params) {
    params.pageInfo = params.pageInfo || { pageNo: 1, pageSize: 10 }
    return await this.dao.findAndCountAll(params)
    // return await this.dao.model.findAndCountAll(query)
  }

  async pushQf (id, tp) {
    let tmpdata
    if (tp == 'od') {
      tmpdata = await this.dao.findOne({ orderId: id })
    } else {
      tmpdata = await this.dao.findOne({ id })
    }
    let reqdata = this.orgdata(tmpdata)

    let req = {
      actionType: "getAppTokenByHosts",
      actionBody: {}
    }
    let tkurl = this.tkurl
    let tokenData = await this.restClient.execPost(req, tkurl)
    tokenData = JSON.parse(tokenData.stdout)
    if (tokenData.status == 0) {
      let token = tokenData.data.token
      console.log(token)
      req.actionType = "receiveDeliveryData"
      req.actionBody = reqdata
      let queuereq = {
        actionType: "produceData",
        actionBody: {
          pushUrl: this.qfurl,
          actionType: req.actionType,
          notifyUrl: "",
          identifyCode: "tmReDeliver",
          messageBody: req.actionBody,
          headData: { token }
        }
      }
      let res = await this.restClient.execPost(queuereq, this.queueurl)
      return res
    } else {
      return "--"
    }
  }

  async pushOff (id) {
    let tmpdata = await this.dao.findOne({ id })
    let reqdata =
    {
      orderNo: tmpdata.orderId,
      officialData: {
        askforId: tmpdata.askforId,
        tradeType: tmpdata.tradeType,
        tradeImg: tmpdata.tradeImg,
        applicantName: tmpdata.applicant.applicantName,
        fileType: tmpdata.offical.otype, // 官文类型
        received_at: tmpdata.offical.oDate,
        dir: tmpdata.offical.dir
      }
    }

    let req = {
      actionType: "getAppTokenByHosts",
      actionBody: {}
    }
    let tkurl = this.tkurl
    let tokenData = await this.restClient.execPost(req, tkurl)
    console.log(tokenData)
    tokenData = JSON.parse(tokenData.stdout)
    if (tokenData.status == 0) {
      let token = tokenData.data.token
      req.actionType = "addOfficial"
      req.actionBody = reqdata
      let queuereq = {
        actionType: "produceData",
        actionBody: {
          pushUrl: this.qfurl,
          actionType: req.actionType,
          notifyUrl: "",
          identifyCode: "tmReDeliverOffcial",
          messageBody: req.actionBody,
          headData: { token }
        }
      }
      let res = await this.restClient.execPost(queuereq, this.queueurl)
      return res
    } else {
      return "--"
    }
  }

  orgdata (data) {
    let datat = {}
    let res = {}
    res.orderNo = data.orderId
    let apply = {
      askforId: data.askforId,
      tradeImg: data.tradeImg,
      tradeType: data.tradeType,
      applicantName: data.v_applicantName,
      usccode: data.usccode,
      agentName: data.agentName
    }
    datat.apply = apply
    datat.applyUser = data.applicant
    datat.applyUser.usccode = data.usccode

    datat.trademarkRejInfo = data.trademarkRejInfo

    datat.askForData = data.askForData

    datat.deliveryStatusName = data.tradeStatus

    datat.supData = data.supData
    datat.recDate = data.recDate
    datat.askforDate = data.askforDate
    res.deliveryData = datat
    return res
  }
}
module.exports = TrademarkcaseService;
