package com.ycwl.basic.controller.pc;

import com.ycwl.basic.constant.BaseContextHandler;
import com.ycwl.basic.integration.scenic.dto.scenic.ScenicV2DTO;
import com.ycwl.basic.model.mobile.statistic.req.CommonQueryReq;
import com.ycwl.basic.model.pc.mp.MpConfigEntity;
import com.ycwl.basic.model.pc.scenic.entity.ScenicAccountEntity;
import com.ycwl.basic.model.pc.scenic.req.ScenicReqQuery;
import com.ycwl.basic.repository.ScenicRepository;
import com.ycwl.basic.service.mobile.AppScenicService;
import com.ycwl.basic.service.mobile.AppStatisticsService;
import com.ycwl.basic.service.pc.ScenicAccountService;
import com.ycwl.basic.service.pc.ScenicService;
import com.ycwl.basic.storage.StorageFactory;
import com.ycwl.basic.storage.adapters.IStorageAdapter;
import com.ycwl.basic.storage.enums.StorageAcl;
import com.ycwl.basic.utils.ApiResponse;
import com.ycwl.basic.utils.WxMpUtil;
import org.apache.commons.lang3.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.Collections;
import java.util.List;

import static com.ycwl.basic.constant.JwtRoleConstant.ADMIN;
import static com.ycwl.basic.constant.JwtRoleConstant.MERCHANT;

/**
 * @Author：longbinbin
 * @Date：2024/12/3 15:20
 */
@RestController
@RequestMapping("/api/scenic/v1")
// 景区管理
public class ScenicController {

    @Autowired
    private ScenicService scenicService;
    @Autowired
    private AppScenicService appScenicService;

    @Autowired
    private ScenicRepository scenicRepository;
    @Autowired
    private AppStatisticsService appStatisticsService;
    @Autowired
    private ScenicAccountService accountService;

    // 根据景区ID下载小程序二维码
    @GetMapping("/{id}/QRCode")
    public ApiResponse<String> downloadQrCode(@PathVariable Long id) {
        MpConfigEntity mpConfig = scenicRepository.getScenicMpConfig(id);
        if (mpConfig == null) {
            return ApiResponse.fail("小程序配置不存在");
        }
        String appId = mpConfig.getAppId();
        String appSecret = mpConfig.getAppSecret();
        String appState = mpConfig.getState();
        String path = "pages/home/index?scenicId=" + id;
        String filePath = "qr_code_" + id + ".jpg";
        IStorageAdapter adapter = StorageFactory.use();
        if (adapter.isExists(filePath)) {
            return ApiResponse.success(adapter.getUrl(filePath));
        }
        try {
            WxMpUtil.generateWXAQRCode(appId, appSecret, appState, path, filePath);
            File file = new File(filePath);
            String s = adapter.uploadFile(null, file, filePath);
            file.delete();
            adapter.setAcl(StorageAcl.PUBLIC_READ, filePath);
            return ApiResponse.success(s);
        } catch (Exception e) {
            return ApiResponse.fail("生成二维码失败");
        }
    }

    @PostMapping("/{scenicId}/one")
    public ApiResponse getStatisticsOne(@PathVariable("scenicId") Long scenicId, @RequestBody CommonQueryReq query) {
        query.setScenicId(scenicId);
        return appStatisticsService.oneStatistics(query);
    }
    @PostMapping("/{scenicId}/two")
    public ApiResponse getStatisticsTwo(@PathVariable("scenicId") Long scenicId, @RequestBody CommonQueryReq query) {
        query.setScenicId(scenicId);
        return appStatisticsService.twoStatistics(query);
    }
    @PostMapping("/{scenicId}/three")
    public ApiResponse getStatisticsThree(@PathVariable("scenicId") Long scenicId, @RequestBody CommonQueryReq query) {
        query.setScenicId(scenicId);
        return appStatisticsService.freeStatistics(query);
    }
    @PostMapping("/{scenicId}/fun")
    public ApiResponse getStatisticsFun(@PathVariable("scenicId") Long scenicId, @RequestBody CommonQueryReq query) {
        query.setScenicId(scenicId);
        return appStatisticsService.userConversionFunnel(query);
    }
    @PostMapping("/{scenicId}/orderChart")
    public ApiResponse getOrderChart(@PathVariable("scenicId") Long scenicId, @RequestBody CommonQueryReq query) {
        query.setScenicId(scenicId);
        return appStatisticsService.orderChart(query);
    }

    @GetMapping("/myScenicList")
    public ApiResponse<List<ScenicV2DTO>> myScenicList() {
        List<ScenicV2DTO> list = Collections.emptyList();
        if (Strings.CS.equals(BaseContextHandler.getRoleId(), MERCHANT.type)) {
            String userId = BaseContextHandler.getUserId();
            ScenicAccountEntity account = accountService.getScenicAccountById(Long.valueOf(userId));
            if (account == null || account.getScenicId().isEmpty()) {
                return ApiResponse.fail("景区账号未绑定景区");
            }
            list = account.getScenicId().stream().map(id -> scenicRepository.getScenicBasic(id)).toList();
        } else if (Strings.CS.equals(BaseContextHandler.getRoleId(), ADMIN.type)) {
            ScenicReqQuery query = new ScenicReqQuery();
            query.setPageSize(1000);
            list = scenicRepository.list(query);
        }
        return ApiResponse.success(list);
    }
}
