const system = require("../../../system");
const ServiceBase = require("../../sve.base");
class TrademarkcaseService extends ServiceBase {
  constructor() {
    super("rejreex", ServiceBase.getDaoName(TrademarkcaseService))
    this.agentDao = system.getObject("db.rejreex.agentDao")
    this.applicantDao = system.getObject('db.rejreex.applicantDao')
  }

  async createOrUpdate (params) {
    let isOrder = undefined
    if (params.orderId) {
      isOrder = await this.dao.findOne({ orderId: params.orderId })
    }
    if (isOrder) {
      params.id = isOrder.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) {
          let sql = ""
          sql = `UPDATE trademarkcase 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};`
          return await this.dao.customExecAddOrPutSql(sql);
        } else {
          return await this.dao.update(params)
        }
      } else {
        if (params.askforData && params.askforData.rmLicense) {
          params.caStatus = "待提报"
        }
        if (!params.caseId) {
          params.caseId = `CS${new Date().getTime()}ae${Math.floor(Math.random() * 100)}`
        }
        return await this.dao.create(params)
      }
    }
  }

  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)
  }
}
module.exports = TrademarkcaseService;
