package com.willalp.web.controller.news;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.willalp.app.domain.HsAppHomeData;
import com.willalp.app.domain.vo.AppConfigVo;
import com.willalp.app.service.IHsAppHomeDataService;
import com.willalp.app.service.IHsAppHomeService;
import com.willalp.common.core.controller.BaseController;
import com.willalp.common.core.domain.AjaxResult;
import com.willalp.common.core.redis.RedisCache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author hs
 */
@Api("app配置控制")
@RestController
@RequestMapping("/config")
public class AppHomeConfigController extends BaseController {

    @Resource
    private IHsAppHomeService hsAppHomeService;

    @Resource
    private IHsAppHomeDataService hsAppHomeDataService;

    @Resource
    private RedisCache redisCache;

    /**
     * 根据首页方案ID获取 所有数据
     *
     * @param homeId
     * @return
     */
    @ApiOperation("获取所有首页方案数据")
    @GetMapping("/info")
    public AjaxResult getConfigById(@RequestParam("homeId")
                                    @ApiParam("首页数据父ID") Long homeId) {
        return AjaxResult.success(hsAppHomeDataService.selectAppConfigVo(homeId));
    }

    /**
     * 保存首页方案
     *
     * @return
     */
    @ApiOperation("保存所有首页方案数据")
    @PostMapping("/save")
    public AjaxResult saveConfig(@RequestBody @ApiParam("首页配置") AppConfigVo appConfigVo) {
        return toAjax(hsAppHomeDataService.saveAppConfig(appConfigVo));
    }

    private String orgCode = "G00000007";

    /**
     * 发布首页方案
     *
     * @return
     */
    @ApiOperation("发布首页方案")
    @RequestMapping("/issue")
    public AjaxResult saveConfig(@RequestBody @ApiParam("首页方案ID") HsAppHomeData appHome) {
        if (ObjectUtil.isNotEmpty(appHome)) {
            try {
                HsAppHomeData temporaryColumn = hsAppHomeDataService.getBaseMapper().selectOne(new QueryWrapper<HsAppHomeData>()
                        .eq("home_parent_id", appHome.getHomeContentId()));
                HsAppHomeData appHomeDataTemporary = new HsAppHomeData();
                BeanUtil.copyProperties(appHome, appHomeDataTemporary);
                if (null == temporaryColumn) {
                    appHomeDataTemporary.setHomeContentId(null);
                    appHomeDataTemporary.setHomeParentId(appHome.getHomeContentId());
                    hsAppHomeDataService.save(appHomeDataTemporary);
                } else {
                    String homeContentId = temporaryColumn.getHomeContentId();
                    appHomeDataTemporary.setHomeContentId(homeContentId);
                    appHomeDataTemporary.setHomeParentId(temporaryColumn.getHomeParentId());
                    hsAppHomeDataService.updateById(appHomeDataTemporary);
                }
                JSONObject jsonObject;
                List<HsAppHomeData> cacheList = new ArrayList<>();
                long count = 0;
                QueryWrapper<HsAppHomeData> queryWrapper = new QueryWrapper<HsAppHomeData>()
                        .notIn("home_parent_id", 0L);
                try {
                    jsonObject = redisCache.getCacheObject(orgCode + "_HomeData");
                    cacheList = (List<HsAppHomeData>) jsonObject.get("data");
                    count = hsAppHomeDataService.getBaseMapper().selectCount(queryWrapper);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (count != 0 && cacheList.size() == count && ObjectUtil.isNotEmpty(cacheList)) {
                    for (int i = 0; i < cacheList.size(); i++) {
                        if (appHome.getHomeContentId().equals(cacheList.get(i).getHomeParentId())) {
                            appHome.setHomeContentId(cacheList.get(i).getHomeContentId());
                            appHome.setHomeParentId(cacheList.get(i).getHomeParentId());
                            cacheList.remove(i);
                            cacheList.add(appHome);
                        }
                    }
                    cacheList = cacheList.stream().sorted(Comparator.comparing(HsAppHomeData::getUpdateTime).reversed()).collect(Collectors.toList());
                    JSONObject jsonObject1 = new JSONObject();
                    jsonObject1.put("data", cacheList);
                    redisCache.setCacheObject(orgCode + "_HomeData", jsonObject1);
                } else {
                    List<HsAppHomeData> homeIssues = hsAppHomeDataService.getBaseMapper().selectList(queryWrapper);
                    if (0 == homeIssues.size()) {
                        return AjaxResult.error("没有要发布的资讯");
                    }
                    JSONObject jsonObject1 = new JSONObject();
                    jsonObject1.put("data", homeIssues);
                    redisCache.setCacheObject(orgCode + "_HomeData", jsonObject1);
                }
                return AjaxResult.success();
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error();
            }
        }
        return AjaxResult.error();
    }

}
