package com.kym.admin.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.kym.common.R;
import com.kym.entity.FaultRecord;
import com.kym.entity.FaultSubscriber;
import com.kym.service.FaultRecordService;
import com.kym.service.FaultSubscriberService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 故障通知订阅管理
 *
 * @author skyline
 */
@Slf4j
@RestController
@RequestMapping("/faultSubscriber")
public class FaultSubscriberController {

    private final FaultSubscriberService faultSubscriberService;
    private final FaultRecordService faultRecordService;
    private final WxMpService wxMpService;

    public FaultSubscriberController(FaultSubscriberService faultSubscriberService,
                                      FaultRecordService faultRecordService,
                                      WxMpService wxMpService) {
        this.faultSubscriberService = faultSubscriberService;
        this.faultRecordService = faultRecordService;
        this.wxMpService = wxMpService;
    }

    /**
     * 获取站点的订阅者列表
     */
    @SaCheckPermission("faultSubscriber.list")
    @GetMapping("/list")
    R<?> list(@RequestParam String stationId) {
        var list = faultSubscriberService.lambdaQuery()
                .eq(FaultSubscriber::getStationId, stationId)
                .eq(FaultSubscriber::getStatus, FaultSubscriber.STATUS_已订阅)
                .orderByDesc(FaultSubscriber::getSubscribeTime)
                .list();
        var stationName = com.kym.service.cache.KymCache.INSTANCE.getStationNameById(stationId);
        list.forEach(s -> s.setStationName(stationName != null ? stationName : stationId));
        return R.success(list);
    }

    /**
     * 管理员手动解绑订阅者
     */
    @SaCheckPermission("faultSubscriber.delete")
    @PostMapping("/unsubscribe")
    R<?> unsubscribe(@RequestBody Map<String, String> params) {
        var openid = params.get("openid");
        var stationId = params.get("stationId");
        faultSubscriberService.unsubscribe(openid, stationId);
        return R.success();
    }

    /**
     * 生成站点故障通知绑定二维码（公众号带参临时二维码）
     * scene_str = stationId, 有效期30天
     */
    @SaCheckPermission("faultSubscriber.qrcode")
    @PostMapping("/generateQrcode")
    R<?> generateQrcode(@RequestBody Map<String, String> params) throws WxErrorException {
        var stationId = params.get("stationId");
        // 生成带scene_str的临时二维码，有效期30天 (最大)
        var ticket = wxMpService.getQrcodeService().qrCodeCreateTmpTicket(stationId, 2592000);
        var url = wxMpService.getQrcodeService().qrCodePictureUrl(ticket.getTicket());
        return R.success(Map.of("ticket", ticket.getTicket(), "url", url, "stationId", stationId));
    }

    /**
     * 查询故障记录列表
     */
    @SaCheckPermission("faultRecord.list")
    @GetMapping("/faultRecords")
    R<?> faultRecords(@RequestParam(required = false) String stationId,
                       @RequestParam(required = false) String faultType,
                       @RequestParam(required = false) Integer isRecovered) {
        var query = faultRecordService.lambdaQuery();
        if (stationId != null && !stationId.isEmpty()) {
            query.eq(FaultRecord::getStationId, stationId);
        }
        if (faultType != null && !faultType.isEmpty()) {
            query.eq(FaultRecord::getFaultType, faultType);
        }
        if (isRecovered != null) {
            query.eq(FaultRecord::getIsRecovered, isRecovered);
        }
        var list = query.orderByDesc(FaultRecord::getFaultTime).list();
        return R.success(list);
    }
}
