package com.cool.store.controller.webb;

import com.alibaba.fastjson.JSONObject;
import com.cool.store.constants.CommonConstants;
import com.cool.store.dao.*;
import com.cool.store.dao.fees.WalletPayInfoDAO;
import com.cool.store.dto.*;
import com.cool.store.dto.contract.ContractCallbackDTO;
import com.cool.store.dto.*;
import com.cool.store.dto.huoma.*;
import com.cool.store.dto.xgj.XgjBranchBankDTO;
import com.cool.store.dto.xgj.XgjPartnerPageDTO;
import com.cool.store.dto.wallet.*;
import com.cool.store.dto.xgj.XgjPayResultDTO;
import com.cool.store.entity.*;
import com.cool.store.entity.fees.WalletPayInfoDO;
import com.cool.store.enums.DownSystemTypeEnum;
import com.cool.store.enums.FranchiseBrandEnum;
import com.cool.store.enums.MessageEnum;
import com.cool.store.enums.SMSMsgEnum;
import com.cool.store.enums.point.ShopSubStageStatusEnum;
import com.cool.store.enums.wechat.WechatTemplateEnum;
import com.cool.store.handler.WeChatHandler;
import com.cool.store.job.XxlJobHandler;
import com.cool.store.mapper.FranchiseFeeMapper;
import com.cool.store.mapper.ShopInfoMapper;
import com.cool.store.mapper.SignFranchiseMapper;
import com.cool.store.mq.util.HttpRestTemplateService;
import com.cool.store.request.*;
import com.cool.store.request.bigdata.ProfitDataRequest;
import com.cool.store.request.close.store.CloseStoreApplyRequest;
import com.cool.store.request.huoma.ShopBasicInfoRequest;
import com.cool.store.request.oppty.*;
import com.cool.store.request.wallet.*;
import com.cool.store.request.xgj.PushFranchiseFeeRequest;
import com.cool.store.request.xgj.*;
import com.cool.store.response.ResponseResult;
import com.cool.store.response.bigdata.ActDataResponse;
import com.cool.store.response.bigdata.ApiResponse;
import com.cool.store.response.bigdata.ProfitDataResponse;
import com.cool.store.response.bigdata.ProfitRateResponse;
import com.cool.store.response.huoma.ShopBaseInfoResponse;
import com.cool.store.response.oppty.CityResponse;
import com.cool.store.response.oppty.OpportunityDetailResponse;
import com.cool.store.response.oppty.OpportunityInfoPageResponse;
import com.cool.store.service.*;
import com.cool.store.service.close.CloseStoreService;
import com.cool.store.service.fees.WalletPayInfoService;
import com.cool.store.service.impl.CommonService;
import com.cool.store.service.impl.UserAuthMappingServiceImpl;
import com.cool.store.service.wallet.WalletApiService;
import com.cool.store.service.wechat.WechatTemplateService;
import com.cool.store.service.xinfa.XinFaBusinessService;
import com.cool.store.utils.RsaSignUtil;
import com.cool.store.utils.poi.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.org.apache.xpath.internal.operations.Bool;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/pc/test")
public class PCTestController {

    @Resource
    private EnterpriseUserDAO enterpriseUserDAO;
    @Resource
    private BigRegionDAO bigRegionDAO;
    @Resource
    private ShopInfoDAO shopInfoDAO;
    @Resource
    private HqtAPIService hqtAPIService;
    @Resource
    private DecorationDesignInfoService decorationDesignInfoService;
    @Resource
    private DecorationMeasureService decorationMeasureService;
    @Resource
    private SyncMainSysServer syncMainSysServer;
    @Resource
    private CommonService commonService;
    @Resource
    private LineInfoDAO lineInfoDAO;
    @Resource
    private PointInfoDAO pointInfoDAO;
    @Resource
    private ShopService shopService;
    @Resource
    private LineInterviewDAO lineInterviewDAO;
    @Resource
    private XxlJobHandler xxlJobHandler;
    @Resource
    DataHandleService dataHandleService;
    @Resource
    DataHandlerServer dataHandlerServer;
    static String url = "https://hzly.cloudcubic.net/ajaxHandle/synchronization/JCallBackSynchronizationHandler.ashx?action=app&controller=GetProjectDetails&projectid=";

    @Resource
    private SyncDataService syncDataService;
    @Resource
    private HttpRestTemplateService httpRestTemplateService;
    @Resource
    FranchiseFeeMapper franchiseFeeMapper;
    @Resource
    WechatTemplateService wechatTemplateService;
    @Resource
    ShopInfoMapper shopInfoMapper;
    @Resource
    LinePayService linePayService;
    @Resource
    LinePayDAO linePayDAO;
    @Resource
    SignFranchiseMapper signFranchiseMapper;

    @Autowired
    WeChatHandler weChatHandler;
    @Resource
    ThirdXgjService thirdXgjService;
    @Resource
    CloseStoreService closeStoreService;

    @Resource
    SignFranchiseDAO signFranchiseDAO;

    @Resource
    SignFranchiseService signFranchiseService;
    @Resource
    WalletPayInfoService walletPayInfoService;

    @PostMapping("/walletReceiptRePush")
    public ResponseResult<Boolean> walletReceiptRePush(Long id) {
        walletPayInfoService.rePushReceipt(id);
        return ResponseResult.success(true);
    }

    @PostMapping("/applyCloseStore")
    public ResponseResult<Boolean> applyCloseStore(@RequestBody @Valid CloseStoreApplyRequest request) {
        return ResponseResult.success(closeStoreService.applyCloseStore(request));
    }

    @PostMapping("/reimburse")
    public ResponseResult<String> reimburse(@RequestBody XgjReimburseRequest request) {
        return ResponseResult.success(thirdXgjService.reimburse(request));
    }

    @PostMapping("/savePartner")
    public ResponseResult<String> savePartner(@RequestBody XgjSavePartnerRequest request) {
        return ResponseResult.success(thirdXgjService.savePartner(request));
    }

    @PostMapping("/queryOrderStatus")
    public ResponseResult<XgjPayResultDTO> queryOrderStatus(@RequestBody XgjPaymentRequest request) {
        return ResponseResult.success(thirdXgjService.queryOrderStatus(request));
    }

    @PostMapping("/queryPartnerPage")
    public ResponseResult<XgjPartnerPageDTO> queryPartnerPage(@RequestBody XgjPartnerQueryRequest request) {
        return ResponseResult.success(thirdXgjService.queryPartnerPage(request));
    }

    @PostMapping("/queryBranchBankList")
    public ResponseResult<List<XgjBranchBankDTO>> queryBranchBankList(@RequestBody XgjBankQueryRequest request) {
        return ResponseResult.success(thirdXgjService.queryBranchBankList(request));
    }

    @PostMapping("/accountClose")
    public ResponseResult<String> accountClose(@RequestBody XgjAccountCloseRequest request) {
        return ResponseResult.success(thirdXgjService.accountClose(request));
    }

    @GetMapping("/syncStore")
    public ResponseResult<Boolean> syncStore(@RequestParam("shopId")Long shopId){
        syncMainSysServer.syncStore(shopId);
        return ResponseResult.success(Boolean.TRUE);
    }

    @GetMapping("/sendMessage")
    public ResponseResult<Boolean> sendMessage(@RequestParam("lineId")Long lineId,
                                               @RequestParam("pointId")Long pointId,
                                               @RequestParam("shopId")Long shopId,
                                               @RequestParam MessageEnum messageEnum){
        LineInfoDO lineInfo = lineInfoDAO.getLineInfo(lineId);
        PointInfoDO pointInfo = pointInfoDAO.getPointInfoById(pointId);
        ShopInfoDO shopInfo = shopService.getShopInfo(shopId);
        Map<String, String> messageMap = new HashMap<>();
        messageMap.put("lineId", String.valueOf(lineId));
        messageMap.put("pointId", String.valueOf(pointId));
        messageMap.put("shopId", String.valueOf(shopId));
        messageMap.put("storeName", shopInfo.getShopName());
        messageMap.put("partnerUsername", lineInfo.getUsername());
        messageMap.put("partnerMobile", lineInfo.getMobile());
        messageMap.put("wantShopName", "杭州市余杭区");
        messageMap.put("appointmentTime", "2024-05-06 12:30");
        messageMap.put("interviewUsername", "章臣彪");
        messageMap.put("payTime", "2024-05-01 12:30");
        messageMap.put("submitTime", "2024-05-04 12:30");
        messageMap.put("pointName", pointInfo.getPointName());
        messageMap.put("pointAddress", pointInfo.getAddress());
        messageMap.put("reason", "表现一般不予通过");
        commonService.sendMessage(Arrays.asList("123836131931284423","020125244825417786"), messageEnum, messageMap);
        return ResponseResult.success(Boolean.FALSE);
    }

    @GetMapping("/sendSms")
    public ResponseResult<Boolean> sendSms(@RequestParam("startTime")String startTime, @RequestParam("endTime")String endTime){
        List<LineInterviewDO> interviewList = lineInterviewDAO.getInterviewRemindList(startTime, endTime);
        Map<String, String> templateParam = new HashMap<>();
        templateParam.put("pointName", "杭州门店A");
        List<SMSMsgEnum> smsMsgList = new ArrayList<>();
        for (SMSMsgEnum value : smsMsgList) {
            //commonService.sendSms("17681878615", value, templateParam);
        }
        return ResponseResult.success(Boolean.FALSE);
    }

    @GetMapping("/initShop")
    public ResponseResult<Boolean> initShop(@RequestParam("lineId")Long lineId){
        LineInfoDO lineInfo = lineInfoDAO.getLineInfo(lineId);
        shopService.initShop(lineInfo);
        return ResponseResult.success(Boolean.FALSE);
    }


    @GetMapping("/dataHandle")
    public ResponseResult<Boolean> dataHandle(@RequestParam("shopId")Long shopId){
        return ResponseResult.success(dataHandleService.dataHandleService(shopId));
    }

    @GetMapping("/openStageBatchInsert")
    public ResponseResult<Boolean> openStageBatchInsert(@RequestParam("shopId")Long shopId){
        return ResponseResult.success(dataHandleService.openStageBatchInsert(shopId));
    }

    @GetMapping("/dataHandleServiceV25")
    public ResponseResult<Integer> dataHandleServiceV25(){
        return ResponseResult.success(dataHandleService.dataHandleServiceV25());
    }

    @GetMapping("/licenseSync")
    public ResponseResult<Boolean> licenseSync(){
        xxlJobHandler.partnerSyncLicense();
        return ResponseResult.success(Boolean.TRUE);
    }
    @GetMapping("/testQWMessage")
    public ResponseResult<Boolean> testQWMessage(){
        List<String> userIds = new ArrayList<>();
        userIds.add("wpayJeDAAAhGIFgUJpJN-zg39JuNbYhg_woayJeDAAA52Wm6ZigyveSjniyimeqZQ");
        HashMap<String, String> map = new HashMap<>();
        map.put("partnerUsername","sx");
        map.put("partnerMobile","13563273279");
        commonService.sendQWMessage(userIds,
                MessageEnum.MESSAGE_14,
                map);

        return ResponseResult.success(Boolean.TRUE);
    }
    @Resource
    ThirdOpportunityService thirdOpportunityService;
    @Resource
    ThirdBigDataService thirdBigDataService;
    @Resource
    HuoMaService huoMaService;

    @PostMapping("/list")
    @ApiOperation("机会点列表/我的机会点")
    public ResponseResult<OpportunityInfoPageResponse> listOpportunities(@Valid @RequestBody OpportunityListRequest request) {
        OpportunityInfoPageResponse list = thirdOpportunityService.listOpportunities(request);
        return ResponseResult.success(list);
    }


    @PostMapping("/getOpportunitiesDetail")
    @ApiOperation("机会点详情")
    public ResponseResult<OpportunityDetailResponse> getOpportunitiesDetail(@Valid @RequestBody OpportunityDetailRequest request) {
        OpportunityDetailResponse list = thirdOpportunityService.getOpportunitiesDetail(request);
        return ResponseResult.success(list);
    }


    @PostMapping("/followOpportunity")
    @ApiOperation("关注/取消关注 机会点")
    public ResponseResult<String> followOpportunity(@Valid @RequestBody FollowRequest request) {
        return ResponseResult.success(thirdOpportunityService.followOpportunity(request));
    }

    @PostMapping("/inspectionOpportunity")
    @ApiOperation("考察机会点")
    public ResponseResult<String> inspectionOpportunity(@Valid @RequestBody InspectionRequest request) {
        return ResponseResult.success(thirdOpportunityService.inspectionOpportunity(request));
    }

    @PostMapping("/berthOperation")
    @ApiOperation("铺位关注机会点")
    public ResponseResult<String> berthOperation(@Valid @RequestBody BerthOperationRequest request) {
        return ResponseResult.success(thirdOpportunityService.berthOperation(request));
    }

    @PostMapping("/storeOperation")
    @ApiOperation("门店关注机会点")
    public ResponseResult<String> storeOperation(@Valid @RequestBody StoreOperationRequest request) {
        return ResponseResult.success(thirdOpportunityService.storeOperation(request));
    }

    @PostMapping("/cityList")
    @ApiOperation("省市区列表 查询省传0")
    public ResponseResult<List<CityResponse>> listOpportunities(@Valid @RequestBody CityRequest request) {
        // 调用第三方接口
        List<CityResponse> list = thirdOpportunityService.cityList(request);
        return ResponseResult.success(list);
    }

    @PostMapping("/getProfitData")
    @ApiOperation("昨天毛利")
    public ResponseResult<ProfitDataResponse> listOpportunities(@Valid @RequestBody ProfitDataRequest request) {
        // 调用第三方接口
        return ResponseResult.success(thirdBigDataService.getProfitData(request));
    }

    @PostMapping("/getCurMonthProfitData")
    @ApiOperation("本月毛利")
    public ResponseResult<ProfitDataResponse> getCurMonthProfitData(@Valid @RequestBody ProfitDataRequest request) {
        // 调用第三方接口
        return ResponseResult.success(thirdBigDataService.getCurMonthProfitData(request));
    }


    @PostMapping("/getPreMonthProfitData")
    @ApiOperation("上月毛利")
    public ResponseResult<ProfitDataResponse> getPreMonthProfitData(@Valid @RequestBody ProfitDataRequest request) {
        // 调用第三方接口
        return ResponseResult.success(thirdBigDataService.getPreMonthProfitData(request));
    }


    @PostMapping("/getMonthProfitTrend")
    @ApiOperation("毛利趋势")
    public ResponseResult<List<ProfitRateResponse>> getMonthProfitTrend(@Valid @RequestBody ProfitDataRequest request) {
        // 调用第三方接口
        return ResponseResult.success(thirdBigDataService.getMonthProfitTrend(request));
    }

    @PostMapping("/getActData")
    @ApiOperation("门店实收")
    public ResponseResult<ActDataResponse> getActData(@Valid @RequestBody ProfitDataRequest request) {
        // 调用第三方接口
        return ResponseResult.success(thirdBigDataService.getActData(request));
    }


    @PostMapping("/getShopInfo")
    @ApiOperation("火码 查询门店信息")
    public ResponseResult<ShopBaseInfoResponse> getShopInfo(@Valid @RequestBody ShopBasicInfoRequest request) {
        // 调用第三方接口
        return ResponseResult.success(huoMaService.getShopInfo(request));
    }

    @GetMapping("/getData")
    public  ResponseResult getData(@RequestParam("shopId")Long shopId,@RequestParam("type")Integer type){
        return ResponseResult.success(syncDataService.getData(shopId, DownSystemTypeEnum.getByCode(type)));
    }


    @Resource
    ShopAccountDAO shopAccountDAO;
    @Resource
    HyPartnerUserInfoDAO hyPartnerUserInfoDAO;
    @GetMapping("/initShopAccount")
    @ApiOperation("初始化门店账号")
    public ResponseResult<Integer> initShopAccount(@RequestParam(value = "partnerId", required = true) String partnerId,
                                                @RequestParam(value = "shopId", required = true) Long shopId) {
        // 调用第三方接口
        HyPartnerUserInfoDO hyPartnerUserInfoDO = hyPartnerUserInfoDAO.selectByPartnerId(partnerId);
        return ResponseResult.success(shopAccountDAO.initShopAccount(hyPartnerUserInfoDO,Arrays.asList(shopId)));
    }

    @Resource
    private PushService pushService;
    @GetMapping("/getXgjOrganization")
    @ApiOperation("获取新管家组织架构")
    public ResponseResult<Object> getXgjOrganization(@RequestParam(value = "partnerId", required = true,defaultValue = "0") String partnerId) {
        return ResponseResult.success(pushService.getXgjOrganization(partnerId));
    }

    @GetMapping("/getXgjAccessToken")
    @ApiOperation("获取新管家token")
    public ResponseResult<Object> getXgjAccessToken() {
        return ResponseResult.success(pushService.getXgjAccessToken());
    }

    @GetMapping("/getUnReadMessageNum")
    @ApiOperation("getUnReadMessageNum")
    public ResponseResult<Object> getUnReadMessageNum(@RequestParam(value = "partnerId", required = true,defaultValue = "0") String partnerId) {
        return ResponseResult.success(pushService.getUnReadMessageNum(partnerId));
    }



    @Resource
    ShopAccountService accountService;
    @Resource
    ThirdXinGuanJiaService thirdXinGuanJiaService;

    @ApiOperation("修改密码")
    @PostMapping("/modifyPassword")
    public ResponseResult<Boolean> modifyPassword(@RequestBody ModifyPasswordDTO request) {
        return ResponseResult.success(accountService.modifyPassword(request));
    }

    @ApiOperation("获取POS免登token")
    @PostMapping("/getPosToken")
    public ResponseResult<String> getPosToken(@RequestBody @Validated GetAccessTokenDTO dto) {
        return ResponseResult.success(pushService.getPosToken(dto));
    }



    @ApiOperation("获取加密子串")
    @PostMapping("/getEncryptedSubstring")
    public ResponseResult<String> getEncryptedSubstring(@RequestBody GetPasswordDTO dto) {
        return ResponseResult.success(thirdXinGuanJiaService.getPassword(dto));
    }

    @Resource
    UserAuthMappingServiceImpl userAuthMappingService;

    @GetMapping("/getAuthRegionIdAndSubRegionIdByUserId")
    @ApiOperation("获取管辖的子区域")
    public ResponseResult<List<String>> getAuthRegionIdAndSubRegionIdByUserId(@RequestParam(value = "userId", required = true) String userId) {
        return ResponseResult.success(userAuthMappingService.getAuthRegionIdAndSubRegionIdByUserId(userId));
    }
    @Resource
    ThirdFoodService thirdFoodService;
    @ApiOperation("获取菜品市场token")
    @PostMapping("/getFoodToken")
    public ResponseResult<String> getFoodToken(@RequestBody @Validated FoodTokenDTO dto) {
        return ResponseResult.success(thirdFoodService.getFoodToken(dto));
    }


    @GetMapping("/getToday")
    @ApiOperation("getToday")
    public ResponseResult<Boolean> getToday() {
        for (int i = 0; i < 10; i++) {
            System.out.println(linePayService.getPaymentReceiptCode());
        }
        return ResponseResult.success(Boolean.TRUE);
    }

    @GetMapping("/pushFranchiseFee")
    @ApiOperation("推送账单")
    public ResponseResult<Boolean> pushFranchiseFee(@RequestParam(value = "shopId", required = true) Long shopId) {
        FranchiseFeeDO franchiseFeeDO = franchiseFeeMapper.selectByShopId(shopId);
        ShopInfoDO shopInfoDO = shopInfoMapper.selectByPrimaryKey(shopId);
        LineInfoDO lineInfoDO = lineInfoDAO.getLineInfo(shopInfoDO.getLineId());
        PushFranchiseFeeRequest feeRequest = new PushFranchiseFeeRequest(shopInfoDO.getId(), lineInfoDO.getUsername(), franchiseFeeDO, Integer.valueOf(shopInfoDO.getFranchiseBrand()));
        pushService.pushFranchiseFeeToXGJ(feeRequest);
        return ResponseResult.success(Boolean.TRUE);
    }

    @GetMapping("/pushPay")
    @ApiOperation("推送收款单")
    public ResponseResult<Boolean> pushPay(@RequestParam(value = "shopId", required = true) Long shopId,
                                                @RequestParam(value = "payId", required = true) Long payId) {
        LinePayDO pay = linePayDAO.getById(payId);
        linePayService.pushPayInfo(shopId,pay);
        return ResponseResult.success(Boolean.TRUE);
    }


    @GetMapping("/pushContract")
    @ApiOperation("推送合同信息")
    public ResponseResult<Boolean> pushContract(@RequestParam(value = "shopId", required = true) Long shopId) {

        ShopInfoDO shopInfoDO = shopInfoDAO.getShopInfo(shopId);
        ContractCallbackDTO contractCallbackDTO = signFranchiseService.pushContractRequest(shopInfoDO, shopId);
        if (!Objects.isNull(contractCallbackDTO)){
            if (StringUtils.isNoneEmpty(contractCallbackDTO.getStoreCode())&&StringUtils.isBlank(shopInfoDO.getShopCode())){
                shopInfoDO.setShopCode(contractCallbackDTO.getStoreCode());
                shopInfoDAO.updateShopInfo(shopInfoDO);
            }
            signFranchiseDAO.updateAuditByShopId(null, shopId,contractCallbackDTO);
        }
        return ResponseResult.success(Boolean.TRUE);
    }

    @Resource
    ShopStageInfoDAO shopStageInfoDAO;

    @GetMapping("/franchiseFeeDataHandler")
    @ApiOperation("加盟费数据处理")
    public ResponseResult<Boolean> franchiseFeeDataHandler(){
        //查询所有的待加盟商缴费 推送账单
        List<ShopStageInfoDO> shopList = shopStageInfoDAO.getShopIdListByStageStatus(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_71.getShopSubStageStatus());
        log.info("----------开始推送账单数据---------");
        shopList.forEach(x->{
            try {
                FranchiseFeeDO franchiseFeeDO = franchiseFeeMapper.selectByShopId(x.getShopId());
                ShopInfoDO shopInfoDO = shopInfoMapper.selectByPrimaryKey(x.getShopId());
                LineInfoDO lineInfoDO = lineInfoDAO.getLineInfo(shopInfoDO.getLineId());
                PushFranchiseFeeRequest feeRequest = new PushFranchiseFeeRequest(shopInfoDO.getId(), lineInfoDO.getUsername(), franchiseFeeDO,Integer.valueOf(shopInfoDO.getFranchiseBrand()));
                pushService.pushFranchiseFeeToXGJ(feeRequest);
            } catch (Exception e) {
                log.error("推送数据失败  shopId {},异常信息：{}",x,e.getMessage());
            }
        });
        log.info("----------推送账单数据结束---------");
        //对账中
        log.info("----------开始推送账单与收款单数据---------");
        List<ShopStageInfoDO> shopList2 = shopStageInfoDAO.getShopIdListByStageStatus(ShopSubStageStatusEnum.SHOP_SUB_STAGE_STATUS_72.getShopSubStageStatus());
        shopList2.forEach(x->{
            //先推送账单
            try {
                FranchiseFeeDO franchiseFeeDO = franchiseFeeMapper.selectByShopId(x.getShopId());
                ShopInfoDO shopInfoDO = shopInfoMapper.selectByPrimaryKey(x.getShopId());
                LineInfoDO lineInfoDO = lineInfoDAO.getLineInfo(shopInfoDO.getLineId());
                PushFranchiseFeeRequest feeRequest = new PushFranchiseFeeRequest(shopInfoDO.getId(), lineInfoDO.getUsername(), franchiseFeeDO,Integer.valueOf(shopInfoDO.getFranchiseBrand()));
                pushService.pushFranchiseFeeToXGJ(feeRequest);
                List<LinePayDO> franchiseFeePayInfoByShopId = linePayDAO.getFranchiseFeePayInfoByShopId(x.getShopId());
                franchiseFeePayInfoByShopId.forEach(y->{
                    linePayService.pushPayInfo(x.getShopId(),y);
                });
            } catch (Exception e) {
                log.error("推送数据失败  shopId {},异常信息：{}",x,e.getMessage());
            }
        });
        log.info("----------账单与收款单数据推送完成---------");
        return ResponseResult.success(Boolean.TRUE);
    }

    @GetMapping("/getHqtToken")
    public ResponseResult<HqtTokenDTO> getHqtToken() {
        return ResponseResult.success(pushService.getHqtToken());
    }

    @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("/assignQuotation")
    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("/decorationAcceptance")
    public ApiResponse<Boolean> decorationAcceptance(@RequestBody @Validated HqtDecorationAcceptanceRequest request) {
        log.info("decorationAcceptance request：{}", JSONObject.toJSONString(request));
        return ApiResponse.success(decorationDesignInfoService.decorationAcceptance(request));
    }

    @ApiOperation("测试红圈通建店")
    @GetMapping("/testHqtBuild")
    public ApiResponse<Boolean> testHqtBuild(@RequestParam("shopId")Long shopId) {
        hqtAPIService.pushHqtBuild(signFranchiseService.getHqtBuildRequest(shopId));
        return ApiResponse.success(true);
    }

    @ApiOperation("测试红圈推送片区")
    @GetMapping("/testHqtRegion")
    public ApiResponse<Boolean> testHqtRegion() {
        hqtAPIService.pushHqtRegion(null);
        return ApiResponse.success(true);
    }


    @RequestMapping(value = "/testWxNotice", produces = "application/xml;charset=UTF-8")
    @ApiOperation("testWxNotice")
    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) {

        System.out.println("收到微信消息:");
        System.out.println("signature: " + signature);
        System.out.println("timestamp: " + timestamp);
        System.out.println("nonce: " + nonce);
        System.out.println("echostr: " + echostr);
        System.out.println("requestBody: " + requestBody);

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

    @ApiOperation("测试小程序模板消息")
    @PostMapping("/testMiniAppTemplate")
    public ApiResponse<Boolean> testMiniAppTemplate() {
        Map<String, Object> data = new HashMap<>();
        data.put("character_string2", "ceshi002");
        data.put("thing10", "测试通知功能");
        data.put("time14", "2025-10-01 12:00:00");
        data.put("thing25", "正新管理有限公司");
        data.put("thing60", "上海市-松江区");
        wechatTemplateService.sendNormalTemplate("o9_unvpJy1SGdnkeun7igRBSLuB0", WechatTemplateEnum.QUESTION_NOTICE, data);
        return ApiResponse.success(true);
    }

    @Resource
    XinFaBusinessService xinFaBusinessService;
    @ApiOperation("测试门店设备信息")
    @GetMapping("/getStoreXinFaDeviceDetail")
    public ResponseResult<List<StoreXinFaDeviceDetail>> getStoreXinFaDeviceDetail(@RequestParam("storeNum")String storeNum) {
        return ResponseResult.success(xinFaBusinessService.getStoreXinFaDeviceDetail(storeNum));
    }

    @ApiOperation("测试标签信息")
    @GetMapping("/getAccountAllTags")
    public ResponseResult<List<TagDetailDTO>> getAccountAllTags(@RequestParam("storeNum")String storeNum,
                                                                @RequestParam("deviceName")String deviceName) {
        List<TagDetailDTO> accountAllTags = xinFaBusinessService.getAccountAllTags(storeNum,deviceName);
        return ResponseResult.success(accountAllTags);
    }

    @ApiOperation("获取节目列表")
    @PostMapping("/getProgramList")
    public ResponseResult<List<ProgramResponseDTO>> getProgramList(@RequestBody ProgramReqDTO programReqDTO) {
        List<ProgramResponseDTO> accountAllTags = xinFaBusinessService.getProgramList(programReqDTO);
        return ResponseResult.success(accountAllTags);
    }

    @ApiOperation("发布/上架")
    @PostMapping("/publishProgram")
    public ResponseResult<Boolean> publishProgram(@RequestBody PublishDTO publishDTO) {
        Boolean publishStatus = xinFaBusinessService.publishProgram(publishDTO);
        return ResponseResult.success(publishStatus);
    }


    public static void main(String[] args) {
        // 测试数据
        Map<String, Object> params = new HashMap<>();
        params.put("key", "370728957227141");
        params.put("status", 1);
        params.put("addTagType", 1);
        params.put("timestamp", "1763694267");
        params.put("outStoreId", "359c107b31c148b59fbe1c2562fdd096");


        String privateKey = "MIIEpQIBAAKCAQEA0erPAWesjkp9J4htmfCyqKS9npmT9dW3KqWTfb4c7x/QBUtKuokWOO0XikHd4bGUa9kl+twSv/5A3kYz1B9eg6wRuDJoads+G5U7rVQjzdoUtLaf3lNXkuSehl4uHUPQfNa6vcmvzraXPxJjEpYzj9WZh7uJqq2oSgw42H1qdbFCXSaE5BwsOb+2vZXjzh4RO10Sy3Qb1UqGsoZoxVzrtDeEctCjrecFyQr96L2UtYa4NTxSTfu4rgObrwIOMvqqnLsXEzK/rd6kIHYjkZYQCOa48AedWp2YKQ7Ldclj+VMLnXvl42J9exVkbs++8k3P5sI9fdZX4Ey2RBjnSoAo/QIDAQABAoIBACbBGi8I+CE77M+13wAu4RkD8xL7CQc3ic2ojGqIRPi7r5CuphD6mpzvXqtyfhd7DKr9h8bAxwBlnQ28ObjVgsI96/aM7dxvMs/uVPpqwIJyWuTDG5A05EPVC9REQnC6Mp09mnPL7rZz3Mfy6dIGY2YQWfwmWiPl1B45k+wZ+WPZPI0JVnvRzM881kf4aAhEAt08i9VoihylwVAjWIPmLuhf6ZcqI5q8iUsjfO22wZJsudVTCA/dsJdNxv+1RDKeYnSLJL79cZQcodqEhFqTy6vnn2dMsaHH7dpphU27barxUjeL482SR7kFfMqEXn5sltRn/3ep+3sf4Ph2vMtoZeECgYEA6gXzEtT9ZOeAMp4BRGmfNZ0TQLprPPVSwudz/uUBE4j/vyhfXkh9p7hqwyoxN+Z8b65yINvx8yP6hge6ek/MyAwBCZyfIRxZAPZu1eEGoYKl391ubFt2EIVqrN2DtAvzHMr5B/E2VHBq6AJm/rERFX5oKsg6zHS9tPLhgGnWVd0CgYEA5aFWOrtiqZJlp1MHQ4OeWBJatBSynkORdxCW7ic0CKbkYus0NSz1SsvskpbnfEXNB53x98qJxRhSopg/DC4m7XqxjSf9lY3HH4Y/9907olj33yGAnLWC88GivVndt577u/XhYRCk33vOQ3GoibEdjnpMOkWmOfwYG/FsRWWQvaECgYEA1N2siEisZIgel+wZAv2AD+hchtgKi1wqd5bIb+Yl4HsRBfPXK4+MnG6mzfcm5c4FCiEHNtRZc+waCKgm+vJzNtOUbgXEyP1cCAAgOPOCcI7CCqsDshRPhB+XNL4Y+kCUVnBZrNu/q3bGB1uIC8tL2t0sKx4OPcNCe8EhVQjwKRECgYEA4uothdhKRPtwDIsVsHfN74Yjr7SMVay7gIcaPrjqyGnzYnS+oJWOx50AaFNK6Rko5JAF3jF9NxE0B4yfMPAic6Y88hpEkpcJ4HMPn2Y1WdbFCu/WYgVUJICCys6VNLCcXj85umtyIY38Y9VbEMW/SV49GZBeFQqy4FoP/fvBrkECgYEAnfjTDYwgdmJdsUqyNzAocwcJXG2rVtYc7Txrl0TltcwuJmgoSywdzyOP2R9+NZsfoxWDzG0/yr15ApMvUcnnTwHN/8bGQ9SLatFLKqS4EtdwDKKS1JvNbs7V1myQGpt7jbShZOI0e6Fs4xP8ujxsLeGgiq9mZrS9UdRj5XKDoVM=";

        String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0erPAWesjkp9J4htmfCyqKS9npmT9dW3KqWTfb4c7x/QBUtKuokWOO0XikHd4bGUa9kl+twSv/5A3kYz1B9eg6wRuDJoads+G5U7rVQjzdoUtLaf3lNXkuSehl4uHUPQfNa6vcmvzraXPxJjEpYzj9WZh7uJqq2oSgw42H1qdbFCXSaE5BwsOb+2vZXjzh4RO10Sy3Qb1UqGsoZoxVzrtDeEctCjrecFyQr96L2UtYa4NTxSTfu4rgObrwIOMvqqnLsXEzK/rd6kIHYjkZYQCOa48AedWp2YKQ7Ldclj+VMLnXvl42J9exVkbs++8k3P5sI9fdZX4Ey2RBjnSoAo/QIDAQAB";

        try {
            // 1. 加签
            String sign = RsaSignUtil.generateSign(new HashMap<>(params), privateKey);
            System.out.println("生成的签名: " + sign);

            // 2. 将签名放入参数中
            params.put("sign", sign);

            // 3. 验签
            boolean isValid = RsaSignUtil.verifySign(new HashMap<>(params), publicKey);
            System.out.println("验签结果: " + isValid);

            // 4. 测试排序字符串生成
            String sortedString = RsaSignUtil.objectToSortedString(params);
            System.out.println("排序后的字符串: " + sortedString);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Resource
    WalletApiService walletApiService;

    @ApiOperation("获取银行信息")
    @PostMapping("/getBankList")
    public ResponseResult<BankListDTO> getBankList(@RequestBody GetBankRequest request) {
        BankListDTO bankList = walletApiService.getBankList(request);
        return ResponseResult.success(bankList);
    }

    @ApiOperation("签约人开通信息")
    @PostMapping("/createStoreAndAccount")
    public ResponseResult<StoreAccountDTO> createStoreAndAccount(@RequestBody CreateStoreAndAccountRequest request) {
        StoreAccountDTO dto = walletApiService.createStoreAndAccount(request);
        return ResponseResult.success(dto);
    }

    @ApiOperation("创建门店接口")
    @PostMapping("/createStore")
    public ResponseResult<AccountNoDTO> createStore(@RequestBody CreateStoreRequest request) {
        AccountNoDTO accountNoDTO = walletApiService.createStore(request);
        return ResponseResult.success(accountNoDTO);
    }


    @ApiOperation("打标接口")
    @PostMapping("/addTag")
    public ResponseResult<AddTagDTO> addTag(@RequestBody AccountAddTagRequest request) {
        AddTagDTO addTag = walletApiService.addTag(request);
        return ResponseResult.success(addTag);
    }

    @ApiOperation("门店签约人账户鉴权申请接口")
    @PostMapping("/authentication")
    public ResponseResult<AccountAuthenticationDTO> authentication(@RequestBody OutStoreIdRequest request) {
        AccountAuthenticationDTO accountAuthenticationDTO = walletApiService.authentication(request);
        return ResponseResult.success(accountAuthenticationDTO);
    }

    @ApiOperation("门店签约人账户开通接口")
    @PostMapping("/openAccount")
    public ResponseResult<AccountVerifyDTO> openAccount(@RequestBody AccountVerifyRequest request) {
        AccountVerifyDTO accountVerifyDTO = walletApiService.openAccount(request);
        return ResponseResult.success(accountVerifyDTO);
    }

    @ApiOperation("获取账户信息")
    @PostMapping("/getAccountInfo")
    public ResponseResult<List<AccountInfoDTO>> getAccountInfo(@RequestBody OutStoreIdRequest request) {
        List<AccountInfoDTO> accountInfoList = walletApiService.getAccountInfo(request);
        return ResponseResult.success(accountInfoList);
    }

    @ApiOperation("大额预支付接口")
    @PostMapping("/largePayment")
    public ResponseResult<LargePaymentDTO> largePayment(@RequestBody LargePaymentRequest request) {
        LargePaymentDTO largePayment = walletApiService.largePayment(request);
        return ResponseResult.success(largePayment);
    }

    @ApiOperation("大额预支付查询接口")
    @PostMapping("/largePaymentQuery")
    public ResponseResult<PaymentDTO> largePaymentQuery(@RequestBody PaymentDetailRequest request) {
        PaymentDTO PaymentDTO = walletApiService.largePaymentQuery(request);
        return ResponseResult.success(PaymentDTO);
    }

    @ApiOperation("门店账户向公司分账转账接口")
    @PostMapping("/transfer")
    public ResponseResult<TransferDTO> transfer(@RequestBody TransferRequest request) {
        TransferDTO transfer = walletApiService.transfer(request);
        return ResponseResult.success(transfer);
    }

    @ApiOperation("门店签约账户,退款提现至提现卡")
    @PostMapping("/withdraw")
    public ResponseResult<WithDrawerDTO> withdraw(@RequestBody WithDrawerRequest request) {
        WithDrawerDTO withdraw = walletApiService.withdraw(request);
        return ResponseResult.success(withdraw);
    }

    @ApiOperation(" 获取账单详情")
    @PostMapping("/getBillDetail")
    public ResponseResult<TradeRecordDTO> getBillDetail(@RequestBody BillDetailRequest request) {
        TradeRecordDTO billDetail = walletApiService.getBillDetail(request);
        return ResponseResult.success(billDetail);
    }

    @ApiOperation("获取账单列表")
    @PostMapping("/getBillPage")
    public ResponseResult<BillPageDTO> getBillPage(@RequestBody BillPageRequest request) {
        BillPageDTO billPage = walletApiService.getBillPage(request);
        return ResponseResult.success(billPage);
    }

    @ApiOperation("获取银行信息")
    @PostMapping("/getCompanyInfo")
    public ResponseResult<CompanyListDTO> getCompanyInfo(@RequestBody FindPageCompanyRequest request) {
        CompanyListDTO companyDTO = walletApiService.getCompanyInfo(request);
        return ResponseResult.success(companyDTO);
    }


    @ApiOperation("获取账户列表信息")
    @PostMapping("/getAccountList")
    public ResponseResult<AccountPageDTO> getAccountList(@RequestBody AccountBatchQueryRequest request) {
        AccountPageDTO accountList = walletApiService.getAccountList(request);
        return ResponseResult.success(accountList);
    }

    @ApiOperation("账户分账接口")
    @PostMapping("/accountTransfer")
    public ResponseResult<AccountTransferDTO> accountTransfer(@RequestBody AccountTransferRequest request) {
        AccountTransferDTO accountList = walletApiService.accountTransfer(request);
        return ResponseResult.success(accountList);
    }

    @ApiOperation("组织账户查询接口")
    @PostMapping("/findOrgAccount")
    public ResponseResult<OrgAccountDTO> findOrgAccount(@RequestBody AccountPageRequest request) {
        OrgAccountDTO accountList = walletApiService.findOrgAccount(request);
        return ResponseResult.success(accountList);
    }

    @ApiOperation("账户提现接口")
    @PostMapping("/accountWithdrawer")
    public ResponseResult<AccountWithdrawerDTO> accountWithdrawer(@RequestBody AccountWithdrawerRequest request) {
        AccountWithdrawerDTO accountList = walletApiService.accountWithdrawer(request);
        return ResponseResult.success(accountList);
    }



    @Value("${cool.api.rsa.private.key}")
    private String coolPrivateKey;
    @Value("${cool.api.rsa.public.key}")
    private String coolPublicKey;
    @ApiOperation("验签")
    @PostMapping("/verify")
    public ResponseResult<Boolean> test(@RequestBody TestVerifyRequest request) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Map<String, Object> params = objectMapper.readValue(JSONObject.toJSONString(request), new TypeReference<Map<String, Object>>() {});
            String s = RsaSignUtil.generateSign(params, coolPrivateKey);
            params.put("sign",s);
            boolean b = RsaSignUtil.verifySign(params, coolPublicKey);
            log.info("验签结果：{}",b);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return ResponseResult.success(Boolean.TRUE);
    }


    @ApiOperation("开业验收数据处理")
    @GetMapping("/openingAcceptanceDataHandle")
    public ResponseResult<Boolean> openingAcceptanceDataHandle() {
        dataHandlerServer.openingAcceptanceDataHandle();
        return ResponseResult.success(Boolean.TRUE);
    }


    @ApiOperation("推送数据")
    @PostMapping("/pushReceiptToXGJ")
    public ResponseResult<Boolean> getAccountList(@RequestBody ReceiptRequest request) {
        pushService.pushReceiptToXGJ(request);
        return ResponseResult.success(Boolean.TRUE);
    }

    @Resource
    private WalletPayInfoDAO walletPayInfoDAO;
    @Resource
    FranchiseFeeDAO franchiseFeeDAO;

    @GetMapping("/pushReceiptToXGJ1")
    public ResponseResult<Boolean> pushReceiptToXGJ(@RequestParam(value = "shopId", required = false) Long shopId,
                                                    @RequestParam(value = "payId", required = false) Long payId) {
        ShopInfoDO shopInfoDO = shopInfoDAO.getShopInfo(shopId);
        if (shopInfoDO==null){
            return  ResponseResult.success(Boolean.FALSE);
        }
        FranchiseFeeDO franchiseFeeDO = franchiseFeeDAO.selectByShopId(shopInfoDO.getId());
        WalletPayInfoDO payInfo = walletPayInfoDAO.getById(payId);
        if (franchiseFeeDO==null||payInfo==null){
            return ResponseResult.success(Boolean.FALSE);
        }
        ReceiptRequest receiptRequest = new ReceiptRequest(shopInfoDO.getId(), franchiseFeeDO.getId().intValue(), payInfo, Integer.valueOf(shopInfoDO.getFranchiseBrand()));
        pushService.pushReceiptToXGJ(receiptRequest);
        return ResponseResult.success(Boolean.TRUE);
    }

}
