package com.ym.mec.cms.controller;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.cms.controller.queryinfo.NewsInformationQueryInfo;
import com.ym.mec.cms.dal.dao.SysNewsInformationDao;
import com.ym.mec.cms.dal.entity.SysConfig;
import com.ym.mec.cms.dal.entity.SysNewsInformation;
import com.ym.mec.cms.service.SysConfigService;
import com.ym.mec.cms.service.SysNewsInformationService;
import com.ym.mec.cms.service.SysNewsTypeService;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.page.WrapperUtil;
import com.ym.mec.util.collection.MapUtil;
import com.ym.mec.web.WebFeignService;
import com.yonge.log.model.AuditLogAnnotation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("news")
@Api(tags = "资讯服务")
public class NewsController extends BaseController {

    @Autowired
    private SysNewsInformationService sysNewsInformationService;
    @Autowired
    private SysNewsTypeService sysNewsTypeService;
    @Autowired
    private SysNewsInformationDao sysNewsInformationDao;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private WebFeignService webFeignService;
    @Autowired
    private SysConfigService sysConfigService;

    @ApiOperation("查询底部按钮信息")
    @GetMapping(value = "/queryBottomInfo")
    public HttpResponseResult<List<SysNewsInformation>> queryBySubType(String clientName) {
        Optional<String> optional = Optional.ofNullable(clientName);
        optional.orElseThrow(() -> new BizException("clientName不能为空"));
        boolean b = WrapperUtil.checkStr(clientName.toLowerCase(), "student", "teacher");
        Integer subType;
        if (b) {
            // 学生21  老师22
            subType = optional.filter(q -> q.equalsIgnoreCase("student"))
                    .map(q -> 21)
                    .orElse(22);
        } else {
            return failed("参数错误");
        }
        return succeed(sysNewsInformationService.queryBottomInfo(subType));
    }

    @ApiOperation("资讯列表分页查询")
    @GetMapping(value = "/list")
    public Object getList(NewsInformationQueryInfo queryInfo) {
        if (queryInfo.getType() == 6 || queryInfo.getType() == 4) {
            queryInfo.setTenantId(-1);
        }
        String clientId = queryInfo.getClientId();

        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || user.getId() == null) {
            queryInfo.setOrganId(43);
            queryInfo.setExcludeIds(new ArrayList<>());
        } else {
            if (!StringUtils.equalsIgnoreCase("student", clientId)) {
                queryInfo.setOrganIdList(webFeignService.queryOrganIdByUserId(user.getId(), clientId));
            } else {
                queryInfo.setOrganId(user.getOrganId());
            }
        }

        Map<String, Object> params = new HashMap<String, Object>();
        MapUtil.populateMap(params, queryInfo);
        int count = sysNewsInformationDao.queryCount(params);
        if (count == 0) {
            queryInfo.setMemo(null);
        }
        return succeed(sysNewsInformationService.queryPage(queryInfo));
    }

    @ApiOperation("资讯列表分页查询")
    @GetMapping(value = "/queryPage")
    public Object queryPage(NewsInformationQueryInfo queryInfo) {

        if (queryInfo.getType() != null && (queryInfo.getType() == 6 || queryInfo.getType() == 4)) {
            queryInfo.setTenantId(-1);
        }

        Map<String, Object> params = new HashMap<String, Object>();
        MapUtil.populateMap(params, queryInfo);
        int count = sysNewsInformationDao.queryCount(params);
        if (count == 0) {
            queryInfo.setMemo(null);
        }
        return succeed(sysNewsInformationService.queryPage(queryInfo));
    }

    @ApiOperation("资讯类型列表查询")
    @GetMapping(value = "/typeList")
    public Object getTypeList(Integer parentId) {
        return succeed(sysNewsTypeService.queryByParentId(parentId));
    }

    @ApiOperation("资讯列表分页查询")
    @GetMapping(value = "/homeList")
    public Object getHomeList(NewsInformationQueryInfo queryInfo) {
        queryInfo.setRows(10);
        SysUser user = sysUserFeignService.queryUserInfo();
        SysConfig cloudTeacherActiveIds = sysConfigService.findByParamName(SysConfigService.CLOUD_TEACHER_ACTIVE_BANNER_IDS);
        List<Integer> excludeIds = new ArrayList<>();
        if (Objects.nonNull(cloudTeacherActiveIds) && StringUtils.isNotBlank(cloudTeacherActiveIds.getParanValue())) {
            excludeIds = Arrays.stream(cloudTeacherActiveIds.getParanValue().split(",")).map(id -> Integer.valueOf(id)).collect(Collectors.toList());
        }
        if (user == null || user.getId() == null) {
            queryInfo.setOrganId(43);
            queryInfo.setTenantId(1);
            queryInfo.setExcludeIds(excludeIds);
        } else {
            queryInfo.setOrganId(user.getOrganId());
        }
        return succeed(sysNewsInformationService.getHomeList(user, queryInfo));
    }

    @ApiOperation("查询资讯详情")
    @ApiImplicitParam(name = "id", value = "资讯ID编号", required = true, dataType = "Long", paramType = "path")
    @GetMapping(value = "/query")
    public Object query(Long id) {

        return succeed(sysNewsInformationService.queryById(id));
    }

    @ApiOperation("新增资讯")
    @PostMapping(value = "/add", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @AuditLogAnnotation(operateName = "资讯新增", interfaceURL = "news/add")
    @PreAuthorize("@pcs.hasPermissions('news/add')")
    public Object add(SysNewsInformation newsInfo) {

        if (newsInfo.getType() == 6 || newsInfo.getType() == 4) {
            newsInfo.setTenantId(-1);
        }
        if (newsInfo.getContent().length() > 7999) {
            return failed("内容过长");
        }
        return succeed(sysNewsInformationService.insert(newsInfo));
    }

    @ApiOperation("更新资讯")
    @PostMapping(value = "/update", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @AuditLogAnnotation(operateName = "资讯更新", interfaceURL = "news/update")
    @PreAuthorize("@pcs.hasPermissions('news/update')")
    public Object update(SysNewsInformation newsInfo) {
        Date date = new Date();
        newsInfo.setUpdateTime(date);

        SysNewsInformation originNewsInfo = sysNewsInformationService.get(newsInfo.getId());
        if (originNewsInfo == null) {
            return failed("请求参数错误");
        }

        if (newsInfo.getType() == null) {
            newsInfo.setType(originNewsInfo.getType());
        }

        if (newsInfo.getType() == 6 || newsInfo.getType() == 4) {
            newsInfo.setTenantId(-1);
        }
        return succeed(sysNewsInformationService.update(newsInfo));
    }

    @ApiOperation("删除")
    @PostMapping(value = "/del/{id}", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @AuditLogAnnotation(operateName = "资讯删除", interfaceURL = "news/del")
    @PreAuthorize("@pcs.hasPermissions('news/del')")
    public Object add(@PathVariable("id") Long id) {
        return succeed(sysNewsInformationService.deleteWithLogical(id));
    }

	@ApiOperation("查询资讯详情")
	@ApiImplicitParams({@ApiImplicitParam(name = "id", value = "资讯ID编号", required = true, dataType = "Long"),
			@ApiImplicitParam(name = "memo", value = "版本号",  dataType = "String") })
	@GetMapping("/list/tree")
	public Object listWithTree(Integer id, String memo) {
		return succeed(sysNewsTypeService.listWithTree(id,memo));
	}
}
