package com.jeequan.jeepay.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.db.entity.MchInfo;
import com.jeequan.jeepay.db.entity.SysAdvertConfig;
import com.jeequan.jeepay.service.mapper.SysAdvertConfigMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * <p>
 * 系统广告配置表 服务实现类
 * </p>
 *
 * @author [mybatis plus generator]
 * @since 2023-02-20
 */
@Service
public class SysAdvertConfigService extends ServiceImpl<SysAdvertConfigMapper, SysAdvertConfig> {

    @Autowired private MchInfoService mchInfoService;

    /**
     * @author: xiaoyu
     * @date: 2023/2/20 11:17
     * @describe: 新增广告配置
     */
    @Transactional
    public void addConfig(String infoIds, SysAdvertConfig record) {

        // 广告图片排序
        if (SysAdvertConfig.ADVERT_TYPE_AFTER != record.getAdvertType() && StringUtils.isNotEmpty(record.getAppContent())) {
            JSONArray array = JSONArray.parseArray(record.getAppContent());
            // 启动页广告默认为轮播
            if (record.getAppPlace() != null && record.getAppPlace() == SysAdvertConfig.APP_PLACE_OPEN) {
                record.setAppPlaceType(SysAdvertConfig.APP_PLACE_TYPE_CHANGE);
            }
            if (CollectionUtil.isNotEmpty(array)) {
                // 如果排序sort为空跳过轮播排序
                JSONObject arrayParams0 = JSONObject.parseObject(array.get(0).toString());
                if (StringUtils.isNotEmpty(arrayParams0.getString("sort"))) {
                    array.sort(Comparator.comparing(obj -> ((JSONObject) obj).getString("sort")));
                    record.setAppContent(array.toJSONString());
                }

                // 预览图保存
                JSONObject firstParam = (JSONObject) array.get(0);
                record.setImgUrl(firstParam.getString("imgUrl"));
                record.setLinkUrl(firstParam.getString("linkUrl"));
            }
        }

        // 更新商户已发布状态的广告为关闭 // 商户刷脸设备保存
        if (record.getAdvertType() == SysAdvertConfig.ADVERT_TYPE_FACE && StringUtils.isNotEmpty(infoIds)) {
            String[] split = infoIds.split(",");
            List<String> infoList = Arrays.asList(split);
            for (String infoId:infoList) {
                if (StringUtils.isEmpty(record.getAgentNo())) {
                    MchInfo mchInfo = mchInfoService.getById(infoId);
                    if (mchInfo != null) {
                        record.setAgentNo(mchInfo.getAgentNo());
                    }else {
                        throw new BizException("商户信息不存在");
                    }
                }
                record.setMchNo(infoId);

                // 如果状态为立即发布，检查其配置的已开启广告，设置为关闭
                if (record.getReleaseState() == CS.YES) {
                    SysAdvertConfig advertConfig = new SysAdvertConfig();
                    advertConfig.setReleaseState(CS.NO);
                    update(advertConfig, SysAdvertConfig.gw()
                            .in(SysAdvertConfig::getMchNo, infoList)
                            .eq(SysAdvertConfig::getAdvertType, record.getAdvertType())
                    );
                }
                save(record);
            }
        } else {
            // 更新全部商户已开启为关闭
            // 如果状态为立即发布，检查其配置的已开启广告，设置为关闭
            if (record.getReleaseState() == CS.YES) {
                SysAdvertConfig advertConfig = new SysAdvertConfig();
                advertConfig.setReleaseState(CS.NO);
                LambdaQueryWrapper<SysAdvertConfig> wrapper = SysAdvertConfig.gw()
                        .eq(SysAdvertConfig::getAdvertType, record.getAdvertType())
                        .eq(record.getAppPlace() != null, SysAdvertConfig::getAppPlace, record.getAppPlace())
                        .eq(record.getAppPlaceType() != null, SysAdvertConfig::getAppPlaceType, record.getAppPlaceType())
                        .isNull(SysAdvertConfig::getMchNo);

                if (StringUtils.isNotEmpty(record.getAgentNo())) {
                    wrapper.eq(StringUtils.isNotEmpty(record.getAgentNo()), SysAdvertConfig::getAgentNo, record.getAgentNo());
                }else {
                    wrapper.isNull(SysAdvertConfig::getAgentNo);
                }
                update(advertConfig, wrapper);
            }
            save(record);
        }
    }

    @Transactional
    public void removeConfig(List<String> advertIdList, String infoNo, String infoType) {
        if (StringUtils.isNotEmpty(infoType) && infoType.equals(CS.SYS_ROLE_TYPE.MCH)) {
            for (String advertId:advertIdList) {
                SysAdvertConfig config = getById(advertId);
                if (config == null || !config.getMchNo().equals(infoNo)) {
                    throw new BizException("删除记录权限异常，advertId" + advertId + "不属于当前商户配置");
                }
                removeById(advertId);
            }
        }else if (StringUtils.isNotEmpty(infoType) && infoType.equals(CS.SYS_ROLE_TYPE.AGENT)) {
            for (String advertId:advertIdList) {
                SysAdvertConfig config = getById(advertId);
                if (config == null || !config.getAgentNo().equals(infoNo)) {
                    throw new BizException("删除记录权限异常，advertId" + advertId + "不属于当前代理配置");
                }
                removeById(advertId);
            }
        }else {
            removeByIds(advertIdList);
        }
    }

    @Transactional
    public void updateAdvert(SysAdvertConfig record) {

        // 图片排序
        if (StringUtils.isNotEmpty(record.getAppContent())) {
            JSONArray array = JSONArray.parseArray(record.getAppContent());
            if (CollectionUtil.isNotEmpty(array)) {
                // 如果排序sort为空跳过轮播排序
                JSONObject arrayParams0 = JSONObject.parseObject(array.get(0).toString());
                if (StringUtils.isNotEmpty(arrayParams0.getString("sort"))) {
                    array.sort(Comparator.comparing(obj -> ((JSONObject) obj).getString("sort")));
                    record.setAppContent(array.toJSONString());
                }

                // 启动页广告默认为轮播
                if (record.getAppPlace() != null && record.getAppPlace() == SysAdvertConfig.APP_PLACE_OPEN) {
                    record.setAppPlaceType(SysAdvertConfig.APP_PLACE_TYPE_CHANGE);
                }
                // 预览图保存
                JSONObject firstParam = (JSONObject) array.get(0);
                record.setImgUrl(firstParam.getString("imgUrl"));
                record.setLinkUrl(firstParam.getString("linkUrl"));
            }
        }
        // 若状态为立即发布，修改其他同类型广告关闭状态 即同类型仅可开启一个
        if (record.getReleaseState() == CS.YES) {
            SysAdvertConfig dbConfig = getById(record.getAdvertId());

            SysAdvertConfig advertConfig = new SysAdvertConfig();
            advertConfig.setReleaseState(CS.NO);

            LambdaQueryWrapper<SysAdvertConfig> wrapper = SysAdvertConfig.gw();
            wrapper.eq(dbConfig.getAppPlace() != null, SysAdvertConfig::getAppPlace, dbConfig.getAppPlace());
            wrapper.eq(StringUtils.isNotEmpty(dbConfig.getMchNo()), SysAdvertConfig::getMchNo, dbConfig.getMchNo());
            if (StringUtils.isEmpty(dbConfig.getMchNo())) {
                wrapper.isNull(SysAdvertConfig::getMchNo);
            }
//            wrapper.eq(dbConfig.getAppPlaceType() != null, SysAdvertConfig::getAppPlaceType, dbConfig.getAppPlaceType());
            wrapper.eq(SysAdvertConfig::getAdvertType, dbConfig.getAdvertType());

            // 更新关闭其他同类型开启状态
            update(advertConfig, wrapper);
        }
        updateById(record);
    }
}
