package com.cool.store.controller.webb;

import com.alibaba.fastjson.JSONObject;
import com.cool.store.annotation.Debounce;
import com.cool.store.dto.*;
import com.cool.store.dto.huoma.StoreXinFaDeviceDetail;
import com.cool.store.dto.region.BigRegionDTO;
import com.cool.store.dto.store.StoreUserPositionDTO;
import com.cool.store.dto.wallet.PaymentDTO;
import com.cool.store.dto.wx.MiniProgramFreeLoginDTO;
import com.cool.store.handler.WeChatHandler;
import com.cool.store.enums.close.CloseTypeEnum;
import com.cool.store.request.OpenApiStoreRequest;
import com.cool.store.request.StoreCodeDTO;
import com.cool.store.request.*;
import com.cool.store.request.close.store.ThirdCloseStoreApplyRequest;
import com.cool.store.request.notice.ThirdHandleMessageRequest;
import com.cool.store.request.notice.ThirdMatterRequest;
import com.cool.store.request.openapi.ShopListRequest;
import com.cool.store.request.openapi.StoreRequest;
import com.cool.store.request.openapi.SubRegionRequest;
import com.cool.store.request.privatesphere.PrivateSphereSnRequest;
import com.cool.store.request.wallet.AccountTradeCallbackRequest;
import com.cool.store.request.wallet.AddTagCallbackNoticeRequest;
import com.cool.store.request.wallet.OnlineCommercialBankCallbackRequest;
import com.cool.store.request.xgj.FranchiseFeeCallBackRequest;
import com.cool.store.request.xgj.ReceiptCallBackRequest;
import com.cool.store.response.RegionResponse;
import com.cool.store.response.ResponseResult;
import com.cool.store.response.ShopResponse;
import com.cool.store.response.bigdata.ApiResponse;
import com.cool.store.service.*;
import com.cool.store.service.privatesphere.PrivateSphereQrService;
import com.cool.store.service.wallet.WalletService;
import com.cool.store.service.xinfa.XinFaBusinessService;
import com.cool.store.service.xinfa.XinFaDeviceService;
import com.cool.store.utils.HttpHelper;
import com.cool.store.utils.poi.StringUtils;
import com.cool.store.service.close.CloseStoreService;
import com.cool.store.vo.privatesphere.PrivateSphereVO;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

/**
 * @Author suzhuhong
 * @Date 2025/4/5 18:19
 * @Version 1.0
 */
@RestController
@RequestMapping("/open/v1/")
@Api(tags = "对外接口")
@Slf4j
public class OpenApiController {

    @Resource
    private DecorationDesignInfoService decorationDesignInfoService;
    @Resource
    private DecorationMeasureService decorationMeasureService;
    @Resource
    OpenApiService openApiService;
    @Resource
    PushService pushService;
    @Resource
    ShopAccountService shopAccountService;
    @Resource
    StoreService storeService;
    @Resource
    MessageTemplateService messageTemplateService;
    @Resource
    WechatMiniAppService wechatMiniAppService;
    @Autowired
    WeChatHandler weChatHandler;
    @Resource
    WalletService walletService;
    @Resource
    CloseStoreService closeStoreService;
    @Resource
    ShopService shopService;
    @Resource
    BigRegionService bigRegionService;
    @Resource
    RegionService regionService;
    @Resource
    PrivateSphereQrService privateSphereQrService;
    @Resource
    XinFaBusinessService xinFaBusinessService;

    @PostMapping("/statusRefresh")
    public ApiResponse<Boolean> statusRefresh(@RequestBody  StatusRefreshDTO statusRefreshDTO){
        log.info("statusRefresh request：{}", JSONObject.toJSONString(statusRefreshDTO));
        return ApiResponse.success(openApiService.statusRefresh(statusRefreshDTO));
    }

    @ApiOperation("获取云流水免登token")
    @PostMapping("/getYlsToken")
    public ApiResponse<String> getYlsToken(@RequestBody @Validated AskBotTokenDTO dto) {
        String ylsCode = shopAccountService.shopCodeToYlsCode(dto.getShopCode());
        return ApiResponse.success(pushService.getYlsToken(new GetAccessTokenDTO(ylsCode,ylsCode)));
    }

    @ApiOperation("获取门店信息")
    @PostMapping("/getStoreList")
    public ApiResponse<PageInfo<StoreDTO>> getStoreList(@RequestBody @Validated OpenApiStoreRequest dto) {
        return ApiResponse.success(storeService.getStoreExtendFieldInfo(dto.getPageSize(),dto.getPageNum(), dto.getQueryOperations()));
    }

    @ApiOperation("获取接入物联网门店信息")
    @PostMapping("/getIoTStoreList")
    public ApiResponse<PageInfo<StoreNameDTO>> getIotStoreList(@RequestBody @Validated OpenApiStoreRequest dto) {
        return ApiResponse.success(storeService.getIotStoreList(dto.getPageNum(), dto.getPageSize()));
    }

    @ApiOperation("新管家回调 刷新收款单状态")
    @PostMapping("/changeReceiptStatus")
    public ApiResponse<Boolean> changeReceiptStatus(@RequestBody @Validated ReceiptCallBackRequest request){
        log.info("changeReceiptStatus request：{}", JSONObject.toJSONString(request));
        return openApiService.changeReceiptStatus(request);
    }

    @ApiOperation("新管家回调 账单收款状态及缴款金额")
    @PostMapping("/changePaymentStatus")
    public ApiResponse<Boolean> changePaymentStatus(@RequestBody @Validated FranchiseFeeCallBackRequest request){
        log.info("changePaymentStatus request：{}", JSONObject.toJSONString(request));
        return openApiService.changePaymentStatus(request);
    }
    @ApiOperation("获取门店人员信息")
    @PostMapping("/getStoreUser")
    public ApiResponse<List<StoreUserPositionDTO>> getStoreUser(@RequestBody @Validated StoreCodeDTO dto) {
        return ApiResponse.success(storeService.getStoreUser(dto.getStoreCodeList()));
    }
    @ApiOperation("分配测量员，设计组")
    @PostMapping("/assignSurveyors")
    public ApiResponse<Boolean> assignSurveyors(@RequestBody @Validated AssignSurveyorsRequest request) {
        log.info("assignSurveyors request：{}", JSONObject.toJSONString(request));
        return ApiResponse.success(decorationMeasureService.assignSurveyors(request));
    }

    @ApiOperation("门店测量、上传测量图")
    @PostMapping("/submitMeasurementDiagram")
    public ApiResponse<Boolean> submitMeasurementDiagram(@RequestBody @Validated SubmitMeasurementRequest request) {
        log.info("submitMeasurementDiagram request：{}", JSONObject.toJSONString(request));
        return ApiResponse.success(decorationMeasureService.submitMeasurementDiagram(request));
    }

    @ApiOperation(" 分配设计师")
    @PostMapping("/assignDesigner")
    public ApiResponse<Boolean> assignDesigner(@RequestBody @Validated AssignDesignerRequest request) {
        log.info("assignDesigner request：{}", JSONObject.toJSONString(request));
        return ApiResponse.success(decorationDesignInfoService.assignDesigner(request));
    }

    @ApiOperation("上传设计图")
    @PostMapping("/submitDesignDrawing")
    public ApiResponse<Boolean> submitDesignDrawing(@RequestBody @Validated SubmitDesignDrawingRequest request) {
        log.info("submitDesignDrawing request：{}", JSONObject.toJSONString(request));
        return ApiResponse.success(decorationDesignInfoService.submitDesignDrawing(request));
    }

    @ApiOperation("分配报价员")
    @PostMapping("/assignQuotationStaff")
    public ApiResponse<Boolean> assignQuotation(@RequestBody @Validated AssignQuotationRequest request) {
        log.info("assignQuotation request：{}", JSONObject.toJSONString(request));
        return ApiResponse.success(decorationDesignInfoService.assignQuotation(request));
    }

    @ApiOperation("上传报价单")
    @PostMapping("/submitQuotationSheet")
    public ApiResponse<Boolean> submitQuotationSheet(@RequestBody @Validated SubmitQuotationSheetRequest request) {
        log.info("submitQuotationSheet request：{}", JSONObject.toJSONString(request));
        return ApiResponse.success(decorationDesignInfoService.submitQuotationSheet(request));
    }

    @ApiOperation("施工派单")
    @PostMapping("/submitConstructionOrder")
    public ApiResponse<Boolean> submitConstructionOrder(@RequestBody @Validated ConstructionOrderRequest request) {
        log.info("submitConstructionOrder request：{}", JSONObject.toJSONString(request));
        return ApiResponse.success(decorationDesignInfoService.submitConstructionOrder(request));
    }

    @ApiOperation("实际进场确认")
    @PostMapping("/entryConfirmation")
    public ApiResponse<Boolean> entryConfirmation(@RequestBody @Validated EntryConfirmationRequest request) {
        log.info("entryConfirmation request：{}", JSONObject.toJSONString(request));
        return ApiResponse.success(decorationDesignInfoService.entryConfirmation(request));
    }

    @ApiOperation("施工完成")
    @PostMapping("/constructionCompleted")
    public ApiResponse<Boolean> constructionCompleted(@RequestBody @Validated ConstructionCompletedRequest request) {
        log.info("constructionCompleted request：{}", JSONObject.toJSONString(request));
        return ApiResponse.success(decorationDesignInfoService.constructionCompleted(request));
    }

    @ApiOperation("装修验收")
    @PostMapping("/hqtDecorationAcceptance")
    public ApiResponse<Boolean> decorationAcceptance(@RequestBody @Validated HqtDecorationAcceptanceRequest request) {
        log.info("decorationAcceptance request：{}", JSONObject.toJSONString(request));
        return ApiResponse.success(decorationDesignInfoService.decorationAcceptance(request));
    }

    @ApiOperation("事项处理")
    @PostMapping("/matterHandle")
    public ApiResponse<Boolean> thirdMatterHandle(@RequestBody @Validated ThirdMatterRequest request) {
        log.info("thirdMatterHandle request：{}", JSONObject.toJSONString(request));
        return messageTemplateService.thirdMatterHandle(request);
    }


    @ApiOperation("确认已处理")
    @PostMapping("/handleMessage")
    public ApiResponse<Boolean> handleMessage(@RequestBody @Validated ThirdHandleMessageRequest  request) {
        return messageTemplateService.thirdHandleMessage(request);
    }

    @ApiOperation("根据手机号获取短期token")
    @PostMapping("/getShortTermToken")
    public ApiResponse<String> getTokenByMobile(@RequestBody @Validated MiniProgramFreeLoginDTO param) {
        return ApiResponse.success(wechatMiniAppService.getShortTermTokenByMobile(param));
    }

    @RequestMapping(value = "/callback", produces = "application/xml;charset=UTF-8")
    @ApiOperation("callback")
    public String handleWechatMessage(
            @RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam(value = "echostr", required = false) String echostr,
            @RequestBody(required = false) String requestBody) {

        log.info("url:{}","/open/v1/");
        log.info("callback_signature:{},timestamp:{},nonce:{}",signature,timestamp,nonce);
        log.info("requestBody:{}",requestBody);

        if (StringUtils.isNotEmpty(requestBody)) {
            try {
                return weChatHandler.processMessage(weChatHandler.parseXmlToMap(requestBody));
            } catch (Exception e) {
                log.info("回调处理失败 e:{}",e);
                return "success";
            }
        }
        return echostr;
    }

    @ApiOperation("打标回调通知接口")
    @PostMapping("/wallet/addTagCallback")
    public ApiResponse<Boolean> addTagCallback(@RequestBody @Validated AddTagCallbackNoticeRequest request) {
        return ApiResponse.successByWallet(walletService.addTagCallback(request));
    }

    @ApiOperation("大额充值通知接口")
    @PostMapping("/wallet/largePaymentCallback")
    public ApiResponse<Boolean> largePaymentCallback(@RequestBody @Validated PaymentDTO request) {
        return ApiResponse.successByWallet(walletService.largePaymentCallback(request));
    }

    @ApiOperation("账户交易回调")
    @PostMapping("/wallet/accountTradeCallback")
    public ApiResponse<Boolean> accountTradeCallback(@RequestBody @Validated AccountTradeCallbackRequest request) {
        return ApiResponse.successByWallet(walletService.accountTradeCallback(request));
    }

    @ApiOperation("网商银行通知接口")
    @PostMapping("/wallet/onlineCommercialBankCallback")
    public ApiResponse<Boolean> accountTradeCallback(@RequestBody @Validated OnlineCommercialBankCallbackRequest request) {
        return ApiResponse.successByWallet(walletService.onlineCommercialBankCallback(request));
    }

    @ApiOperation("根据手机号获取门店列表")
    @PostMapping("/getShopList")
    public ResponseResult<ShopResponse> getShopNameAndCode(@RequestBody @Validated ShopListRequest request) {
        return ResponseResult.success(shopService.getShopNameAndCodeByMobile(request.getMobile(), request.getShopId()));
    }

    @PostMapping("/queryAllBigRegion")
    @ApiOperation("获取所有可选择的大区")
    public ApiResponse<List<BigRegionDTO>> queryContentInfo(@RequestBody @Validated StoreRequest request) {
        return ApiResponse.success(bigRegionService.queryAllBigRegion(request.getKeyword(), null,1));
    }

    @ApiOperation("获取管理下级区域")
    @PostMapping("/getSubRegionByParentId")
    public ApiResponse<List<RegionResponse>> getSubRegionByParentId(@RequestBody SubRegionRequest request) {
        return ApiResponse.success(regionService.getSubRegionByParentId(request.getRegionId()));
    }

    @ApiOperation("私域二维码-生成绑定二维码")
    @PostMapping("/ps/geBindQr")
    @Debounce(key = "#request.sn", diffUser = false, timeMs = 5000)
    public ApiResponse<PrivateSphereVO> geBindQr(@RequestBody @Validated PrivateSphereSnRequest request, HttpServletRequest httpRequest) {
        request.setClientIp(HttpHelper.getIpAddr(httpRequest));
        return ApiResponse.success(privateSphereQrService.generateQrCode(request));
    }

    @ApiOperation("私域二维码-根据设备sn获取门店私域二维码")
    @PostMapping("/ps/getPrivateSphereQr")
    @Debounce(key = "#request.sn", diffUser = false, timeMs = 5000)
    public ApiResponse<PrivateSphereVO> getPrivateSphereQr(@RequestBody @Validated PrivateSphereSnRequest request, HttpServletRequest httpRequest) {
        request.setClientIp(HttpHelper.getIpAddr(httpRequest));
        return ApiResponse.success(privateSphereQrService.getPrivateSphereQr(request));
    }

    @ApiOperation("获取门店设备列表")
    @PostMapping("/getDeviceByStoreNum")
    public ApiResponse<List<StoreXinFaDeviceDetail>> getStoreXinFaDeviceDetail(@RequestBody StoreNumRequest request) {
        return ApiResponse.success(xinFaBusinessService.getStoreXinFaDeviceDetail(request.getStoreNum()));
    }

}
