package cn.axzo.msg.center.message.service.impl;

import cn.axzo.msg.center.common.enums.TableIsDeleteEnum;
import cn.axzo.msg.center.common.utils.BizAssertions;
import cn.axzo.msg.center.common.utils.PageHelperUtil;
import cn.axzo.msg.center.dal.CardStyleDao;
import cn.axzo.msg.center.domain.entity.CardStyle;
import cn.axzo.msg.center.message.domain.param.CardStyleSaveOrUpdateParam;
import cn.axzo.msg.center.message.service.CardStyleService;
import cn.axzo.msg.center.service.card.request.CardStylePageRequest;
import cn.axzo.msg.center.service.card.response.CardStyleDetailResponse;
import cn.axzo.msg.center.service.card.response.CardStylePageResponse;
import cn.axzo.msg.center.service.enums.YesOrNo;
import cn.axzo.msg.center.utils.UUIDUtil;
import cn.azxo.framework.common.model.Page;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @author xudawei@axzo.cn
 * @date 2024/12/10
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CardStyleServiceImpl implements CardStyleService {


    private final CardStyleDao cardStyleDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String createCardStyle(CardStyleSaveOrUpdateParam param) {
        log.info("CardStyleServiceImpl#createCardStyle,param:{}", JSON.toJSONString(param));
        String code = UUIDUtil.uuidString();
        CardStyle cardStyle = param.toEntityWhenCreate(code);
        cardStyleDao.save(cardStyle);
        return code;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCardStyle(CardStyleSaveOrUpdateParam param) {
        log.info("CardStyleServiceImpl#updateTemplate,param:{}", JSON.toJSONString(param));
        //1 更新卡片样式
        doUpdateCardStyle(param);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteCardStyle(CardStyleSaveOrUpdateParam param) {
        log.info("CardStyleServiceImpl#delete,param:{}", JSON.toJSONString(param));
        if (Objects.isNull(param) || StringUtils.isBlank(param.getCode())) {
            log.info("code is blank");
            return;
        }
        cardStyleDao.lambdaUpdate()
                .eq(CardStyle::getCode, param.getCode())
                .eq(CardStyle::getIsDelete, TableIsDeleteEnum.NORMAL.value)
                .set(CardStyle::getIsDelete, YesOrNo.NO.getCode())
                .update();
    }

    @Override
    public CardStyleDetailResponse detail(String code) {
        log.info("MessageTemplateV3ServiceImpl#detail,code:{}", code);
        if (StringUtils.isBlank(code)) {
            return null;
        }
        CardStyle cardStyle = cardStyleDao.lambdaQuery()
                .eq(CardStyle::getCode, code)
                .eq(CardStyle::getIsDelete, TableIsDeleteEnum.NORMAL.value)
                .one();
        if (Objects.isNull(cardStyle)) {
            log.info("there is not any cardstyle match the templateCode:[{}]", code);
            return null;
        }

        return convert(cardStyle);
    }

    /**
     * 对象转换
     */
    private CardStyleDetailResponse convert(CardStyle cardStyle) {
        return CardStyleDetailResponse.builder()
                .name(cardStyle.getName())
                .code(cardStyle.getCode())
                .previewImages(cardStyle.getPreviewImages())
                .elementConfigs(cardStyle.getElementConfigs())
                .build();
    }


    @Override
    public Page<CardStylePageResponse> page(CardStylePageRequest request) {
        IPage<CardStyle> result = pageQueryCardStyle(request);
        if (Objects.isNull(result)
                || CollectionUtils.isEmpty(result.getRecords())) {
            return PageHelperUtil.emptyPage(request.getPage(), request.getPageSize());
        }

        List<CardStylePageResponse> responses = BeanUtil.copyToList(result.getRecords(), CardStylePageResponse.class);
        return Page.toPage(request.getPage(), request.getPageSize(), result.getTotal(), responses);
    }

    /**
     * 执行更新
     */
    private void doUpdateCardStyle(CardStyleSaveOrUpdateParam param) {
        boolean updated = cardStyleDao.lambdaUpdate()
                .eq(CardStyle::getCode, param.getCode())
                .eq(CardStyle::getIsDelete, TableIsDeleteEnum.NORMAL.value)
                .set(StringUtils.isNotBlank(param.getName()), CardStyle::getName, param.getName())
                //预览大图
                .set(CollectionUtils.isNotEmpty(param.getPreviewImages()), CardStyle::getPreviewImages, JSON.toJSONString(param.getPreviewImages()))
                //卡片元素配置
                .set(CollectionUtils.isNotEmpty(param.getElementConfigs()), CardStyle::getElementConfigs, JSON.toJSONString(param.getElementConfigs()))
                .update();
        BizAssertions.assertTrue(updated, "卡片样式不存在:", param.getCode());
    }

    private IPage<CardStyle> pageQueryCardStyle(CardStylePageRequest request) {
        IPage<CardStyle> pageRequest = request.toPage();

        return cardStyleDao.lambdaQuery()
                .eq(StringUtils.isNotBlank(request.getCode()), CardStyle::getCode, request.getCode())
                .eq(StringUtils.isNotBlank(request.getName()), CardStyle::getName, request.getName())
                .orderByDesc(CardStyle::getCreateAt)
                .page(pageRequest);
    }

}
