package com.jsowell.api.uniapp.customer;

import com.alibaba.fastjson2.JSON;
import com.jsowell.common.UserAgentUtils;
import com.jsowell.common.annotation.Anonymous;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.enums.adapay.AdapayPayChannelEnum;
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.file.AliyunOssUploadUtils;
import com.jsowell.common.util.file.FileUtils;
import com.jsowell.pile.domain.PileBasicInfo;
import com.jsowell.pile.service.IThirdpartySnRelationService;
import com.jsowell.pile.service.MemberGroupService;
import com.jsowell.pile.service.PileBasicInfoService;
import com.jsowell.pile.vo.base.PileInfoVO;
import com.jsowell.pile.vo.uniapp.customer.GroundLockInfoVO;
import com.jsowell.pile.vo.uniapp.customer.PileConnectorVO;
import com.jsowell.pile.vo.web.ThirdPartySnRelationVO;
import com.jsowell.service.PileService;
import com.jsowell.thirdparty.common.CommonService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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


@Anonymous
@RestController
@RequestMapping("/app-xcx-h5")
public class JumpController extends BaseController {

    @Autowired
    private PileService pileService;

    @Autowired
    private PileBasicInfoService pileBasicInfoService;

    @Autowired
    private MemberGroupService memberGroupService;

    @Autowired
    private IThirdpartySnRelationService snRelationService;

    @Autowired
    private CommonService commonService;

    /**
     * 查询充电桩详情
     * http://localhost:8080/app-xcx-h5/pile/pileDetail/{pileSn}
     */
    @GetMapping("/pile/pileDetail/{pileSn}")
    public RestApiResponse<?> getPileDetail(HttpServletRequest request, @PathVariable("pileSn") String pileSn) {
        // logger.info("app-xcx-h5查询充电桩详情 param:{}", pileSn);
        logger.info("User-Agent:{}", request.getHeader("user-agent"));
        RestApiResponse<?> response = null;
        try {
            // 如果对接了类似华为平台的第三方平台，先修改一下枪口状态
            updateThirdPartyConnectorStatus(pileSn);
        }catch (Exception e) {
            logger.error("修改第三方平台枪口状态 error", e);
        }

        try {
            // 进入充电桩详情做一下鉴权
            String memberId = getMemberIdByAuthorization(request);
            PileConnectorVO vo = pileService.getPileDetailByPileSn(pileSn);
            addMember2MemberGroup(memberId, vo);
            response = new RestApiResponse<>(vo);
        } catch (BusinessException e) {
            logger.warn("app-xcx-h5查询充电桩详情 warn", e);
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("app-xcx-h5查询充电桩详情 error", e);
            response = new RestApiResponse<>(ReturnCodeEnum.CODE_GET_PILE_DETAIL_ERROR);
        }
        logger.info("app-xcx-h5查询充电桩详情 param:{}, result:{}", pileSn, JSON.toJSONString(response));
        return response;
    }

    // 针对汇鑫大厦的用户，自动加入集团中
    private void addMember2MemberGroup(String memberId, PileConnectorVO vo) {
        if (vo == null || StringUtils.isBlank(memberId)) {
            return;
        }
        PileInfoVO pileInfo = vo.getPileInfo();
        if (pileInfo == null) {
            return;
        }
        String stationId = pileInfo.getStationId();
        if (!StringUtils.equals(stationId, "159")) {
            return;
        }
        int i = memberGroupService.addMember2MemberGroup(memberId, pileInfo.getMerchantId());
        if (i > 0) {
            logger.info("会员:{}加入到运营商:{}的集团中，操作成功", memberId, pileInfo.getMerchantName());
        }
    }

    /**
     * 查询充电枪口详情
     * http://localhost:8080/app-xcx-h5/pile/connectorDetail/{pileConnectorCode}
     */
    @GetMapping("/pile/connectorDetail/{pileConnectorCode}")
    public RestApiResponse<?> getConnectorDetail(HttpServletRequest request, @PathVariable("pileConnectorCode") String pileConnectorCode) {
        // logger.info("app-xcx-h5查询充电枪口详情 param:{}", pileConnectorCode);
        String requestSource = UserAgentUtils.determineRequestSource(request);
        logger.info("查询充电枪口详情-User-Agent:{}, 请求来源:{}", request.getHeader("user-agent"), requestSource);
        RestApiResponse<?> response = null;
        // 截取桩号
        String pileSn = StringUtils.substring(pileConnectorCode, 0, 14);

        try {
            // 如果对接了类似华为平台的第三方平台，先修改一下枪口状态
            updateThirdPartyConnectorStatus(pileSn);
        }catch (Exception e) {
            logger.error("修改第三方平台枪口状态 error", e);
        }

        try {
            String memberId = null;
            // 进入充电桩详情做一下鉴权, 请求来源来自微信或者支付宝，必须校验登录状态
            if (StringUtils.equals(requestSource, AdapayPayChannelEnum.WX_LITE.getValue())
                    || StringUtils.equals(requestSource, AdapayPayChannelEnum.ALIPAY_LITE.getValue())) {
                memberId = getMemberIdByAuthorization(request);
            }

            PileConnectorVO vo = pileService.getConnectorDetail(pileConnectorCode);
            if (StringUtils.isNotBlank(memberId)) {
                addMember2MemberGroup(memberId, vo);
            }
            response = new RestApiResponse<>(vo);
        } catch (BusinessException e) {
            logger.warn("app-xcx-h5查询充电枪口详情 warn param:{}", pileConnectorCode, e);
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("app-xcx-h5查询充电枪口详情 error param:{}", pileConnectorCode, e);
            response = new RestApiResponse<>(ReturnCodeEnum.CODE_GET_PILE_DETAIL_ERROR);
        }
        logger.info("app-xcx-h5查询充电枪口详情 param:{} result:{}", pileConnectorCode, JSON.toJSONString(response));
        return response;
    }

    /**
     * 上传到阿里云oss
     * http://localhost:8080/app-xcx-h5/uploadOSS
     *
     * @param file
     * @return
     */
    @CrossOrigin
    @PostMapping("/uploadOSS")
    public AjaxResult uploadFileOSS(MultipartFile file) {
        try {
            String url = AliyunOssUploadUtils.uploadFile(file);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", FileUtils.getName(url));
            ajax.put("newFileName", FileUtils.getName(url));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 获取地锁列表信息
     * http://localhost:8080/app-xcx-h5/getGroundLockInfo/{stationId}
     *
     * @param stationId
     * @return
     */
    @GetMapping("/getGroundLockInfo/{stationId}")
    public RestApiResponse<?> getGroundLockInfo(@PathVariable("stationId") String stationId, HttpServletRequest request) {
        logger.info("获取地锁列表信息 params:{}", stationId);
        RestApiResponse<?> response = null;
        try {
            String memberId = getMemberIdByAuthorization(request);
            if (StringUtils.isBlank(memberId)) {
                throw new BusinessException(ReturnCodeEnum.CODE_TOKEN_ERROR);
            }
            List<GroundLockInfoVO> list = pileBasicInfoService.getGroundLockInfo(stationId);
            response = new RestApiResponse<>(list);
        } catch (BusinessException e) {
            logger.error("获取地锁列表信息 error,", e);
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("获取地锁列表信息 error, ", e);
            response = new RestApiResponse<>(e);
        }
        logger.info("获取地锁列表信息 result:{}", response);
        return response;
    }


    private void updateThirdPartyConnectorStatus(String pileSn) {
        // 根据桩号查询站点id
        PileBasicInfo pileBasicInfo = pileBasicInfoService.selectPileBasicInfoBySN(pileSn);
        if (pileBasicInfo == null) {
            return;
        }
        Long stationId = pileBasicInfo.getStationId();
        String stationIdStr = String.valueOf(stationId);
        List<ThirdPartySnRelationVO> list = snRelationService.selectSnRelationListByParams(stationIdStr, null, null);
        if (CollectionUtils.isEmpty(list)) {
            return;
        }

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

    }
}
