
package com.seer.teach.mp.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seer.teach.common.PageListBean;
import com.seer.teach.common.utils.PageConverterUtils;
import com.seer.teach.mp.api.WechatOfficialAccountApi;
import com.seer.teach.mp.admin.controller.req.MpAccountPageReq;
import com.seer.teach.mp.admin.controller.req.MpAccountReq;
import com.seer.teach.mp.admin.controller.resp.AdminMpAccountResp;
import com.seer.teach.mp.admin.convert.AdminMpAccountConvert;
import com.seer.teach.mp.entity.MpAccountEntity;
import com.seer.teach.mp.factory.MpServiceFactory;
import com.seer.teach.mp.service.IMpAccountService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import java.util.List;

@RequiredArgsConstructor
@Slf4j
@Validated
@Service
public class AdminMpAccountService {

    private final IMpAccountService mpAccountService;

    private final WechatOfficialAccountApi wechatOfficialAccountApi;

    @Resource
    @Lazy
    private MpServiceFactory mpServiceFactory;

    public void loadCache() {
        mpServiceFactory.init();
        wechatOfficialAccountApi.initMpAccountCache();
    }

    /**
     * 创建公众号账号
     *
     * @param createReqVO 创建信息
     * @return 公众号账号ID
     */
    public boolean createAccount(@Valid MpAccountReq createReqVO) {
        MpAccountEntity mpAccount = AdminMpAccountConvert.INSTANCE.convertOne(createReqVO);
        boolean result = mpAccountService.save(mpAccount);
        log.info("[createAccount][创建公众号账号成功，结果为:{}]", result);
        loadCache();
        log.info("[createAccount][刷新公众号緩存成功]");
        return result;
    }

    /**
     * 更新公众号账号
     *
     * @param updateReqVO 更新信息
     * @return 是否更新成功
     */
    public Boolean updateAccount(@Valid MpAccountReq updateReqVO) {
        MpAccountEntity mpAccount = AdminMpAccountConvert.INSTANCE.convertOne(updateReqVO);
        boolean updated = mpAccountService.updateById(mpAccount);
        log.info("[updateAccount][更新公众号账号成功，结果为:{}]", updated);
        loadCache();
        log.info("[updateAccount][刷新公众号緩存成功]");
        return updated;
    }

    /**
     * 删除公众号账号
     *
     * @param id 公众号账号ID
     * @return 是否删除成功
     */
    public Boolean deleteAccount(Integer id) {
        boolean removed = mpAccountService.removeById(id);
        log.info("[deleteAccount][删除公众号账号成功，结果为:{}]", removed);
        loadCache();
        log.info("[deleteAccount][刷新公众号緩存成功]");
        return removed;
    }

    /**
     * 获取公众号账号详情
     *
     * @param id 公众号账号ID
     * @return 公众号账号信息
     */
    public AdminMpAccountResp getAccount(Integer id) {
        MpAccountEntity mpAccount = mpAccountService.getById(id);
        return AdminMpAccountConvert.INSTANCE.convertOne(mpAccount);
    }

    /**
     * 分页获取公众号账号列表
     *
     * @param pageReq 分页查询条件
     * @return 公众号账号分页结果
     */
    public PageListBean<AdminMpAccountResp> getAccountPage(MpAccountPageReq pageReq) {
        Page<MpAccountEntity> pageParm = new Page<>(pageReq.getPageNo(), pageReq.getPageSize());
        LambdaQueryWrapper<MpAccountEntity> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(pageReq.getAppId())) {
            wrapper.like(MpAccountEntity::getAppId, pageReq.getAppId());
        }
        if (StringUtils.isNotBlank(pageReq.getName())) {
            wrapper.like(MpAccountEntity::getName, pageReq.getName());
        }
        if (StringUtils.isNotBlank(pageReq.getAccount())) {
            wrapper.like(MpAccountEntity::getAccount, pageReq.getAccount());
        }
        IPage<MpAccountEntity> resultPage = mpAccountService.page(pageParm, wrapper);

        return PageConverterUtils.convertPageListBean(resultPage, AdminMpAccountConvert.INSTANCE::convertRespList);
    }

    /**
     * 获取所有公众号账号列表
     *
     * @return 公众号账号列表
     */
    public List<AdminMpAccountResp> getAccountList() {
        List<MpAccountEntity> accountList = mpAccountService.list();
        return AdminMpAccountConvert.INSTANCE.convertRespList(accountList);
    }

    /**
     * 生成公众号二维码
     *
     * @param id 公众号账号ID
     * @return 是否生成成功
     */
    public Boolean generateAccountQrCode(Integer id,String sceneStr) {
        MpAccountEntity account = mpAccountService.getById(id);
        WxMpService mpService = mpServiceFactory.getRequiredMpService(account.getAppId());
        String qrCodeUrl;
        try {
            WxMpQrCodeTicket qrCodeTicket = mpService.getQrcodeService().qrCodeCreateLastTicket(sceneStr);
            qrCodeUrl = mpService.getQrcodeService().qrCodePictureUrl(qrCodeTicket.getTicket());
        } catch (WxErrorException e) {
            log.error("生成公众号二维码失败", e);
            return false;
        }
        MpAccountEntity updateAccount = new MpAccountEntity();
        updateAccount.setId(id);
        updateAccount.setQrCodeUrl(qrCodeUrl);

        return mpAccountService.updateById(updateAccount);
    }
}