package com.bs.df.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.bs.cm.domain.CmAttach;
import com.bs.cm.service.ICmAttachService;
import com.bs.common.core.domain.entity.SysUser;
import com.bs.common.utils.SecurityUtils;
import com.bs.df.domain.DfOrder;
import com.bs.df.domain.DfProductArticle;
import com.bs.df.domain.DfProductInfo;
import com.bs.df.service.IDfBrokerService;
import com.bs.df.service.IDfProductInfoService;
import com.bs.system.mapper.SysUserMapper;
import com.bs.system.service.ISysUserService;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.bs.common.annotation.Log;
import com.bs.common.core.controller.BaseController;
import com.bs.common.core.domain.AjaxResult;
import com.bs.common.core.page.TableDataInfo;
import com.bs.common.enums.BusinessType;
import com.bs.common.utils.poi.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.hutool.core.lang.Validator;
import com.bs.df.domain.DfProductPoster;
import com.bs.df.service.IDfProductPosterService;
import javax.annotation.Resource;

/**
 * 产品海报Controller
 *
 * @author bs
 * @date 2024-04-06
 */
@Api(tags = "产品海报")
@RestController
@RequestMapping("/poster/poster")
public class DfProductPosterController extends BaseController {
    @Resource
    private IDfProductPosterService dfProductPosterService;
    @Resource
    private IDfProductInfoService dfProductInfoService;
    @Autowired
    private ICmAttachService cmAttachService;
    @Resource
    private IDfBrokerService dfBrokerService;;
    @Resource
    private ISysUserService userService;
    @Autowired
    private SysUserMapper sysUserMapper;
    /**
     * 分页查询产品海报列表
     */
    @ApiOperation("分页查询产品海报列表")
    @GetMapping("/pageList")
    public TableDataInfo pageList(DfProductPoster dfProductPoster) {
        SysUser sysUser = sysUserMapper.selectById(getUserId());
        String reviewStatus = sysUser.getReviewStatus();
        if ("1".equals(reviewStatus)) {
            return null;
        }
        MPJLambdaWrapper<DfProductPoster> queryWrapper = new MPJLambdaWrapper();
        queryWrapper.selectAll(DfProductPoster.class)
                    .select(DfProductInfo::getProductName)
                    .disableSubLogicDel()
                    .leftJoin(DfProductInfo.class,DfProductInfo::getId,DfProductPoster::getProductId);
        if (Validator.isEmpty(dfProductPoster.getOrderByColumn())) {
            queryWrapper.last("ORDER BY CASE WHEN t.serial_number IS NULL THEN 1 ELSE 0 END, t.serial_number ASC");
        }
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            if (!sysUser.getDeptId().equals(-1L)) {
                if ("-99".equals(dfProductPoster.getStatus())) {
                } else {
                    List<Long> productIdsByBrokerId = dfBrokerService.getProductIdsByBrokerId();
                    List<DfProductPoster> list = dfProductPosterService.list(new LambdaQueryWrapper<DfProductPoster>()
                            .eq(DfProductPoster::getPosterType, "1"));
                    List<Long> productIds = list.stream()
                            .map(DfProductPoster::getProductId)
                            .collect(Collectors.toList());
                    if (productIdsByBrokerId.size() == 0) {
                        productIdsByBrokerId.add(0L);
                    }
                    productIdsByBrokerId.addAll(productIds);
                    queryWrapper.nested(wrapper -> wrapper.in(DfProductPoster::getProductId, productIdsByBrokerId)
                            .or()
                            .isNull(DfProductPoster::getProductId));
                    SysUser byId = userService.getById(SecurityUtils.getUserId());
                    if ("jj".equals(byId.getUserType()) || "kh".equals(byId.getUserType())) {
                        queryWrapper.eq(DfProductPoster::getStatus,"1");
                    }
                }
            }
        }
        conditionByMPJ(queryWrapper,dfProductPoster);
        startPage();
        List<DfProductPoster> list = dfProductPosterService.list(queryWrapper);
        List<CmAttach> attachVo = cmAttachService.list();
        Map<String, List<CmAttach>> attachMap = attachVo.stream()
                .filter(cmAttach -> cmAttach.getFileId() != null)
                .collect(Collectors.groupingBy(CmAttach::getFileId));
        for (DfProductPoster dfProductPosterVo : list) {
            String id = dfProductPosterVo.getId();
            List<CmAttach> matchingAttachments = attachMap.get(String.valueOf(id));
            if (matchingAttachments != null) {
                dfProductPosterVo.setFiles(matchingAttachments);
            }
            if ("1".equals(dfProductPosterVo.getPosterType())) {
                dfProductPosterVo.setProductName(null);
            }
        }
        return getDataTable(list);
    }

    /**
     * 查询产品海报列表
     */
    @ApiOperation("查询产品海报列表")
    @GetMapping("/list")
    public AjaxResult list(DfProductPoster dfProductPoster) {
        LambdaQueryWrapper<DfProductPoster> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,dfProductPoster);
        List<DfProductPoster> list = dfProductPosterService.list(queryWrapper);
        return success(list);
    }

    /**
     * 导出产品海报列表
     */
    @ApiOperation("导出产品海报列表")
    @Log(title = "产品海报导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DfProductPoster dfProductPoster) {
        MPJLambdaWrapper<DfProductPoster> queryWrapper = new MPJLambdaWrapper();
        queryWrapper.selectAll(DfProductPoster.class)
                .select(DfProductInfo::getProductName)
                .disableSubLogicDel()
                .leftJoin(DfProductInfo.class,DfProductInfo::getId,DfProductPoster::getProductId);
        conditionByMPJ(queryWrapper,dfProductPoster);
        List<DfProductPoster> list = dfProductPosterService.list(queryWrapper);
        ExcelUtil<DfProductPoster> util = new ExcelUtil<DfProductPoster>(DfProductPoster. class);
        util.exportExcel(response, list, "产品海报数据");
    }

    /**
     * 获取产品海报详细信息
     */
    @ApiOperation("获取产品海报详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        DfProductPoster byId = dfProductPosterService.getById(id);
        List<CmAttach> attachVo = cmAttachService.list(new LambdaQueryWrapper<CmAttach>().eq(CmAttach::getFileId, id));
        byId.setFiles(attachVo);
        return success(byId);
    }

    /**
     * 新增产品海报
     */
    @ApiOperation("新增产品海报")
    @Log(title = "产品海报新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DfProductPoster dfProductPoster) {
        if ("1".equals(dfProductPoster.getPosterType())) {
            dfProductPoster.setProductId(-1L);
        }
        return toAjax(dfProductPosterService.save(dfProductPoster));
    }

    /**
     * 修改产品海报
     */
    @ApiOperation("修改产品海报")
    @Log(title = "产品海报修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DfProductPoster dfProductPoster) {
        if ("1".equals(dfProductPoster.getPosterType())) {
            dfProductPoster.setProductId(-1L);
        }
        return toAjax(dfProductPosterService.updateById(dfProductPoster));
    }

    /**
     * 修改产品海报状态
     */
    @ApiOperation("修改产品海报状态")
    @Log(title = "修改产品海报状态", businessType = BusinessType.DELETE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody DfProductPoster dfProductPoster) {
        String[] ids = dfProductPoster.getIds();
        String status = dfProductPoster.getStatus();
        List<DfProductPoster> dfProductPosters = new ArrayList<>();
        for (String id : ids) {
            DfProductPoster dfProductPosterNew = new DfProductPoster();
            dfProductPosterNew.setId(id);
            dfProductPosterNew.setStatus(status);
            dfProductPosters.add(dfProductPosterNew);
        }
        return toAjax(dfProductPosterService.updateBatchById(dfProductPosters));
    }

    /**
     * 删除产品海报
     */
    @ApiOperation("删除产品海报")
    @Log(title = "产品海报删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<String> ids) {
        List<DfProductPoster> list = dfProductPosterService.list(new LambdaQueryWrapper<DfProductPoster>().in(DfProductPoster::getId, ids));
        for (DfProductPoster dfProductPoster : list) {
            if ("1".equals(dfProductPoster.getStatus())) {
                return AjaxResult.warn("该海报已经上架，请先下架再删除");
            }
        }
        return toAjax(dfProductPosterService.removeBatchByIds(ids));
    }

    private void conditionByMPJ (MPJLambdaWrapper<DfProductPoster> queryWrapper,DfProductPoster dfProductPoster){


        //海报id
        if(Validator.isNotEmpty(dfProductPoster.getId())){
            queryWrapper.eq(DfProductPoster::getId,dfProductPoster.getId());
        }

        //产品id
        if(Validator.isNotEmpty(dfProductPoster.getProductId())){
            queryWrapper.eq(DfProductPoster::getProductId,dfProductPoster.getProductId());
        }

        //产品名称
        if(Validator.isNotEmpty(dfProductPoster.getProductName())){
            queryWrapper.like(DfProductInfo::getProductName,dfProductPoster.getProductName());
        }

        //海报分类0产品海报1经纪海报
        if(Validator.isNotEmpty(dfProductPoster.getPosterType())){
            queryWrapper.eq(DfProductPoster::getPosterType,dfProductPoster.getPosterType());
        }

        //海报名称
        if(Validator.isNotEmpty(dfProductPoster.getPosterName())){
            queryWrapper.like(DfProductPoster::getPosterName,dfProductPoster.getPosterName());
        }

        //海报标签
        if(Validator.isNotEmpty(dfProductPoster.getPosterTag())){
            queryWrapper.eq(DfProductPoster::getPosterTag,dfProductPoster.getPosterTag());
        }

        //海报图片id
        if(Validator.isNotEmpty(dfProductPoster.getPosterFileId())){
            queryWrapper.eq(DfProductPoster::getPosterFileId,dfProductPoster.getPosterFileId());
        }

        //状态0草稿1上架
        if(Validator.isNotEmpty(dfProductPoster.getStatus())){
            queryWrapper.eq(DfProductPoster::getStatus,dfProductPoster.getStatus());
        }

        //备注
        if(Validator.isNotEmpty(dfProductPoster.getRemark())){
            queryWrapper.eq(DfProductPoster::getRemark,dfProductPoster.getRemark());
        }

        //创建部门
        if(Validator.isNotEmpty(dfProductPoster.getCreateDept())){
            queryWrapper.eq(DfProductPoster::getCreateDept,dfProductPoster.getCreateDept());
        }

        //创建人员
        if(Validator.isNotEmpty(dfProductPoster.getCreateBy())){
            queryWrapper.eq(DfProductPoster::getCreateBy,dfProductPoster.getCreateBy());
        }

        //创建时间
        if(Validator.isNotEmpty(dfProductPoster.getCreateTime())){
            queryWrapper.eq(DfProductPoster::getCreateTime,dfProductPoster.getCreateTime());
        }

        //修改人员
        if(Validator.isNotEmpty(dfProductPoster.getUpdateBy())){
            queryWrapper.eq(DfProductPoster::getUpdateBy,dfProductPoster.getUpdateBy());
        }

        //修改时间
        if(Validator.isNotEmpty(dfProductPoster.getUpdateTime())){
            queryWrapper.eq(DfProductPoster::getUpdateTime,dfProductPoster.getUpdateTime());
        }

        //删除标志（0代表存在 2代表删除）
        if(Validator.isNotEmpty(dfProductPoster.getDelFlag())){
            queryWrapper.eq(DfProductPoster::getDelFlag,dfProductPoster.getDelFlag());
        }

        //租户id
        if(Validator.isNotEmpty(dfProductPoster.getTenantId())){
            queryWrapper.eq(DfProductPoster::getTenantId,dfProductPoster.getTenantId());
        }

    }

    /**
      * 条件设置
      */
    private void condition (LambdaQueryWrapper<DfProductPoster> queryWrapper,DfProductPoster dfProductPoster){


        //海报id
        if(Validator.isNotEmpty(dfProductPoster.getId())){
            queryWrapper.eq(DfProductPoster::getId,dfProductPoster.getId());
        }

        //产品id
        if(Validator.isNotEmpty(dfProductPoster.getProductId())){
            queryWrapper.eq(DfProductPoster::getProductId,dfProductPoster.getProductId());
        }

        //海报分类0产品海报1经纪海报
        if(Validator.isNotEmpty(dfProductPoster.getPosterType())){
            queryWrapper.eq(DfProductPoster::getPosterType,dfProductPoster.getPosterType());
        }

        //海报名称
        if(Validator.isNotEmpty(dfProductPoster.getPosterName())){
            queryWrapper.eq(DfProductPoster::getPosterName,dfProductPoster.getPosterName());
        }

        //海报标签
        if(Validator.isNotEmpty(dfProductPoster.getPosterTag())){
            queryWrapper.eq(DfProductPoster::getPosterTag,dfProductPoster.getPosterTag());
        }

        //海报图片id
        if(Validator.isNotEmpty(dfProductPoster.getPosterFileId())){
            queryWrapper.eq(DfProductPoster::getPosterFileId,dfProductPoster.getPosterFileId());
        }

        //状态0草稿1上架
        if(Validator.isNotEmpty(dfProductPoster.getStatus())){
            queryWrapper.eq(DfProductPoster::getStatus,dfProductPoster.getStatus());
        }

        //备注
        if(Validator.isNotEmpty(dfProductPoster.getRemark())){
            queryWrapper.eq(DfProductPoster::getRemark,dfProductPoster.getRemark());
        }

        //创建部门
        if(Validator.isNotEmpty(dfProductPoster.getCreateDept())){
            queryWrapper.eq(DfProductPoster::getCreateDept,dfProductPoster.getCreateDept());
        }

        //创建人员
        if(Validator.isNotEmpty(dfProductPoster.getCreateBy())){
            queryWrapper.eq(DfProductPoster::getCreateBy,dfProductPoster.getCreateBy());
        }

        //创建时间
        if(Validator.isNotEmpty(dfProductPoster.getCreateTime())){
            queryWrapper.eq(DfProductPoster::getCreateTime,dfProductPoster.getCreateTime());
        }

        //修改人员
        if(Validator.isNotEmpty(dfProductPoster.getUpdateBy())){
            queryWrapper.eq(DfProductPoster::getUpdateBy,dfProductPoster.getUpdateBy());
        }

        //修改时间
        if(Validator.isNotEmpty(dfProductPoster.getUpdateTime())){
            queryWrapper.eq(DfProductPoster::getUpdateTime,dfProductPoster.getUpdateTime());
        }

        //删除标志（0代表存在 2代表删除）
        if(Validator.isNotEmpty(dfProductPoster.getDelFlag())){
            queryWrapper.eq(DfProductPoster::getDelFlag,dfProductPoster.getDelFlag());
        }

        //租户id
        if(Validator.isNotEmpty(dfProductPoster.getTenantId())){
            queryWrapper.eq(DfProductPoster::getTenantId,dfProductPoster.getTenantId());
        }

        }

}
