package com.ycwl.basic.controller.pc;

import com.ycwl.basic.model.pc.broker.entity.BrokerEntity;
import com.ycwl.basic.model.pc.broker.req.BrokerRecordReqQuery;
import com.ycwl.basic.model.pc.broker.req.BrokerReqQuery;
import com.ycwl.basic.model.pc.broker.resp.BrokerRespVO;
import com.ycwl.basic.model.pc.broker.resp.DailySummaryRespVO;
import com.ycwl.basic.service.pc.BrokerRecordService;
import com.ycwl.basic.service.pc.BrokerService;
import com.ycwl.basic.storage.enums.StorageAcl;
import com.ycwl.basic.utils.ApiResponse;
import com.ycwl.basic.utils.WxMpUtil;
import com.ycwl.basic.repository.ScenicRepository;
import com.ycwl.basic.storage.StorageFactory;
import com.ycwl.basic.storage.adapters.IStorageAdapter;
import com.ycwl.basic.model.pc.mp.MpConfigEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

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

/**
 * @Author：longbinbin
 * @Date：2024/12/2 15:50
 */
@RestController
@RequestMapping("/api/broker/v1")
@Api(tags = "推客（推广人）管理")
public class BrokerController {
    @Autowired
    private BrokerService brokerService;

    @Autowired
    private BrokerRecordService brokerRecordService;

    @Autowired
    private ScenicRepository scenicRepository;

    @ApiOperation("分页查询")
    @PostMapping("/page")
    public ApiResponse page(@RequestBody BrokerReqQuery brokerReqQuery){
        return ApiResponse.success(brokerService.pageQuery(brokerReqQuery));
    }

    @ApiOperation("列表查询")
    @PostMapping("/list")
    public ApiResponse list(@RequestBody BrokerReqQuery brokerReqQuery){
        return ApiResponse.success(brokerService.list(brokerReqQuery));
    }

    @ApiOperation("详情查询")
    @GetMapping("/getDetails/{id}")
    public ApiResponse getDetails(@PathVariable("id") Long id){
        return ApiResponse.success(brokerService.getById(id));
    }
    @ApiOperation("新增或修改")
    @PostMapping("/addOrUpdate")
    public ApiResponse addOrUpdate(@RequestBody BrokerEntity broker){
        return ApiResponse.success(brokerService.addOrUpdate(broker));
    }
    @ApiOperation("删除")
    @DeleteMapping("/delete/{id}")
    public ApiResponse delete(@PathVariable("id") Long id){
        return ApiResponse.success(brokerService.delete(id));
    }
    @ApiOperation("修改状态")
    @PutMapping("/updateStatus/{id}")
    public ApiResponse updateStatus(@PathVariable("id") Long id){
        return ApiResponse.success(brokerService.updateStatus(id));
    }

    @ApiOperation("修改状态")
    @PutMapping("/updateBrokerEnable/{id}")
    public ApiResponse updateBrokerEnable(@PathVariable("id") Long id){
        return ApiResponse.success(brokerService.updateBrokerEnable(id));
    }

    @ApiOperation("推客记录分页查询")
    @PostMapping("/record/page")
    public ApiResponse pageRecord(@RequestBody BrokerRecordReqQuery brokerRecordReqQuery) {
        return ApiResponse.success(brokerRecordService.pageQuery(brokerRecordReqQuery));
    }

    @ApiOperation("推客记录列表查询")
    @PostMapping("/record/list")
    public ApiResponse listRecord(@RequestBody BrokerRecordReqQuery brokerRecordReqQuery) {
        return ApiResponse.success(brokerRecordService.list(brokerRecordReqQuery));
    }

    @ApiOperation("推客记录详情查询")
    @GetMapping("/record/getDetails/{id}")
    public ApiResponse getRecordDetails(@PathVariable("id") Long id) {
        return ApiResponse.success(brokerRecordService.getById(id));
    }

    @ApiOperation("根据brokerId和时间范围查询每天的记录数量和orderPrice汇总")
    @GetMapping("/{id}/record/summary")
    public ApiResponse<List<DailySummaryRespVO>> getDailySummaryByBrokerId(
            @PathVariable("id") Long brokerId,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime) {
        return ApiResponse.success(brokerRecordService.getDailySummaryByBrokerId(brokerId, startTime, endTime));
    }

    @ApiOperation("根据景区ID下载小程序二维码")
    @GetMapping("/{id}/QRCode")
    public ApiResponse<String> downloadQrCode(@PathVariable Long id) {
        BrokerRespVO broker = brokerService.getById(id);
        if (broker == null) {
            return ApiResponse.fail("推客不存在");
        }
        MpConfigEntity mpConfig = scenicRepository.getScenicMpConfig(broker.getScenicId());
        if (mpConfig == null) {
            return ApiResponse.fail("小程序配置不存在");
        }
        String appId = mpConfig.getAppId();
        String appSecret = mpConfig.getAppSecret();
        String appState = mpConfig.getState();
        String path = "pages/home/index?scenicId=" + broker.getScenicId() + "&morphId=" + id;
        String filePath = "qr_code_tk_" + 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("生成二维码失败");
        }
    }
}
