/**
 * Copyright
 * All right reserved.
 * 项目名称:
 * 创建日期:2022/3/9
 */
package org.springblade.modules.business.notice.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.constant.BusinessConstant;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.oss.model.BladeFile;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tenant.annotation.TenantDS;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.ConcurrentDateFormat;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.business.notice.dto.NoticeDTO;
import org.springblade.modules.business.notice.entity.NoticeAttachEntity;
import org.springblade.modules.business.notice.entity.NoticeEntity;
import org.springblade.modules.business.notice.entity.NoticeViewEntity;
import org.springblade.modules.business.notice.service.INoticeAttachService;
import org.springblade.modules.business.notice.service.INoticeService;
import org.springblade.modules.business.notice.service.INoticeViewService;
import org.springblade.modules.business.notice.vo.NoticeAttachVO;
import org.springblade.modules.business.notice.vo.NoticeVO;
import org.springblade.modules.business.notice.wrapper.NoticeWrapper;
import org.springblade.modules.resource.builder.oss.OssBuilder;
import org.springblade.modules.resource.entity.Attach;
import org.springblade.modules.resource.service.IAttachService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/***
 * Date:2022-03-08
 * Title:通知公告控制器
 * Description：对本文件的详细描述，原则上不能少于30字
 * @author admin
 * @mender：（文件的修改者，文件创建者之外的人）
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@TenantDS
@Slf4j
@RestController
@RequestMapping("galaxy-business/notice")
@AllArgsConstructor
@ApiSort(2)
@Api(value = "通知公告", tags = "通知公告")
public class NoticeController extends BladeController {

	private final INoticeService noticeService;
	private final INoticeViewService noticeViewService;
	private final INoticeAttachService noticeAttachService;
	private final IAttachService attachService;
	private final OssBuilder ossBuilder;

	@PostMapping("/test")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入notice")
	public R update(@RequestBody Map<String, Object> data) {
		log.info(data.toString());
		return R.success("ok");
	}

	/**
	 * 列表
	 */
	@GetMapping("/list")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "title", value = "公告标题", paramType = "query", dataType = "string")
	})
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入notice")
	public R<List<NoticeVO>> list(@ApiIgnore NoticeDTO notice) {
		BladeUser user = AuthUtil.getUser();
		notice.setCreateDept(Func.toLong(user.getDeptId()));
		if (BusinessConstant.ROLE_SYS_ADMIN.equals(user.getRoleName())) {
			notice.setCategory(0);
		} else if (BusinessConstant.ROLE_ORG_ADMIN.equals(user.getRoleName())) {
			//盟市查看本部门通知，以及自治区公开的通知
			notice.setCategory(1);
		} else if (BusinessConstant.ROLE_COMPANY_ADMIN.equals(user.getRoleName()) || BusinessConstant.ROLE_COMPANY_SERVICE_PERSON.equals(user.getRoleName())) {
			//运维公司查看本部门通知，以及盟市公开的通知
			notice.setCategory(2);
		}
		List<NoticeVO> pages = noticeService.selectList(notice);
		for (NoticeVO vo:pages){
			NoticeWrapper.build().entityVO(vo);
		}
		return R.data(pages);
	}

	/**
	 * 多表联合查询自定义分页
	 */
	@GetMapping("/page")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "title", value = "公告标题", paramType = "query", dataType = "string")
	})
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入实体类NoticeDTO")
	public R<IPage<NoticeVO>> page(@ApiIgnore NoticeDTO notice, Query query) {
		BladeUser user = AuthUtil.getUser();
		notice.setCreateDept(Func.toLong(user.getDeptId()));
		if (BusinessConstant.ROLE_SYS_ADMIN.equals(user.getRoleName())) {
			notice.setCategory(0);
		} else if (BusinessConstant.ROLE_ORG_ADMIN.equals(user.getRoleName())) {
			//盟市查看本部门通知，以及自治区公开的通知
			notice.setCategory(1);
		} else if (BusinessConstant.ROLE_COMPANY_ADMIN.equals(user.getRoleName()) || BusinessConstant.ROLE_COMPANY_SERVICE_PERSON.equals(user.getRoleName())) {
			//运维公司查看本部门通知，以及盟市公开的通知
			notice.setCategory(2);
		}
		IPage<NoticeVO> pages = noticeService.selectPage(Condition.getPage(query), notice);
		List<NoticeVO> list = pages.getRecords();
		for (NoticeVO vo:list){
			NoticeWrapper.build().entityVO(vo);
		}
		return R.data(pages);
	}

	@GetMapping("/attach/page")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "groupId", value = "公告ID", paramType = "query", dataType = "long"),
	})
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入notice")
	public R<IPage<NoticeAttachVO>> attachPage(@ApiIgnore NoticeAttachEntity notice, Query query) {
		IPage<NoticeAttachVO> pages = noticeAttachService.selectPage(Condition.getPage(query), notice);
		return R.data(pages);
	}

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入notice")
	public R<NoticeVO> detail(NoticeDTO noticeEntity) {
		if (null == noticeEntity.getId()){
			return R.fail("参数错误!");
		}
		NoticeEntity detail = noticeService.getById(noticeEntity.getId());
		return R.data(NoticeWrapper.build().entityVO(detail));
	}

	/**
	 * 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入notice")
	public R save(@RequestBody NoticeDTO noticeEntity) {
		BladeUser user = AuthUtil.getUser();
		if (BusinessConstant.ROLE_SYS_ADMIN.equals(user.getRoleName())) {
			noticeEntity.setCategory(0);
		} else if (BusinessConstant.ROLE_ORG_ADMIN.equals(user.getRoleName())) {
			//盟市查看本部门通知，以及自治区公开的通知
			noticeEntity.setCategory(1);
		} else if (BusinessConstant.ROLE_COMPANY_ADMIN.equals(user.getRoleName()) || BusinessConstant.ROLE_COMPANY_SERVICE_PERSON.equals(user.getRoleName())) {
			//运维公司查看本部门通知，以及盟市公开的通知
			noticeEntity.setCategory(2);
			noticeEntity.setPublicState(0);
		}
		if (noticeService.save(noticeEntity)) {
			if (noticeEntity.getAttach() != null && noticeEntity.getAttach().size() > 0) {
				for (Map<String, Object> att : noticeEntity.getAttach()) {
					Attach attach = new Attach();
					attach.setName((String) att.get("url"));
					attach.setOriginalName((String) att.get("name"));
					attachService.save(attach);
					NoticeAttachEntity attachEntity = new NoticeAttachEntity();
					attachEntity.setAttachId(attach.getId());
					attachEntity.setGroupId(noticeEntity.getId());
					noticeAttachService.save(attachEntity);
				}
			}
		}
		return R.status(true);
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入notice")
	public R update(@RequestBody NoticeEntity noticeEntity) {
		return R.status(noticeService.updateById(noticeEntity));
	}


	@PostMapping("/view")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "查阅")
	public R userView() {
		BladeUser user = AuthUtil.getUser();
		LambdaQueryWrapper<NoticeViewEntity> wrapper = Wrappers.<NoticeViewEntity>query().lambda();
		wrapper.eq(NoticeViewEntity::getCreateUser, user.getUserId());
		wrapper.eq(NoticeViewEntity::getIsDeleted, 0);
		NoticeViewEntity entity = noticeViewService.getOne(wrapper);
		if (null != entity) {
			entity.setViewTime(new Date());
		} else {
			entity = new NoticeViewEntity();
			entity.setViewTime(new Date());
		}
		noticeViewService.saveOrUpdate(entity);
		return R.success("OK");
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入notice")
	public R submit(@RequestBody NoticeEntity noticeEntity) {
		return R.status(noticeService.saveOrUpdate(noticeEntity));
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入notice")
	public R remove(@ApiParam(value = "主键集合") @RequestParam String ids) {
		BladeUser user = AuthUtil.getUser();
		List<Long> list =Func.toLongList(ids);
		for(Long id : list){
			NoticeEntity noticeEntity=noticeService.getById(id);
			if (noticeEntity.getCreateDept() != Func.toLong(user.getDeptId())){
				return R.fail("只支持删除本部门创建的通知公告信息！");
			}
		}
		boolean temp = noticeService.deleteLogic(Func.toLongList(ids));
		return R.status(temp);
	}

	/**
	 * 查询最新的数据
	 */
	@GetMapping("/last/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页")
	public R<List<NoticeVO>> lastList(@RequestParam String limit) {
		BladeUser user = AuthUtil.getUser();
		NoticeDTO noticeDTO = new NoticeDTO();
		noticeDTO.setCreateDept(Func.toLong(user.getDeptId()));
		if (BusinessConstant.ROLE_SYS_ADMIN.equals(user.getRoleName())) {
			noticeDTO.setCategory(0);
		} else if (BusinessConstant.ROLE_ORG_ADMIN.equals(user.getRoleName())) {
			//盟市查看本部门通知，以及自治区公开的通知
			noticeDTO.setCategory(1);
		} else if (BusinessConstant.ROLE_COMPANY_ADMIN.equals(user.getRoleName()) || BusinessConstant.ROLE_COMPANY_SERVICE_PERSON.equals(user.getRoleName())) {
			//运维公司查看本部门通知，以及盟市公开的通知
			noticeDTO.setCategory(2);
		}
		List<NoticeVO> pages = noticeService.selectList(noticeDTO);
		if (Func.toLong(limit)>pages.size()){
			for (NoticeVO vo:pages){
				NoticeWrapper.build().entityVO(vo);
			}
			return R.data(pages);
		}else{
			List<NoticeVO> list = new LinkedList<>();
			for(int i=0;i<Func.toInt(limit);i++){
				NoticeVO entity=pages.get(i);
				list.add(entity);
				NoticeWrapper.build().entityVO(entity);
			}
			return R.data(list);
		}
	}

	/**
	 * 查询最新的数据
	 */
	@GetMapping("/today/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "当天通知公告")
	public R<List<NoticeVO>> todayList() {
		BladeUser user = AuthUtil.getUser();
		NoticeDTO noticeDTO = new NoticeDTO();
		if (BusinessConstant.ROLE_SYS_ADMIN.equals(user.getRoleName())) {
			noticeDTO.setCategory(0);
		} else if (BusinessConstant.ROLE_ORG_ADMIN.equals(user.getRoleName())) {
			//盟市查看本部门通知，以及自治区公开的通知
			noticeDTO.setCategory(1);
		} else if (BusinessConstant.ROLE_COMPANY_ADMIN.equals(user.getRoleName()) || BusinessConstant.ROLE_COMPANY_SERVICE_PERSON.equals(user.getRoleName())) {
			//运维公司查看本部门通知，以及盟市公开的通知
			noticeDTO.setCategory(2);

		}
		Date date = new Date();
		String dt = Func.formatDateTime(date);
		noticeDTO.setViewDate(Func.parse(dt, ConcurrentDateFormat.of("yyyy-MM-dd")));
		List<NoticeVO> pages = noticeService.selectList(noticeDTO);
		for (NoticeVO vo:pages){
			NoticeWrapper.build().entityVO(vo);
		}
		return R.data(pages);
	}

	@ApiLog("附件上传")
	@PostMapping(value = "/putFile")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "附件上传", notes = "")
	public R putFile(MultipartFile file) {
		BladeFile bladeFile = ossBuilder.template().putFile(file);
//		Attach attach = new Attach();
//		attach.setName(bladeFile.getName());
//		attach.setAttachSize(file.getSize());
//		attach.setDomainUrl(bladeFile.getDomain());
//		String  name = bladeFile.getOriginalName();
//		String[] nameArr = name.split("[.]");
//		attach.setExtension(nameArr[1]);
//		attach.setLink(bladeFile.getLink());
//		attach.setOriginalName(bladeFile.getOriginalName());
//		attachService.save(attach);
//		bladeFile.setAttachId(attach.getId());
		return R.data(bladeFile);
	}
}
