package com.bs.df.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
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.DfProductArticle;
import com.bs.df.domain.DfProductPoster;
import com.bs.df.utils.HtmlUtils;
import com.bs.system.mapper.SysUserMapper;
import com.bs.system.service.ISysUserService;
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.DfProductMoment;
import com.bs.df.service.IDfProductMomentService;
import javax.annotation.Resource;

/**
 * 产品朋友圈Controller
 *
 * @author bs
 * @date 2024-04-06
 */
@Api(tags = "产品朋友圈")
@RestController
@RequestMapping("/moment/moment")
public class DfProductMomentController extends BaseController {
    @Resource
    private IDfProductMomentService dfProductMomentService;
    @Resource
    private ICmAttachService cmAttachService;
    @Resource
    private ISysUserService userService;
    @Autowired
    private SysUserMapper sysUserMapper;
    /**
     * 分页查询产品朋友圈列表
     */
    @ApiOperation("分页查询产品朋友圈列表")
    @GetMapping("/pageList")
    public TableDataInfo pageList(DfProductMoment dfProductMoment) {
        SysUser sysUser = sysUserMapper.selectById(getUserId());
        startPage();
        String reviewStatus = sysUser.getReviewStatus();
        if ("1".equals(reviewStatus)) {
            return null;
        }
        LambdaQueryWrapper<DfProductMoment> queryWrapper = new LambdaQueryWrapper();
        if (Validator.isEmpty(dfProductMoment.getOrderByColumn())) {
            queryWrapper.orderByDesc(DfProductMoment::getCreateTime);
        }
        condition(queryWrapper,dfProductMoment);
        boolean admin = SecurityUtils.isAdmin(SecurityUtils.getUserId());
        if (!admin) {
            if (!sysUser.getDeptId().equals(-1L)) {
                if ("-99".equals(dfProductMoment.getStatus())) {
                } else {
                    SysUser byId = userService.getById(SecurityUtils.getUserId());
                    if ("jj".equals(byId.getUserType()) || "kh".equals(byId.getUserType())) {
                        queryWrapper.eq(DfProductMoment::getStatus, "1");
                    }
                }
            }
        }
        List<DfProductMoment> list = dfProductMomentService.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 (DfProductMoment moment : list) {
            moment.setMomentContent(HtmlUtils.stripHtmlTags(moment.getMomentContent()));
            String id = moment.getId();
            List<CmAttach> matchingAttachments = attachMap.get(String.valueOf(id));
            if (matchingAttachments != null) {
                moment.setFiles(matchingAttachments);
            }
        }
        return getDataTable(list);
    }

    /**
     * 查询产品朋友圈列表
     */
    @ApiOperation("查询产品朋友圈列表")
    @GetMapping("/list")
    public AjaxResult list(DfProductMoment dfProductMoment) {
        LambdaQueryWrapper<DfProductMoment> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,dfProductMoment);
        List<DfProductMoment> list = dfProductMomentService.list(queryWrapper);
        return success(list);
    }

    /**
     * 导出产品朋友圈列表
     */
    @ApiOperation("导出产品朋友圈列表")
    @Log(title = "产品朋友圈导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DfProductMoment dfProductMoment) {
        LambdaQueryWrapper<DfProductMoment> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,dfProductMoment);
        List<DfProductMoment> list = dfProductMomentService.list(queryWrapper);
        for (DfProductMoment moment : list) {
            moment.setMomentContent(HtmlUtils.stripHtmlTags(moment.getMomentContent()));
        }
        ExcelUtil<DfProductMoment> util = new ExcelUtil<DfProductMoment>(DfProductMoment. class);
        util.exportExcel(response, list, "产品朋友圈数据");
    }

    /**
     * 获取产品朋友圈详细信息
     */
    @ApiOperation("获取产品朋友圈详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        DfProductMoment byId = dfProductMomentService.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 DfProductMoment dfProductMoment) {
        return toAjax(dfProductMomentService.save(dfProductMoment));
    }

    /**
     * 修改产品朋友圈
     */
    @ApiOperation("修改产品朋友圈")
    @Log(title = "产品朋友圈修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DfProductMoment dfProductMoment) {
        return toAjax(dfProductMomentService.updateById(dfProductMoment));
    }

    /**
     * 修改产品朋友圈状态
     */
    @ApiOperation("修改产品朋友圈状态")
    @Log(title = "修改产品朋友圈状态", businessType = BusinessType.DELETE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody DfProductMoment dfProductMoment) {
        String[] ids = dfProductMoment.getIds();
        String status = dfProductMoment.getStatus();
        List<DfProductMoment> dfProductMoments = new ArrayList<>();
        for (String id : ids) {
            DfProductMoment dfProductMomentNew = new DfProductMoment();
            dfProductMomentNew.setId(id);
            dfProductMomentNew.setStatus(status);
            dfProductMoments.add(dfProductMomentNew);
        }
        return toAjax(dfProductMomentService.updateBatchById(dfProductMoments));
    }

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

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


        //朋友圈id
        if(Validator.isNotEmpty(dfProductMoment.getId())){
            queryWrapper.eq(DfProductMoment::getId,dfProductMoment.getId());
        }

        //朋友圈分类0产品朋友圈1经纪朋友圈
        if(Validator.isNotEmpty(dfProductMoment.getMomentType())){
            queryWrapper.eq(DfProductMoment::getMomentType,dfProductMoment.getMomentType());
        }

        //朋友圈类型
        if(Validator.isNotEmpty(dfProductMoment.getMomentKind())){
            queryWrapper.eq(DfProductMoment::getMomentKind,dfProductMoment.getMomentKind());
        }

        //朋友圈标题
        if(Validator.isNotEmpty(dfProductMoment.getMomentTitle())){
            queryWrapper.eq(DfProductMoment::getMomentTitle,dfProductMoment.getMomentTitle());
        }

        //朋友圈正文
        if(Validator.isNotEmpty(dfProductMoment.getMomentContent())){
            queryWrapper.eq(DfProductMoment::getMomentContent,dfProductMoment.getMomentContent());
        }

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

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

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

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

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

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

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

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

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

        }

}
