package com.jiayue.ipfcst.dataexchange.controller;

import com.alibaba.fastjson.JSONObject;
import com.jiayue.ipfcst.aop.SaveValidate;
import com.jiayue.ipfcst.common.core.exception.BusinessException;
import com.jiayue.ipfcst.common.core.web.vo.ResponseVO;
import com.jiayue.ipfcst.dataexchange.domain.EquipmentDataTemplate;
import com.jiayue.ipfcst.dataexchange.service.EquipmentDataTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 设备模版的对外http接口
 *
 * @author 修唯xiuwei
 * @version 3.0
 */
@RestController
@RequestMapping("dataExchange")
public class EquipmentDataTemplateController {


  /**
   * 模版服务类
   */
  @Autowired
  EquipmentDataTemplateService equipmentDataTemplateService;


  /**
   * 查询符合条件对应的模版
   *
   * @param equipmentDataTemplate 模版范例
   * @return ResponseVO 统一返回值格式
   */
  @GetMapping(value = "/equipmentDataTemplate")
  public ResponseVO get(@ModelAttribute() EquipmentDataTemplate equipmentDataTemplate) {
    return ResponseVO.success(equipmentDataTemplateService.get(equipmentDataTemplate));
  }


  /**
   * 删除对应id的模版
   *
   * @param equipmentDataTemplateId 模版ID
   * @return ResponseVO 统一返回值格式
   */
  @DeleteMapping(value = "equipmentDataTemplate")
  @SaveValidate
  public ResponseVO delete(@RequestParam Integer equipmentDataTemplateId) {
    //该操作将会删除该模版下所有的模版点位
    equipmentDataTemplateService.delete(equipmentDataTemplateId);
    return ResponseVO.success();
  }


  /**
   * 添加 或修改模版
   *
   * @param equipmentDataTemplate 模版实体
   * @return ResponseVO 统一返回值格式
   */
  @PutMapping(value = "equipmentDataTemplate")
  @SaveValidate
  public ResponseVO add(@RequestBody EquipmentDataTemplate equipmentDataTemplate) {
    return ResponseVO.success(equipmentDataTemplateService.saveOrUpdate(equipmentDataTemplate));
  }


  /**
   * 通过 模版生成设备点位
   *
   * @param obj 设备模版id 和 设备ID的集合 以及寻位地址 组成对象
   * @return ResponseVO 统一返回值格式
   */
  @PostMapping(value = "/equipmentDataTemplate/generatePoint4Equipment")
  @SaveValidate
  public ResponseVO generatePoint4Equipment(@RequestBody JSONObject obj) throws BusinessException {
    if (obj.containsKey("equipmentDataTemplateId") && obj.containsKey("equipmentIds") && obj.containsKey("findAddressN")) {
      int equipmentDataTemplateId = obj.getInteger("equipmentDataTemplateId");
      int findAddressN = obj.getInteger("findAddressN");
      List<Integer> selectedEquipment = (List<Integer>) obj.get("equipmentIds");
      if (selectedEquipment.size() > 0) {
        equipmentDataTemplateService.generatePoint4Equipment(equipmentDataTemplateId, selectedEquipment, findAddressN);
      }
    }
    return ResponseVO.success();
  }

}
