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.annotation.Anonymous;
import com.bs.common.core.domain.entity.SysUser;
import com.bs.common.utils.SecurityUtils;
import com.bs.df.domain.*;
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.service.IDfProductArticleService;
import javax.annotation.Resource;

/**
 * 产品文章Controller
 *
 * @author bs
 * @date 2024-04-06
 */
@Api(tags = "产品文章")
@RestController
@RequestMapping("/article/article")
public class DfProductArticleController extends BaseController {
    @Resource
    private IDfProductArticleService dfProductArticleService;
    @Resource
    private ICmAttachService cmAttachService;
    @Resource
    private ISysUserService userService;
    @Autowired
    private SysUserMapper sysUserMapper;
    /**
     * 分页查询产品文章列表
     */
    @ApiOperation("分页查询产品文章列表")
    @GetMapping("/pageList")
    public TableDataInfo pageList(DfProductArticle dfProductArticle) {
        SysUser sysUser = sysUserMapper.selectById(getUserId());
        startPage();
        String reviewStatus = sysUser.getReviewStatus();
        if ("1".equals(reviewStatus)) {
            return null;
        }
        LambdaQueryWrapper<DfProductArticle> queryWrapper = new LambdaQueryWrapper();
        boolean admin = SecurityUtils.isAdmin(SecurityUtils.getUserId());
        if (!admin) {
            if (!sysUser.getDeptId().equals(-1L)) {
                if ("-99".equals(dfProductArticle.getStatus())) {

                } else {
                    SysUser byId = userService.getById(SecurityUtils.getUserId());
                    if ("jj".equals(byId.getUserType()) || "kh".equals(byId.getUserType())) {
                        queryWrapper.eq(DfProductArticle::getStatus, "1");
                    }
                }
            }
        }
        if (Validator.isEmpty(dfProductArticle.getOrderByColumn())) {
            queryWrapper.last("ORDER BY CASE WHEN serial_number IS NULL THEN 1 ELSE 0 END, serial_number ASC");
        }
        condition(queryWrapper,dfProductArticle);
        List<DfProductArticle> list = dfProductArticleService.list(queryWrapper);
        for (DfProductArticle article : list) {
            article.setArticleContent(HtmlUtils.stripHtmlTags(article.getArticleContent()));
        }
        List<CmAttach> attachVo = cmAttachService.list();
        Map<String, List<CmAttach>> attachMap = attachVo.stream()
                .filter(cmAttach -> cmAttach.getFileId() != null)
                .collect(Collectors.groupingBy(CmAttach::getFileId));
        for (DfProductArticle article : list) {
            article.setArticleContent(HtmlUtils.stripHtmlTags(article.getArticleContent()));
            String id = article.getId();
            List<CmAttach> matchingAttachments = attachMap.get(String.valueOf(id));
            if (matchingAttachments != null) {
                article.setFiles(matchingAttachments);
            }
        }
        return getDataTable(list);
    }

    /**
     * 查询产品文章列表
     */
    @ApiOperation("查询产品文章列表")
    @GetMapping("/list")
    public AjaxResult list(DfProductArticle dfProductArticle) {
        LambdaQueryWrapper<DfProductArticle> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,dfProductArticle);
        List<DfProductArticle> list = dfProductArticleService.list(queryWrapper);
        return success(list);
    }

    /**
     * 导出产品文章列表
     */
    @ApiOperation("导出产品文章列表")
    @Log(title = "产品文章导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DfProductArticle dfProductArticle) {
        LambdaQueryWrapper<DfProductArticle> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,dfProductArticle);
        List<DfProductArticle> list = dfProductArticleService.list(queryWrapper);
        for (DfProductArticle article : list) {
            //去除富文本中的HTML标签
            article.setArticleContent(HtmlUtils.stripHtmlTags(article.getArticleContent()));
        }
        ExcelUtil<DfProductArticle> util = new ExcelUtil<DfProductArticle>(DfProductArticle. class);
        util.exportExcel(response, list, "产品文章数据");
    }

    /**
     * 获取产品文章详细信息
     */
    @ApiOperation("获取产品文章详细信息")
    @GetMapping(value = "/{id}")
    @Anonymous
    public AjaxResult getInfo(@PathVariable("id") String id) {
        DfProductArticle byId = dfProductArticleService.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 DfProductArticle dfProductArticle) {
        return toAjax(dfProductArticleService.save(dfProductArticle));
    }

    /**
     * 修改产品文章
     */
    @ApiOperation("修改产品文章")
    @Log(title = "产品文章修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DfProductArticle dfProductArticle) {
        return toAjax(dfProductArticleService.updateById(dfProductArticle));
    }

    /**
     * 修改产品文章状态
     */
    @ApiOperation("修改产品文章状态")
    @Log(title = "修改产品文章状态", businessType = BusinessType.DELETE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody  DfProductArticle dfProductArticle) {
        String[] ids = dfProductArticle.getIds();
        String status = dfProductArticle.getStatus();
        List<DfProductArticle> dfProductArticles = new ArrayList<>();
        for (String id : ids) {
            DfProductArticle dfProductArticlerNew = new DfProductArticle();
            dfProductArticlerNew.setId(id);
            dfProductArticlerNew.setStatus(status);
            dfProductArticles.add(dfProductArticlerNew);
        }
        return toAjax(dfProductArticleService.updateBatchById(dfProductArticles));
    }


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

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


        //文章id
        if(Validator.isNotEmpty(dfProductArticle.getId())){
            queryWrapper.eq(DfProductArticle::getId,dfProductArticle.getId());
        }

        //文章分类0产品文章1经纪文章
        if(Validator.isNotEmpty(dfProductArticle.getArticleType())){
            queryWrapper.eq(DfProductArticle::getArticleType,dfProductArticle.getArticleType());
        }

        //文章类型
        if(Validator.isNotEmpty(dfProductArticle.getArticleKind())){
            queryWrapper.eq(DfProductArticle::getArticleKind,dfProductArticle.getArticleKind());
        }

        //文章标题
        if(Validator.isNotEmpty(dfProductArticle.getArticleTitle())){
            queryWrapper.like(DfProductArticle::getArticleTitle,dfProductArticle.getArticleTitle());
        }

        //发布时间
        if(Validator.isNotEmpty(dfProductArticle.getPublishTime())){
            queryWrapper.eq(DfProductArticle::getPublishTime,dfProductArticle.getPublishTime());
        }

        if(Validator.isNotEmpty(dfProductArticle.getPublishTimeBegin())){
            queryWrapper.ge(DfProductArticle::getPublishTime,dfProductArticle.getPublishTimeBegin());
        }

        if(Validator.isNotEmpty(dfProductArticle.getPublishTimeEnd())){
            queryWrapper.le(DfProductArticle::getPublishTime,dfProductArticle.getPublishTimeEnd());
        }

        //文章正文
        if(Validator.isNotEmpty(dfProductArticle.getArticleContent())){
            queryWrapper.eq(DfProductArticle::getArticleContent,dfProductArticle.getArticleContent());
        }

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

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

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

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

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

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

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

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

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

        }

}
