package com.jsowell.web.controller.pile;

import com.alibaba.fastjson2.JSON;
import com.jsowell.api.uniapp.customer.PileController;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.response.RestApiResponse;
import com.jsowell.common.util.poi.ExcelUtil;
import com.jsowell.pile.domain.PileConnectorInfo;
import com.jsowell.pile.dto.QueryConnectorDTO;
import com.jsowell.pile.dto.QueryConnectorListDTO;
import com.jsowell.pile.dto.UpdateConnectorParkNoDTO;
import com.jsowell.pile.service.IThirdpartySnRelationService;
import com.jsowell.pile.service.PileBasicInfoService;
import com.jsowell.pile.service.PileConnectorInfoService;
import com.jsowell.pile.service.PileStationInfoService;
import com.jsowell.pile.vo.web.PileConnectorInfoVO;
import com.jsowell.pile.vo.web.ThirdPartySnRelationVO;
import com.jsowell.thirdparty.common.CommonService;
import org.apache.commons.collections4.CollectionUtils;
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.ArrayList;
import java.util.List;

/**
 * 充电桩枪口信息Controller
 *
 * @author jsowell
 * @date 2022-08-31
 */
@RestController
@RequestMapping("/pile/connector")
public class PileConnectorInfoController extends BaseController {
    @Autowired
    private PileConnectorInfoService pileConnectorInfoService;

    @Autowired
    private IThirdpartySnRelationService snRelationService;

    @Autowired
    private PileStationInfoService pileStationInfoService;

    @Autowired
    private PileBasicInfoService pileBasicInfoService;

    @Autowired
    private CommonService commonService;

    /**
     * 查询充电桩枪口信息列表
     */
    @PreAuthorize("@ss.hasPermi('pile:connector:list')")
    @GetMapping("/list")
    public TableDataInfo list(QueryConnectorDTO queryConnectorDTO) {
        startPage();
        List<PileConnectorInfoVO> list = pileConnectorInfoService.getConnectorInfoListByParams(queryConnectorDTO);
        return getDataTable(list);
    }

    /**
     * 导出充电桩枪口信息列表
     */
    @PreAuthorize("@ss.hasPermi('pile:connector:export')")
    @Log(title = "充电桩枪口信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PileConnectorInfo pileConnectorInfo) {
        List<PileConnectorInfo> list = pileConnectorInfoService.selectPileConnectorInfoList(pileConnectorInfo);
        ExcelUtil<PileConnectorInfo> util = new ExcelUtil<PileConnectorInfo>(PileConnectorInfo.class);
        util.exportExcel(response, list, "充电桩枪口信息数据");
    }

    /**
     * 通过入参 查询接口列表
     * http://localhost:8080/pile/connector/getConnectorInfoListByParams?pileIds=1,2
     * 多id使用逗号拼接
     */
    @PostMapping("/getConnectorInfoListByParams")
    public TableDataInfo getConnectorInfoListByParams(@RequestBody QueryConnectorListDTO dto) {
        logger.info("查询接口列表 param:{}", JSON.toJSONString(dto));
        // try {
        //     // 修改对接第三方平台的枪口状态
        //     selectThirdPartyConnectorStatus(dto);
        // } catch (Exception e) {
        //     logger.error("修改对接第三方平台的枪口状态 error");
        // }
        List<PileConnectorInfoVO> list = pileConnectorInfoService.getConnectorInfoListByParams(dto);
        logger.info("查询接口列表 result:{}", JSON.toJSONString(list));
        return getDataTable(list);
    }

    /**
     * 修改车位号
     *
     * @param dto
     * @return
     */
    @PreAuthorize("@ss.hasPermi('pile:connector:edit')")
    @Log(title = "充电桩枪口信息", businessType = BusinessType.UPDATE)
    @PostMapping("/updateParkNo")
    public RestApiResponse<?> updateParkNo(@RequestBody UpdateConnectorParkNoDTO dto) {
        logger.info("修改车位号 param:{}", JSON.toJSONString(dto));
        RestApiResponse<?> response = null;
        try {
            int i = pileConnectorInfoService.updateConnectorParkNo(dto);
            response = new RestApiResponse<>(i);
        } catch (Exception e) {
            logger.error("修改车位号 error,", e);
            response = new RestApiResponse<>(e);
        }
        return response;
    }

    /**
     * 获取充电桩枪口信息详细信息
     */
    // @PreAuthorize("@ss.hasPermi('pile:connector:query')")
    // @GetMapping(value = "/{id}")
    // public AjaxResult getInfo(@PathVariable("id") Integer id) {
    // 	return AjaxResult.success(pileConnectorInfoService.selectPileConnectorInfoById(id));
    // }

    /**
     * 新增充电桩枪口信息
     */
    // @PreAuthorize("@ss.hasPermi('pile:connector:add')")
    // @Log(title = "充电桩枪口信息", businessType = BusinessType.INSERT)
    // @PostMapping
    // public AjaxResult add(@RequestBody PileConnectorInfo pileConnectorInfo) {
    // 	return toAjax(pileConnectorInfoService.insertPileConnectorInfo(pileConnectorInfo));
    // }

    /**
     * 修改充电桩枪口信息
     */
    // @PreAuthorize("@ss.hasPermi('pile:connector:edit')")
    // @Log(title = "充电桩枪口信息", businessType = BusinessType.UPDATE)
    // @PutMapping
    // public AjaxResult edit(@RequestBody PileConnectorInfo pileConnectorInfo) {
    // 	return toAjax(pileConnectorInfoService.updatePileConnectorInfo(pileConnectorInfo));
    // }

    /**
     * 删除充电桩枪口信息
     */
    // @PreAuthorize("@ss.hasPermi('pile:connector:remove')")
    // @Log(title = "充电桩枪口信息", businessType = BusinessType.DELETE)
    // @DeleteMapping("/{ids}")
    // public AjaxResult remove(@PathVariable Integer[] ids) {
    // 	return toAjax(pileConnectorInfoService.deletePileConnectorInfoByIds(ids));
    // }

    /**
     * 修改第三方平台枪口状态
     * @see PileController#selectThirdPartyConnectorStatus(com.jsowell.pile.dto.QueryConnectorListDTO)
     * 两个方法完全相同，如有修改需同步修改
     */
    private void selectThirdPartyConnectorStatus(QueryConnectorListDTO dto) {
        if (dto == null) {
            return;
        }
        List<Long> pileIds = dto.getPileIds();
        List<Long> stationIdList = dto.getStationIdList();

        List<ThirdPartySnRelationVO> list = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(pileIds)) {
            list = snRelationService.selectSnRelationListByParams(null, null, pileIds);
        }
        if (CollectionUtils.isNotEmpty(stationIdList)) {
            for (Long stationId : stationIdList) {
                String stationIdStr = String.valueOf(stationId);
                list = snRelationService.selectSnRelationListByParams(stationIdStr, null, null);
            }
        }
        if (CollectionUtils.isEmpty(list)) {
            return;
        }

        for (ThirdPartySnRelationVO vo : list) {
            String thirdPartyType = vo.getThirdPartyType();
            String stationId = vo.getStationId();
            // 调用通用查询实时数据接口（需在接口中修改枪口状态）
            commonService.commonQueryStationStatus(stationId, thirdPartyType);
        }
    }

}
