package com.shanghaichengdi.ghjgitem.controller;

import com.alibaba.fastjson.JSONObject;
import com.shanghaichengdi.ghjgitem.constant.HttpStatus;
import com.shanghaichengdi.ghjgitem.domain.BusinessSupervisionInform;
import com.shanghaichengdi.ghjgitem.domain.BusinessSupervisionRecord;
import com.shanghaichengdi.ghjgitem.exception.EnumException;
import com.shanghaichengdi.ghjgitem.service.BusinessSupervisionInformService;
import com.shanghaichengdi.ghjgitem.service.BusinessSupervisionRecordService;
import com.shanghaichengdi.ghjgitem.service.CommonService;
import com.shanghaichengdi.ghjgitem.vo.ObjectBodyVo;
import com.shanghaichengdi.ghjgitem.vo.request.SupervisionOrDocNumberReq;
import com.shanghaichengdi.ghjgitem.vo.response.ResultRes;
import com.shanghaichengdi.ghjgitem.vo.response.ReturnMsg;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin
@Slf4j
@RequestMapping("supervision")
public class SupervisionController extends CommonController {

  @Resource
  private CommonService commonService;
  @Resource
  private BusinessSupervisionInformService supervisionInformService;
  @Resource
  private BusinessSupervisionRecordService supervisionRecordService;

  @PostMapping("/getRecordOrDocNumber")
  public ReturnMsg getAisRealTimeXY(@RequestBody @Validated ObjectBodyVo vo) {
    if (!checkDbKey(vo.getKey())) {
      return ReturnMsg.error(HttpStatus.BAD_REQUEST, "key值有误,请确认您输入的key值正确!");
    }
    String paramJsonData = getParamJsonData(vo.getData());
    SupervisionOrDocNumberReq req = JSONObject.parseObject(paramJsonData,
        SupervisionOrDocNumberReq.class);
    String supervisionOrDocNumber = commonService.selectRecordOrDocNumber(req);
    if ("inform".equals(req.getType())) {
      BusinessSupervisionInform inform = new BusinessSupervisionInform();
      inform.setDocnumber(supervisionOrDocNumber);
      inform.setCode(String.valueOf(System.nanoTime()));
      supervisionInformService.save(inform);
    } else if ("record".equals(req.getType())) {
      BusinessSupervisionRecord record = new BusinessSupervisionRecord();
      record.setSupervisionnumber(supervisionOrDocNumber);
      supervisionRecordService.save(record);
    } else {
      throw new EnumException("类型输入有误");
    }
    ResultRes resultRes = ResultRes.encapsulationResult(supervisionOrDocNumber);
    String jsonString = JSONObject.toJSONString(resultRes);
    String encodedData = resultEncode(jsonString);
    return ReturnMsg.success("获取成功", encodedData);
  }
}
