package com.jsowell.api.uniapp.customer;

import com.alibaba.fastjson2.JSON;
import com.google.common.collect.ImmutableMap;
import com.jsowell.common.UserAgentUtils;
import com.jsowell.common.annotation.Anonymous;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.page.PageResponse;
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.pile.dto.*;
import com.jsowell.pile.service.PileBasicInfoService;
import com.jsowell.pile.service.PileMerchantInfoService;
import com.jsowell.pile.service.PileReservationInfoService;
import com.jsowell.pile.vo.uniapp.customer.PersonPileConnectorSumInfoVO;
import com.jsowell.pile.vo.uniapp.customer.PersonPileRealTimeVO;
import com.jsowell.pile.vo.uniapp.customer.PersonalPileInfoVO;
import com.jsowell.service.PileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * 个人桩controller
 *
 * @author JS-ZZA
 * @date 2023/2/23 15:36
 */
@Anonymous
@RestController
@RequestMapping("/uniapp/personalPile")
public class PersonPileController extends BaseController {

    @Autowired
    private PileService pileService;

    @Autowired
    private PileMerchantInfoService pileMerchantInfoService;

    @Autowired
    private PileBasicInfoService pileBasicInfoService;

    @Autowired
    private PileReservationInfoService pileReservationInfoService;


    /**
     * 用户绑定个人桩
     * <p>
     * http://localhost:8080/uniapp/personalPile/pileMemberBinding
     *
     * @param dto
     * @return
     */
    @RequestMapping("/pileMemberBinding")
    public RestApiResponse<?> pileMemberBinding(HttpServletRequest request, @RequestBody PileMemberBindingDTO dto) {
        logger.info("绑定个人桩信息 params:{}", JSON.toJSONString(dto));
        RestApiResponse<?> response = null;
        try {
            String memberId = getMemberIdByAuthorization(request);
            dto.setMemberId(memberId);
            int i = pileService.pileMemberBinding(dto);
            response = new RestApiResponse<>(i);
        } catch (BusinessException e) {
            logger.error("绑定个人桩信息 error,", e);
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
        } catch (Exception exception) {
            logger.error("绑定个人桩信息 error,", exception);
            response = new RestApiResponse<>(ReturnCodeEnum.CODE_BINDING_PERSONAL_PILE_ERROR);
        }
        logger.info("绑定个人桩信息  result:{}", response);
        return response;
    }

    /**
     * 用户解绑个人桩
     * http://localhost:8080/uniapp/personalPile/userUnbindPile
     *
     * @return
     */
    @RequestMapping("/userUnbindPile")
    public RestApiResponse<?> userUnbindPile(HttpServletRequest request, @RequestBody PileMemberBindingDTO dto) {
        logger.info("用户解绑个人桩信息 params:{}", JSON.toJSONString(dto));
        RestApiResponse<?> response = null;
        try {
            String memberId = getMemberIdByAuthorization(request);
            dto.setMemberId(memberId);
            int i = pileService.userUnbindPile(dto);
            response = new RestApiResponse<>(i);
        } catch (BusinessException e) {
            logger.error("用户解绑个人桩 error, ", e);
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("用户解绑个人桩 error, ", e);
            response = new RestApiResponse<>(ReturnCodeEnum.CODE_UNBIND_PILE_ERROR);
        }
        logger.info("用户解绑个人桩 result:{}", response);
        return response;
    }


    /**
     * 个人桩管理员下发给其他用户
     * <p>
     * http://localhost:8080/uniapp/personalPile/adminIssuePile
     *
     * @param request
     * @param dto
     * @return
     */
    @RequestMapping("/adminIssuePile")
    public RestApiResponse<?> adminIssuePile(HttpServletRequest request, @RequestBody PileMemberBindingDTO dto) {
        logger.info("桩管理员下发个人桩 params: {}", JSON.toJSONString(dto));
        RestApiResponse<?> response = null;
        try {
            String appId = request.getHeader("appId");
            if (StringUtils.isNotBlank(appId)) {
                String firstLevelMerchantId = pileMerchantInfoService.getFirstLevelMerchantIdByWxAppId(appId);
                if (StringUtils.isNotBlank(firstLevelMerchantId)) {
                    dto.setFirstLevelMerchantId(firstLevelMerchantId);
                }
            }
            String memberId = getMemberIdByAuthorization(request);
            dto.setMemberId(memberId);
            pileService.adminIssuePile(dto);
            response = new RestApiResponse<>();
        } catch (BusinessException e) {
            logger.error("桩管理员下发个人桩 error", e);
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("桩管理员下发个人桩 error", e);
            response = new RestApiResponse<>(ReturnCodeEnum.CODE_ADMIN_ISSUE_ERROR);
        }
        logger.info("桩管理员下发个人桩 result: {}", response);
        return response;
    }

    /**
     * 个人桩停止充电
     * http://localhost:8080/uniapp/personalPile/personPileStopCharging
     * 管理员可以停自己启动的和别人启动的
     * 其他人员只能停止自己启动的
     */
    @PostMapping("/personPileStopCharging")
    public RestApiResponse<?> personPileStopCharging(HttpServletRequest request, PersonPileStopChargingDTO dto) {
        RestApiResponse<?> response = null;
        try {
            String appId = request.getHeader("appId");
            if (StringUtils.isNotBlank(appId)) {
                String firstLevelMerchantId = pileMerchantInfoService.getFirstLevelMerchantIdByWxAppId(appId);
                if (StringUtils.isNotBlank(firstLevelMerchantId)) {
                    dto.setFirstLevelMerchantId(firstLevelMerchantId);
                }
            }
            String memberId = getMemberIdByAuthorization(request);
            dto.setMemberId(memberId);
            pileReservationInfoService.personPileStopCharging(dto);
            response = new RestApiResponse<>();
        } catch (BusinessException e) {
            logger.error("个人桩停止充电error", e);
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("个人桩停止充电error", e);
            response = new RestApiResponse<>(ReturnCodeEnum.CODE_PERSON_PILE_STOP_CHARGING_ERROR);
        }
        return response;
    }


    /**
     * 通过memberId查个人桩列表
     * <p>
     * http://localhost:8080/uniapp/personalPile/getPersonalPileList
     *
     * @return
     */
    @GetMapping("/getPersonalPileList")
    public RestApiResponse<?> getPersonalPileList(HttpServletRequest request) {
        RestApiResponse<?> response = null;
        try {
            String memberId = getMemberIdByAuthorization(request);
            logger.info("通过memberId查个人桩列表 params: {}", memberId);
            List<PersonalPileInfoVO> list = pileBasicInfoService.getPileInfoByMemberId(memberId);
            response = new RestApiResponse<>(list);
        } catch (Exception e) {
            logger.error("通过memberId查个人桩列表异常", e);
            response = new RestApiResponse<>(ReturnCodeEnum.CODE_GET_PERSONAL_PILE_BY_MEMBER_ID_ERROR);
        }
        logger.info("通过memberId查个人桩列表 result:{}", response);
        return response;
    }


    /**
     * 获取枪口实时数据
     * http://localhost:8080/uniapp/personalPile/getConnectorRealTimeInfo
     *
     * @param request
     * @param dto
     * @return
     */
    @PostMapping("/getConnectorRealTimeInfo")
    public RestApiResponse<?> getConnectorRealTimeInfo(HttpServletRequest request, @RequestBody QueryPersonPileDTO dto) {
        logger.info("获取个人桩枪口实时数据  params:{}", JSON.toJSONString(dto));
        RestApiResponse<?> response = null;
        try {
            String memberId = getMemberIdByAuthorization(request);
            dto.setMemberId(memberId);
            PersonPileRealTimeVO connectorRealTimeInfo = pileService.getConnectorRealTimeInfo(dto);
            response = new RestApiResponse<>(connectorRealTimeInfo);
        } catch (BusinessException e) {
            logger.error("获取个人桩枪口实时数据 error", e);
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("获取个人桩枪口实时数据 error", e);
            response = new RestApiResponse<>(ReturnCodeEnum.CODE_GET_PERSONAL_PILE_CONNECTOR_INFO_ERROR);
        }
        logger.info("获取个人桩枪口实时数据 result:{}", response);
        return response;
    }


    /**
     * 获取某枪口某段时间内累计信息
     * <p>
     * http://localhost:8080/uniapp/personalPile/getAccumulativeInfo
     *
     * @param dto
     * @return
     */
    @RequestMapping("/getAccumulativeInfo")
    public RestApiResponse<?> getAccumulativeInfo(HttpServletRequest request, @RequestBody QueryPersonPileDTO dto) {
        logger.info("获取某枪口某段时间内累计信息 params:{}", JSON.toJSONString(dto));
        RestApiResponse<?> response = null;
        try {
            String memberId = getMemberIdByAuthorization(request);
            dto.setMemberId(memberId);
            PersonPileConnectorSumInfoVO accumulativeInfo = pileService.getAccumulativeInfo(dto);
            response = new RestApiResponse<>(accumulativeInfo);
        } 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;
    }

    /**
     * 获取充电记录
     * <p>
     * http://localhost:8080/uniapp/personalPile/getChargingRecord
     *
     * @param request
     * @param dto
     * @return
     */
    @RequestMapping("/getChargingRecord")
    public RestApiResponse<?> getChargingRecord(HttpServletRequest request, @RequestBody QueryPersonPileDTO dto) {
        logger.info("获取个人桩充电记录  params:{}", JSON.toJSONString(dto));
        RestApiResponse<?> response = null;
        try {
            String memberId = getMemberIdByAuthorization(request);
            dto.setMemberId(memberId);
            PageResponse chargingRecord = pileService.getChargingRecord(dto);
            response = new RestApiResponse<>(chargingRecord);
        } 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;
    }

    /**
     * 个人桩启动充电/个人桩一键启动
     * http://localhost:8080/uniapp/personalPile/startPersonalPileCharging
     */
    @PostMapping("/startPersonalPileCharging")
    public RestApiResponse<?> startPersonalPileCharging(HttpServletRequest request, @RequestBody StartPersonPileDTO dto) {
        RestApiResponse<?> response = null;
        try {
            String memberId = getMemberIdByAuthorization(request);
            dto.setMemberId(memberId);
            // 请求来源
            dto.setRequestSource(UserAgentUtils.determineRequestSource(request));
            // appId
            dto.setAppId(request.getHeader("appId"));
            String orderCode = pileService.startPersonalPileCharging(dto);
            response = new RestApiResponse<>(ImmutableMap.of("orderCode", orderCode));
        } catch (BusinessException e) {
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
            logger.error("个人桩启动充电error, params:{}", dto, e);
        } catch (Exception e) {
            logger.error("个人桩启动充电error, params:{}", dto, e);
            response = new RestApiResponse<>(ReturnCodeEnum.CODE_CREATE_RESERVED_ERROR);
        }
        logger.info("个人桩启动充电params:{}, result:{}", dto, response);
        return response;
    }


    /**
     * 添加预约充电
     * http://localhost:8080/uniapp/personalPile/createReserved
     */
    @PostMapping("/createReserved")
    public RestApiResponse<?> createReserved(HttpServletRequest request, @RequestBody CreateReservedDTO dto) {
        // logger.info("修改预约充电状态params:{}", dto);
        RestApiResponse<?> response = null;
        try {
            String memberId = getMemberIdByAuthorization(request);
            dto.setMemberId(memberId);
            int reservedId = pileReservationInfoService.createReservation(dto);
            response = new RestApiResponse<>(ImmutableMap.of("reservedId", reservedId));
        } catch (BusinessException e) {
            logger.error("添加预约充电error, params:{}", dto, e);
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("添加预约充电error, params:{}", dto, e);
            response = new RestApiResponse<>(ReturnCodeEnum.CODE_CREATE_RESERVED_ERROR);
        }
        logger.info("添加预约充电params:{}, result:{}", dto, response);
        return response;
    }

    /**
     * 查询预约充电列表
     * http://localhost:8080/uniapp/personalPile/queryReservedList
     */
    @PostMapping("/queryReservedList")
    public RestApiResponse<?> queryReservedList(HttpServletRequest request, @RequestBody PileReservationDTO dto) {
        // logger.info("修改预约充电状态params:{}", dto);
        RestApiResponse<?> response = null;
        try {
            String memberId = getMemberIdByAuthorization(request);
            dto.setMemberId(memberId);
            PageResponse pageResponse = pileReservationInfoService.queryReservationList(dto);
            response = new RestApiResponse<>(pageResponse);
        } catch (BusinessException e) {
            logger.error("查询预约列表error, params:{}", dto, e);
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("查询预约列表error, params:{}", dto, e);
            response = new RestApiResponse<>(ReturnCodeEnum.CODE_QUERY_RESERVED_LIST_ERROR);
        }
        logger.info("查询预约列表params:{}, result:{}", dto, response);
        return response;
    }

    /**
     * 修改预约充电
     * http://localhost:8080/uniapp/personalPile/updateReservation
     */
    @PostMapping("/updateReservation")
    public RestApiResponse<?> updateReservation(HttpServletRequest request, @RequestBody PileReservationDTO dto) {
        // logger.info("修改预约充电状态params:{}", dto);
        RestApiResponse<?> response = null;
        try {
            String memberId = getMemberIdByAuthorization(request);
            dto.setMemberId(memberId);
            pileReservationInfoService.updateReservation(dto);
            response = new RestApiResponse<>();
        } catch (BusinessException e) {
            logger.error("修改预约充电状态error, params:{}", dto, e);
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("修改预约充电状态error, params:{}", dto, e);
            response = new RestApiResponse<>(ReturnCodeEnum.CODE_UPDATE_RESERVED_STATUS_ERROR);
        }
        logger.info("修改预约充电状态params:{}, result:{}", dto, response);
        return response;
    }

    /**
     * 修改预约充电状态
     * http://localhost:8080/uniapp/personalPile/updateReservedStatus
     */
    @PostMapping("/updateReservedStatus")
    public RestApiResponse<?> updateReservedStatus(HttpServletRequest request, @RequestBody PileReservationDTO dto) {
        // logger.info("修改预约充电状态params:{}", dto);
        RestApiResponse<?> response = null;
        try {
            String memberId = getMemberIdByAuthorization(request);
            dto.setMemberId(memberId);
            pileReservationInfoService.updateReservationStatus(dto);
            response = new RestApiResponse<>();
        } catch (BusinessException e) {
            logger.error("修改预约充电状态error, params:{}", dto, e);
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("修改预约充电状态error, params:{}", dto, e);
            response = new RestApiResponse<>(ReturnCodeEnum.CODE_UPDATE_RESERVED_STATUS_ERROR);
        }
        logger.info("修改预约充电状态params:{}, result:{}", dto, response);
        return response;
    }

    /**
     * 删除预约
     * http://localhost:8080/uniapp/personalPile/deleteReservation
     */
    @PostMapping("/deleteReservation")
    public RestApiResponse<?> deleteReservation(HttpServletRequest request, @RequestBody PileReservationDTO dto) {
        // logger.info("修改预约充电状态params:{}", dto);
        RestApiResponse<?> response = null;
        try {
            String memberId = getMemberIdByAuthorization(request);
            dto.setMemberId(memberId);
            pileReservationInfoService.deleteReservation(dto);
            response = new RestApiResponse<>();
        } catch (BusinessException e) {
            logger.error("修改预约充电状态error, params:{}", dto, e);
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("修改预约充电状态error, params:{}", dto, e);
            response = new RestApiResponse<>(ReturnCodeEnum.CODE_UPDATE_RESERVED_STATUS_ERROR);
        }
        logger.info("修改预约充电状态params:{}, result:{}", dto, response);
        return response;
    }


}
