package com.cool.store.controller.webb;

import com.alibaba.fastjson.JSONObject;
import com.cool.store.context.PartnerUserHolder;
import com.cool.store.dto.*;
import com.cool.store.dto.store.StoreUserPositionDTO;
import com.cool.store.dto.wx.MiniProgramFreeLoginDTO;
import com.cool.store.handler.WeChatHandler;
import com.cool.store.request.OpenApiStoreRequest;
import com.cool.store.request.StoreCodeDTO;
import com.cool.store.request.*;
import com.cool.store.request.notice.ThirdHandleMessageRequest;
import com.cool.store.request.notice.ThirdMatterRequest;
import com.cool.store.request.xgj.FranchiseFeeCallBackRequest;
import com.cool.store.request.xgj.ReceiptCallBackRequest;
import com.cool.store.response.ResponseResult;
import com.cool.store.response.bigdata.ApiResponse;
import com.cool.store.service.*;
import com.cool.store.utils.poi.StringUtils;
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 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;

    @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()));
    }

    @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;
    }
}
