package com.yc.ship.module.miniapplet.controller.admin.advert;

import com.yc.ship.framework.common.pojo.CommonResult;
import com.yc.ship.framework.common.pojo.PageParam;
import com.yc.ship.framework.common.pojo.PageResult;
import com.yc.ship.framework.common.util.collection.CollectionUtils;
import com.yc.ship.framework.common.util.object.BeanUtils;
import com.yc.ship.framework.excel.core.util.ExcelUtils;
import com.yc.ship.framework.operatelog.core.annotations.OperateLog;
import com.yc.ship.module.miniapplet.controller.admin.advert.vo.AdvertPageReqVO;
import com.yc.ship.module.miniapplet.controller.admin.advert.vo.AdvertRespVO;
import com.yc.ship.module.miniapplet.controller.admin.advert.vo.AdvertSaveReqVO;
import com.yc.ship.module.miniapplet.convert.adsense.AdsenseConvert;
import com.yc.ship.module.miniapplet.dal.dataobject.adsense.AdsenseDO;
import com.yc.ship.module.miniapplet.dal.dataobject.advert.AdvertDO;
import com.yc.ship.module.miniapplet.service.adsense.AdsenseService;
import com.yc.ship.module.miniapplet.service.advert.AdvertService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.yc.ship.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.yc.ship.framework.common.pojo.CommonResult.success;
import static com.yc.ship.framework.common.util.collection.CollectionUtils.convertList;
import static com.yc.ship.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static com.yc.ship.module.miniapplet.enums.ErrorCodeConstants.*;

@Tag(name = "管理后台 - 广告管理")
@RestController
@RequestMapping("/applet/advert")
@Validated
public class AdvertController {

    @Resource
    private AdsenseService adsenseService;

    @Resource
    private AdvertService advertService;

    @PostMapping("/create")
    @Operation(summary = "创建广告管理")
    @PreAuthorize("@ss.hasPermission('applet:advert:create')")
    public CommonResult<Long> createAdvert(@Valid @RequestBody AdvertSaveReqVO createReqVO) {
//        verifyAdsense(null, createReqVO.getAdsenseId());
        return success(advertService.createAdvert(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新广告管理")
    @PreAuthorize("@ss.hasPermission('applet:advert:update')")
    public CommonResult<Boolean> updateAdvert(@Valid @RequestBody AdvertSaveReqVO updateReqVO) {
//        verifyAdsense(updateReqVO.getId(), updateReqVO.getAdsenseId());
        advertService.updateAdvert(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除广告管理")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('applet:advert:delete')")
    public CommonResult<Boolean> deleteAdvert(@RequestParam("id") Long id) {
        advertService.deleteAdvert(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得广告管理")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('applet:advert:query')")
    public CommonResult<AdvertRespVO> getAdvert(@RequestParam("id") Long id) {
        AdvertDO advert = advertService.getAdvert(id);
        return success(BeanUtils.toBean(advert, AdvertRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得广告管理分页")
    @PreAuthorize("@ss.hasPermission('applet:advert:query')")
    public CommonResult<PageResult<AdvertRespVO>> getAdvertPage(@Valid AdvertPageReqVO pageReqVO) {
        PageResult<AdvertDO> pageResult = advertService.getAdvertPage(pageReqVO);
        List<AdsenseDO> adsenseList = adsenseService.getAdsenseList(convertList(pageResult.getList(), AdvertDO::getAdsenseId));
        Map<Long, AdsenseDO> adsenseMap = CollectionUtils.convertMap(adsenseList, AdsenseDO::getId);
        return success(new PageResult<>(AdsenseConvert.INSTANCE.convertAdvertList(pageResult.getList(), adsenseMap),
                pageResult.getTotal()));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出广告管理 Excel")
    @PreAuthorize("@ss.hasPermission('applet:advert:export')")
    @OperateLog(type = EXPORT,enable = false)
    public void exportAdvertExcel(@Valid AdvertPageReqVO pageReqVO,
                                  HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<AdvertDO> list = advertService.getAdvertPage(pageReqVO).getList();
        List<AdsenseDO> adsenseList = adsenseService.getAdsenseList(convertList(list, AdvertDO::getAdsenseId));
        Map<Long, AdsenseDO> adsenseMap = CollectionUtils.convertMap(adsenseList, AdsenseDO::getId);
        List<AdvertRespVO> respList = AdsenseConvert.INSTANCE.convertAdvertList(list, adsenseMap);
        // 导出 Excel
        ExcelUtils.write(response, "广告管理.xls", "数据", AdvertRespVO.class,
                respList);
    }

    /**
     * 验证广告类型
     *
     * @param adsenseId 目录类型ID
     */
    private void verifyAdsense(Long id, Long adsenseId) {
        AdsenseDO adsenseDO = adsenseService.getAdsense(adsenseId);
        if (adsenseDO == null) {
            throw exception(ADSENSE_NOT_EXISTS);
        }
        Integer type = adsenseDO.getAdsenseType();
        List<AdvertDO> advertList = advertService.getAdvertList(adsenseId);
        if (id != null) {
            // 过滤出 非当前操作的内容ID
            advertList = advertList.stream()
                    .filter(contentDO -> !id.equals(contentDO.getId()))
                    .collect(Collectors.toList());
        }
        switch (type) {
            case 0:
                // 单图片
                if (!advertList.isEmpty()) {
                    throw exception(ADSENSE_TYPE_EXCEED);
                }
                break;
            case 1:
                // 单视频
                if (!advertList.isEmpty()) {
                    throw exception(ADSENSE_TYPE_EXCEED);
                }
                break;
            default:
                // 2图片轮播

        }
    }

}
