package com.jsowell.web.controller.pile;

import com.alibaba.fastjson2.JSONObject;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.enums.ykc.ReturnCodeEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.response.RestApiResponse;
import com.jsowell.common.util.StringUtils;
import com.jsowell.common.util.poi.ExcelUtil;
import com.jsowell.pile.domain.PileStationInfo;
import com.jsowell.pile.domain.StationSettingRelation;
import com.jsowell.pile.domain.ThirdPartySettingInfo;
import com.jsowell.pile.dto.FastCreateStationDTO;
import com.jsowell.pile.dto.LianLianPushStationInfoDTO;
import com.jsowell.pile.dto.QueryStationDTO;
import com.jsowell.pile.service.IPileStationInfoService;
import com.jsowell.pile.service.IStationSettingRelationService;
import com.jsowell.pile.service.IThirdPartySettingInfoService;
import com.jsowell.pile.vo.base.StationSettingRelationVO;
import com.jsowell.pile.vo.web.PileStationVO;
import com.jsowell.service.PileService;
import com.jsowell.thirdparty.lianlian.service.LianLianService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 充电站信息Controller
 *
 * @author jsowell
 * @date 2022-08-30
 */
@RestController
@RequestMapping("/pile/station")
public class PileStationInfoController extends BaseController {
	@Autowired
	private IPileStationInfoService pileStationInfoService;

	@Autowired
	private PileService pileService;

	@Autowired
	private IThirdPartySettingInfoService thirdPartySettingInfoService;

	@Autowired
	private LianLianService lianLianService;

	@Autowired
	private IStationSettingRelationService stationSettingRelationService;


	/**
	 * 查询充电站信息列表NEW
	 */
    @PreAuthorize("@ss.hasPermi('pile:station:list')")
    @GetMapping("/list")
    public TableDataInfo list(QueryStationDTO queryStationDTO) {
		startPage();
		// List<PileStationInfo> list = pileStationInfoService.selectPileStationInfoList(pileStationInfo);
		List<PileStationVO> list = pileStationInfoService.queryStationInfos(queryStationDTO);
		return getDataTable(list);
	}

	/**
	 * 快速建站接口
	 */
    // @PreAuthorize("@ss.hasPermi('pile:station:add')")
    @PostMapping("/fastCreateStation")
    public AjaxResult fastCreateStation(@RequestBody FastCreateStationDTO dto) {
    	logger.info("快速建站接口 param:{}", JSONObject.toJSONString(dto));
		int i = 0;
		try {
			i = pileStationInfoService.fastCreateStation(dto);
		} catch (BusinessException e) {
			logger.warn("快速建站接口 warn", e);
		} catch (Exception e) {
			logger.error("快速建站接口 error", e);
		}
		return toAjax(i);
    }


	/**
	 * 查询充电站信息列表
	 */
	/*@PreAuthorize("@ss.hasPermi('pile:station:list')")
	@GetMapping("/list")
	public TableDataInfo list(PileStationInfo pileStationInfo) {
		startPage();
		List<PileStationInfo> list = pileStationInfoService.selectPileStationInfoList(pileStationInfo);
		return getDataTable(list);
	}*/

	/**
	 * 导出充电站信息列表
	 */
	@PreAuthorize("@ss.hasPermi('pile:station:export')")
	@Log(title = "充电站信息", businessType = BusinessType.EXPORT)
	@PostMapping("/export")
	public void export(HttpServletResponse response, PileStationInfo pileStationInfo) {
		List<PileStationInfo> list = pileStationInfoService.selectPileStationInfoList(pileStationInfo);
		ExcelUtil<PileStationInfo> util = new ExcelUtil<PileStationInfo>(PileStationInfo.class);
		util.exportExcel(response, list, "充电站信息数据");
	}

	/**
	 * 获取充电站信息详细信息
	 */
	@PreAuthorize("@ss.hasPermi('pile:station:query')")
	@GetMapping(value = "/{id}")
	public AjaxResult getInfo(@PathVariable("id") Long id) {
		return AjaxResult.success(pileStationInfoService.selectPileStationInfoById(id));
	}

	/**
	 * 后管站点基本资料页面
	 * @return
	 */
	@PreAuthorize("@ss.hasPermi('pile:station:query')")
	@GetMapping(value = "/getStationInfo/{stationId}")
	public AjaxResult getStationInfo(@PathVariable("stationId") String stationId) {
		return AjaxResult.success(pileStationInfoService.getStationInfo(stationId));
	}

	/**
	 * 新增充电站信息
	 */
	@PreAuthorize("@ss.hasPermi('pile:station:add')")
	@Log(title = "充电站信息", businessType = BusinessType.INSERT)
	@PostMapping
	public AjaxResult add(@RequestBody PileStationInfo pileStationInfo) {
		return toAjax(pileStationInfoService.insertPileStationInfo(pileStationInfo));
	}

	/**
	 * 修改充电站信息
	 */
	@PreAuthorize("@ss.hasPermi('pile:station:edit')")
	@Log(title = "充电站信息", businessType = BusinessType.UPDATE)
	@PutMapping
	public AjaxResult edit(@RequestBody PileStationInfo pileStationInfo) {
		logger.info("修改充电站信息 param:{}", pileStationInfo.toString());
		return toAjax(pileStationInfoService.updatePileStationInfo(pileStationInfo));
	}

	/**
	 * 删除充电站信息
	 */
	@PreAuthorize("@ss.hasPermi('pile:station:remove')")
	@Log(title = "充电站信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
	public AjaxResult remove(@PathVariable Long[] ids) {
		return toAjax(pileStationInfoService.deletePileStationInfoByIds(ids));
	}

	/**
	 * 根据运营商id获取充电站列表
	 */
	@PreAuthorize("@ss.hasPermi('pile:station:query')")
	@PostMapping(value = "/selectStationListByMerchantId")
	public AjaxResult selectStationListByMerchantId(@RequestBody QueryStationDTO dto) {
		return AjaxResult.success(pileStationInfoService.selectStationListByMerchantId(Long.valueOf(dto.getMerchantId())));
	}

	/**
	 * 修改站点二维码前缀
	 * @param dto
	 * @return
	 */
	@PreAuthorize("@ss.hasPermi('pile:station:edit')")
	@PostMapping("/updateStationQRCodePrefix")
	public AjaxResult updateStationQRCodePrefix(@RequestBody QueryStationDTO dto) {
		// 校验入参
		if (StringUtils.isBlank(dto.getStationId()) || StringUtils.isBlank(dto.getQrcodePrefix())) {
			return AjaxResult.error(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR.getValue());
		}
		return AjaxResult.success(pileService.updateStationQRCodePrefix(dto));
	}

	/**
	 * 查询站点互联互通配置
	 * @param id
	 * @return
	 */
	@PreAuthorize("@ss.hasPermi('pile:station:query')")
	@GetMapping("/getSettingByStationId/{stationId}")
	public AjaxResult getSettingByStationId(@PathVariable("stationId") Long id) {
		StationSettingRelation info = new StationSettingRelation();
		info.setStationId(id);
		return AjaxResult.success(stationSettingRelationService.selectRelationInfo(info));
	}

	/**
	 * 查询第三方平台配置信息
	 * @param info
	 * @return
	 */
	@PreAuthorize("@ss.hasPermi('pile:station:query')")
	@PostMapping("/getSettingInfo")
	public AjaxResult getSettingInfo(@RequestBody ThirdPartySettingInfo info) {
		return AjaxResult.success(thirdPartySettingInfoService.selectSettingInfo(info));
	}

	/**
	 * 修改站点互联互通配置信息
	 * @param info
	 * @return
	 */
	// @PreAuthorize("@ss.hasPermi('pile:station:edit')")
	// @PostMapping("/updateSettingByStationId")
	// public AjaxResult updateSettingByStationId(@RequestBody ThirdPartySettingInfo info) {
	// 	return AjaxResult.success(thirdPartySettingInfoService.updateStationSettingInfo(info));
	// }

	/**
	 * 新增站点互联互通配置信息
	 * @param info
	 * @return
	 */
	// @PreAuthorize("@ss.hasPermi('pile:station:add')")
	// @PostMapping("/insertSettingInfo")
	// public AjaxResult insertSettingInfo(ThirdPartySettingInfo info) {
	// 	return AjaxResult.success(thirdPartySettingInfoService.insertThirdPartySettingInfo(info));
	// }



	/**
	 * 推送充电站信息 notification_stationInfo
	 * http://localhost:8080/LianLian/pushStationInfo
	 * @param dto
	 * @return
	 */
	@PostMapping("/pushStationInfo")
	public RestApiResponse<?> pushStationInfo(@RequestBody LianLianPushStationInfoDTO dto) {
		logger.info("推送联联平台充电站信息 params:{}", JSONObject.toJSONString(dto));
		RestApiResponse<?> response = null;
		try {
			if (StringUtils.isBlank(String.valueOf(dto.getStationId()))) {
				throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
			}

			// 推送联联
			if (StringUtils.equals("1", dto.getThirdPartyType())) {
				String result = lianLianService.pushStationInfo(dto);
				response = new RestApiResponse<>(result);
			}
		}catch (BusinessException e) {
			logger.error("推送联联平台充电站信息 error",e);
			response = new RestApiResponse<>(e.getCode(), e.getMessage());
		}catch (Exception e) {
			logger.error("推送联联平台充电站信息 error", e);
			response = new RestApiResponse<>("推送失败，请联系管理员");
			// 删除对应配置信息
			StationSettingRelation relation = new StationSettingRelation();
			relation.setStationId(dto.getStationId());
			relation.setDelFlag("1");
			stationSettingRelationService.updateStationSettingRelation(relation);
		}
		logger.info("推送联联平台充电站信息 result:{}", response);
		return response;
	}

}
