package com.jeequan.jeepay.mch.ctrl.merchant;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jeequan.jeepay.core.aop.MethodLog;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.db.entity.MchInfo;
import com.jeequan.jeepay.db.entity.SysAdvertConfig;
import com.jeequan.jeepay.mch.ctrl.CommonCtrl;
import com.jeequan.jeepay.mch.service.MarketAdvertService;
import com.jeequan.jeepay.service.impl.MchInfoService;
import com.jeequan.jeepay.service.impl.SysAdvertConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 广告
 *
 * @author xiaoyu
 *
 * @date 2023/2/21 16:13
 */
@RestController
@RequestMapping("/api/advert")
public class AdvertController extends CommonCtrl {

    @Autowired SysAdvertConfigService advertConfigService;
    @Autowired MchInfoService  mchInfoService;
    @Autowired MarketAdvertService marketAdvertService;

    /** 刷脸设备广告 **/
    @GetMapping("/faceDevice")
    public ApiRes faceDevice() {

        // 商户是否开启并配置刷脸设备广告
        MchInfo mchInfo = mchInfoService.getById(getCurrentMchNo());
        if (mchInfo != null && mchInfo.getAdvertFlag() != null) {
            if (mchInfo.getAdvertFlag() == CS.YES) {
                // 查询配置商户的广告
                LambdaQueryWrapper<SysAdvertConfig> wrapper = SysAdvertConfig.gw();
                wrapper.eq(SysAdvertConfig::getMchNo, getCurrentMchNo());
                wrapper.eq(SysAdvertConfig::getAdvertType, SysAdvertConfig.ADVERT_TYPE_FACE);
                wrapper.eq(SysAdvertConfig::getReleaseState, CS.YES);
                wrapper.orderByDesc(SysAdvertConfig::getCreatedAt);
                List<SysAdvertConfig> list = advertConfigService.list(wrapper);

                // 广告配置不为空
                if (!list.isEmpty()) {
                    return ApiRes.ok(list.get(0));
                }
                return ApiRes.ok();
            }
        }

        // 查询平台全局广告
        LambdaQueryWrapper<SysAdvertConfig> wrapper = SysAdvertConfig.gw();
        wrapper.eq(SysAdvertConfig::getAdvertType, SysAdvertConfig.ADVERT_TYPE_FACE);
        wrapper.eq(SysAdvertConfig::getReleaseState, CS.YES);
        wrapper.isNull(SysAdvertConfig::getMchNo);
        wrapper.orderByDesc(SysAdvertConfig::getCreatedAt);
        List<SysAdvertConfig> listPlat = advertConfigService.list(wrapper);
        if (!listPlat.isEmpty()) {
            return ApiRes.ok(listPlat.get(0));
        }
        return ApiRes.ok();
    }

    /** APP 商户通广告 **/
    @GetMapping("/appAdvert")
    public ApiRes appAdvert() {

        // 广告位置 1-启动页 2-首页 3-我的页
        Byte appPlace = getValByteRequired("appPlace");
        // 查询平台全局广告
        LambdaQueryWrapper<SysAdvertConfig> wrapper = SysAdvertConfig.gw();
        wrapper.eq(SysAdvertConfig::getAdvertType, SysAdvertConfig.ADVERT_TYPE_APP_MCH);
        wrapper.eq(SysAdvertConfig::getAppPlace, appPlace);
        wrapper.eq(SysAdvertConfig::getReleaseState, CS.YES);
        wrapper.orderByAsc(SysAdvertConfig::getAdvertSort);
        wrapper.orderByDesc(SysAdvertConfig::getCreatedAt);
        List<SysAdvertConfig> list = advertConfigService.list(wrapper);
        return ApiRes.ok(list);
    }


    /**
     * @author: xiaoyu
     * @date: 2023/2/20 11:06
     * @describe: 广告配置列表
     */
    @PreAuthorize("hasAnyAuthority('ENT_ADVERT_LIST', 'ENT_ADVERT_VIEW')")
    @GetMapping
    public ApiRes pages() {

        SysAdvertConfig record = getObject(SysAdvertConfig.class);

        LambdaQueryWrapper<SysAdvertConfig> condition = SysAdvertConfig.gw();
        condition.eq(record.getAdvertId() != null, SysAdvertConfig::getAdvertId, record.getAdvertId());
        condition.eq(record.getAppPlaceType() != null, SysAdvertConfig::getAppPlaceType, record.getAppPlaceType());
        condition.eq(record.getReleaseState() != null, SysAdvertConfig::getReleaseState, record.getReleaseState());
        condition.eq(record.getAdvertType() != null, SysAdvertConfig::getAdvertType, record.getAdvertType());
        condition.eq(record.getAppPlace() != null, SysAdvertConfig::getAppPlace, record.getAppPlace());
        condition.like(StringUtils.isNotEmpty(record.getTitle()), SysAdvertConfig::getTitle, record.getTitle());
        condition.eq(SysAdvertConfig::getMchNo, getCurrentMchNo());
        condition.orderByDesc(SysAdvertConfig::getCreatedAt);
        IPage<SysAdvertConfig> pages = advertConfigService.page(getIPage(), condition);

        for (SysAdvertConfig config: pages.getRecords()) {
            if (StringUtils.isNotEmpty(config.getMchNo())) {
                MchInfo mchInfo = mchInfoService.getById(config.getMchNo());
                if (mchInfo != null) {
                    config.addExt("infoName", mchInfo.getMchName());
                }else {
                    config.addExt("infoName", "");
                }
            }
        }

        //返回数据
        return ApiRes.ok(pages);
    }

    /** detail */
    @PreAuthorize("hasAuthority( 'ENT_ADVERT_VIEW' )")
    @RequestMapping(value="/{advertId}", method = RequestMethod.GET)
    public ApiRes getConfigs(@PathVariable("advertId") Long advertId) {

        checkAdvertFlag();

        SysAdvertConfig config = advertConfigService.getOne(
                SysAdvertConfig.gw()
                        .eq(SysAdvertConfig::getAdvertId, advertId)
                        .eq(SysAdvertConfig::getMchNo, getCurrentMchNo())
        );
        return ApiRes.ok(config);
    }

    /**
     * @author: xiaoyu
     * @date: 2023/2/20 11:06
     * @describe: 广告配置修改
     */
    @PreAuthorize("hasAnyAuthority('ENT_ADVERT_EDIT')")
    @MethodLog(remark = "广告配置修改")
    @RequestMapping(value="/{advertId}", method = RequestMethod.PUT)
    public ApiRes update(@PathVariable("advertId") Long advertId) {
        // 校验权限
        SysAdvertConfig config = advertConfigService.getById(advertId);
        if (config != null && !getCurrentMchNo().equals(config.getMchNo())) {
            return ApiRes.fail(ApiCodeEnum.SYS_PERMISSION_ERROR);
        }

        checkAdvertFlag();

        SysAdvertConfig record = getObject(SysAdvertConfig.class);
        record.setAdvertId(advertId);
        if (getReqParamJSON().getByte("state") != null) {
            record.setReleaseState(getReqParamJSON().getByte("state"));
        }

        advertConfigService.updateAdvert(record);
        return ApiRes.ok();
    }

    /**
     * @author: xiaoyu
     * @date: 2023/2/20 11:10
     * @describe: 广告配置新增
     */
    @PreAuthorize("hasAuthority( 'ENT_ADVERT_ADD' )")
    @MethodLog(remark = "广告配置新增")
    @RequestMapping(value="", method = RequestMethod.POST)
    public ApiRes add() {
        checkAdvertFlag();

        SysAdvertConfig record = getObject(SysAdvertConfig.class);
        record.setCreatedUid(getCurrentUser().getSysUserId());
        record.setCreatedBy(getCurrentUser().getSysUser().getRealname());
        advertConfigService.addConfig(getCurrentMchNo(), record);
        return ApiRes.ok();
    }

    /** delete */
    @PreAuthorize("hasAuthority('ENT_ADVERT_DEL')")
    @MethodLog(remark = "广告配置删除")
    @DeleteMapping
    public ApiRes del() {

        checkAdvertFlag();

        String delAdvertIds = getValStringRequired("delAdvertIds");
        List<String> advertIdList = Arrays.stream(delAdvertIds.split(",")).collect(Collectors.toList());
        advertConfigService.removeConfig(advertIdList, getCurrentMchNo(), CS.SYS_ROLE_TYPE.MCH);
        return ApiRes.ok();

    }

    public void checkAdvertFlag() {
        // 商户广告权限校验
        MchInfo mchInfo = mchInfoService.getById(getCurrentMchNo());
        if (mchInfo.getAdvertFlag() == null || mchInfo.getAdvertFlag() != CS.YES) {
            throw new BizException("权限错误，当前用户不支持此操作");
        }
    }

}
