package com.cyksj.web.controller.manage.information;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.Jsons;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.GoodsDonMapper;
import com.cyksj.mapper.InformationClickUserRecordMapper;
import com.cyksj.mapper.OrderDonMapper;
import com.cyksj.model.entity.*;
import com.cyksj.model.views.InformationView;
import com.cyksj.redis.RedisService;
import com.cyksj.service.information.InformationCategoryService;
import com.cyksj.service.information.InformationService;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapBuilder;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author zwhui
 * @date 2023/10/12 14:41
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/manage/information")
public class CmsInformationController {
    private final InformationService informationService;

    private final BeanSearcher beanSearcher;

    private final HttpServletRequest request;

    private final InformationCategoryService informationCategoryService;

    private final GoodsDonMapper goodsDonMapper;

    private final RedisService redisService;

    private final InformationClickUserRecordMapper informationClickUserRecordMapper;

    private final OrderDonMapper orderDonMapper;

    /**
     * 保存文章
     */
    @PostMapping("/post")
    public Result<String> saveInformation(@RequestBody Information information) {
        informationService.save(information);
        Set<String> keys = redisService.keys(RedisService.key.INFORMATION_KEY.getName() + "*");
        redisService.del(keys.toArray(String[]::new));
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 修改文章
     */
    @PutMapping("/put")
    public Result<String> updateInformation(@RequestBody Information information) {
        if (information.getId() == null) {
            throw BusinessRuntimeException.getInstance("请指定要修改的文章");
        }
        informationService.updateById(information);
        Set<String> keys = redisService.keys(RedisService.key.INFORMATION_KEY.getName() + "*");
        redisService.del(keys.toArray(String[]::new));
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }


    /**
     * 文章排序
     */
    @PutMapping("/sorted")
    public Result<String> sortedInformation(@RequestBody Information information) {
        if (information.getId() == null) {
            throw BusinessRuntimeException.getInstance("请指定要排序的文章");
        }
        Integer sorted = information.getSorted();
        if (sorted != null && sorted >= 0) {
            Information byId = informationService.getById(information.getId());
            if (byId != null && byId.getSorted() != sorted) {
                byId.setSorted(sorted);
                informationService.updateById(byId);
                Set<String> keys = redisService.keys(RedisService.key.INFORMATION_KEY.getName() + "*");
                redisService.del(keys.toArray(String[]::new));
            }
        }
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }


    /**
     * 获取文章
     */
    @GetMapping("/get")
    public Result<SearchResult<InformationView>> getInformation(Long category) {
        MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
        if (category != null) {
            builder.put("ct", String.format(" and JSON_CONTAINS(i.category_ids,'\"%s\"')", category));
        }
        SearchResult<InformationView> list = beanSearcher.search(InformationView.class, builder.build());
        list.getDataList().forEach(data -> {
            try {
                List<Long> goodsIds = Jsons.parseList(data.getGoodsIds(), Long.class);
                data.setGoodsTitles(goodsDonMapper.selectList(Wrappers.lambdaQuery(GoodsDon.class)
                        .select(GoodsDon::getTitle)
                        .in(GoodsDon::getId, goodsIds)
                        .eq(GoodsDon::getStatus, true)
                        .eq(GoodsDon::getDeleted,true)).stream().map(GoodsDon::getTitle).collect(Collectors.toList()));
                List<Long> categoryIds = Jsons.parseList(data.getCategoryIds(), Long.class);
                data.setCategoryNames(informationCategoryService.list(Wrappers.lambdaQuery(InformationCategory.class)
                        .select(InformationCategory::getName)
                        .in(InformationCategory::getId,categoryIds)).stream().map(InformationCategory::getName).collect(Collectors.toList()));
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
        return GatewayResponse.SUCCESS.newBuilder().toResult(list);
    }

    /**
     * 修改文章状态
     */
    @PutMapping("/update/status")
    public Result<String> updateStatus(@RequestBody Information information) {
        if (information.getId() == null) {
            throw BusinessRuntimeException.getInstance("请指定要修改的文章");
        }
        informationService.updateById(information);
        Set<String> keys = redisService.keys(RedisService.key.INFORMATION_KEY.getName() + "*");
        redisService.del(keys.toArray(String[]::new));
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 删除文章
     */
    @DeleteMapping("/del/{id}")
    public Result<String> delById(@PathVariable Long id) {
        Information byId = informationService.getById(id);
        if (byId == null) {
            return GatewayResponse.SUCCESS.newBuilder().toResult();
        }
        byId.setDeleted(false);
        informationService.updateById(byId);
        Set<String> keys = redisService.keys(RedisService.key.INFORMATION_KEY.getName() + "*");
        redisService.del(keys.toArray(String[]::new));
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }


    /**
     * 保存文章类型
     */
    @PostMapping("/post/category")
    public Result<String> saveInformationCategory(@RequestBody List<InformationCategory> informationCategorys) {
        log.info("保存文章类型 categorys:{}",informationCategorys);
        informationCategoryService.saveBatch(informationCategorys);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 修改文章类型
     */
    @PutMapping("/put/category")
    public Result<String> updateInformationCategory(@RequestBody List<InformationCategory> informationCategorys) {
        informationCategoryService.updateBatchById(informationCategorys);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

    /**
     * 获取文章类型
     */
    @GetMapping("/get/category")
    public Result<List<InformationCategory>> getInformationCategory() {
        return GatewayResponse.SUCCESS.newBuilder().toResult(informationCategoryService.list(Wrappers.lambdaQuery(InformationCategory.class).orderByAsc(InformationCategory::getSortBy)));
    }

    /**
     * 删除文章类型
     */
    @DeleteMapping("/del/category/{id}")
    public Result<String> delCategoryById(@PathVariable Long id) {
        int count = informationService.count(Wrappers.lambdaQuery(Information.class).apply("JSON_CONTAINS(category_ids,'\"" + id + "\"')").eq(Information::getDeleted, true));
        if (count > 0){
            throw BusinessRuntimeException.getInstance("该类型下存在文章,无法删除");
        }
        informationCategoryService.removeById(id);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }

}
