/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.desk.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import org.springblade.bank.cardswallow.entity.CardSwallow;
import org.springblade.bank.checklist.vo.ChecklistVO;
import org.springblade.bank.goodsuse.entity.GoodsUse;
import org.springblade.bank.keypwd.entity.KeyPwd;
import org.springblade.bank.message.entity.Message;
import org.springblade.bank.postchange.entity.PostChange;
import org.springblade.bank.returns.entity.Returns;
import org.springblade.bank.sealhandover.entity.SealHandover;
import org.springblade.common.utils.hangxin.HangxinUtil;
import org.springblade.common.utils.hangxin.bean.HangxinResultBean;
import org.springblade.core.datascope.annotation.DataAuth;
import org.springblade.core.datascope.enums.DataScopeEnum;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.desk.entity.Notice;
import org.springblade.modules.desk.mapper.NoticeMapper;
import org.springblade.modules.desk.service.INoticeService;
import org.springblade.modules.desk.vo.NoticeVO;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.entity.Role;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IDictService;
import org.springblade.modules.system.service.IRoleService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 服务实现类
 *
 * @author Chill
 */
@Service
@AllArgsConstructor
public class NoticeServiceImpl extends BaseServiceImpl<NoticeMapper, Notice> implements INoticeService {

	private final IUserService userService;
	private final IDictService dictService;
	private final IDeptService deptService;
	private final IRoleService roleService;

	private HangxinUtil hangxinUtil;

	@Override
	public IPage<NoticeVO> selectNoticePage(IPage<NoticeVO> page, NoticeVO notice) {
		// 若不使用mybatis-plus自带的分页方法，则不会自动带入tenantId，所以我们需要自行注入
		notice.setTenantId(AuthUtil.getTenantId());
		return page.setRecords(baseMapper.selectNoticePage(page, notice));
	}

	@Override
	public IPage<NoticeVO> selectMyNoticePage(IPage<NoticeVO> page, NoticeVO notice) {
		notice.setTenantId(AuthUtil.getTenantId());
		return page.setRecords(baseMapper.selectMyNoticePage(page, notice));
	}

	@Override
	public List<Notice> selectMyNoticeAll() {
		NoticeVO notice = new NoticeVO();
		notice.setTenantId(AuthUtil.getTenantId());
		notice.setCurrentUserId(AuthUtil.getUserId());
		notice.setHadRead(0);
		return baseMapper.selectMyNoticePage(notice);
	}

	@Override
	public boolean sendNotice(Notice notice) {
		notice.setType("0"); //系統
		if (StringUtil.isBlank(notice.getTargetIds())){
			List<String> deptIds = Func.toStrList(notice.getDeptId());
			List<String> roleIds = Func.toStrList(notice.getRoleId());
			List<User> userList = userService.getUsersByDeptIdsRoleIds(deptIds, roleIds);
			List<Long> userIdList = userList.stream().map(user -> user.getId()).collect(Collectors.toList());
			String join = StringUtil.join(userIdList);
			notice.setTargetIds(join);
		}
		return save(notice);
	}

	@Override
	public boolean sendKeyPwdNotice(KeyPwd keyPwd, boolean isEdit, boolean isComplete) {
		//有關XXX(分類+種類+鎖匙/密碼)的交接登記已於X年X月X日完成；交出人﹕XXX；接收人﹕XXX
		String categoryName = getCategoryName(keyPwd);
		String now = DateUtil.formatDate(DateUtil.now());
		String title = "";
		if (isEdit){
			title = "更正：";
		}
		String HandoverName = keyPwd.getHandoverPersonName() != null ? keyPwd.getHandoverPersonName() : "上級單位";
		String ReceiverName = keyPwd.getReceiverName() != null ? keyPwd.getReceiverName() : "上級單位";

		if (isComplete){
			title += "有關（" + categoryName + "）的交接登記已於" + now + "完成；交出人：" + HandoverName + "；接收人：" + ReceiverName;
		}else{
			title += HandoverName + "提交了" + "有關 （" + categoryName + "） 的交接登記" + "，請登入系統進行確認";
		}
		User user1 = userService.getUserByEhr(keyPwd.getHandoverPersonNo());
		User user2 = userService.getUserByEhr(keyPwd.getReceiverNo());

		List<Long> targetList = new ArrayList<>();
		if (user1 != null){
			targetList.add(user1.getId());
		}
		if (user2 != null){
			targetList.add(user2.getId());
		}

		Notice notice = new Notice();
		notice.setTitle(title);
		notice.setBusinessType("keypwd");
		notice.setTargetIds(StringUtil.join(targetList));
		return sendNotice(notice);
	}

	@Override
	public boolean sendCardSwallowNotice(CardSwallow cardSwallow, boolean isEdit) {
		String title = "";
		if (isEdit){
			title = "更正：";
		}
		title += "營運部已發佈新消息，請查閱";
		Dept dept = deptService.getByOrgNo(cardSwallow.getSendOrgNo());

		Notice notice = new Notice();
		notice.setTitle(title);
		notice.setBusinessType("cardswallow");
		notice.setDeptId(dept.getId()+"");
		notice.setRoleId(null);
		return sendNotice(notice);
	}

	@Override
	public boolean sendReturnsNotice(Returns returns, boolean isEdit) {
		String title = "";
		if (isEdit){
			title = "更正：";
		}
		title += "營運部已發佈新消息，請查閱";
		Dept dept = deptService.getByOrgNo(returns.getSubOrgNo());

		Notice notice = new Notice();
		notice.setTitle(title);
		notice.setBusinessType("returns");
		notice.setDeptId(dept.getId()+"");
		notice.setRoleId(null);
		return sendNotice(notice);
	}

	@Override
	public boolean sendMessageNotice(Message message, boolean isEdit) {
		String title = "";
		if (isEdit){
			title = "更正：";
		}
		title += "營運部已發佈新消息，請查閱";
		Notice notice = new Notice();
		notice.setTitle(title);
		notice.setBusinessType("message");
		notice.setDeptId(message.getDeptId());
		notice.setRoleId(message.getRoleId());
		notice.setTargetIds(message.getTargetIds());
		return sendNotice(notice);
	}

	@Override
	public boolean sendSealNotice(SealHandover sealHandover, boolean isEdit, boolean isComplete) {
		//有關XXX(印章種類+印章編號)的交接登記已於X年X月X日完成；交出人﹕XXX；接收人﹕XXX
		String seal_type = dictService.getValue("seal_type", sealHandover.getSealType());
		String now = DateUtil.formatDate(DateUtil.now());
		User user1 = userService.getUserByEhr(sealHandover.getHandoverPersonNo());
		User user2 = userService.getUserByEhr(sealHandover.getReceiverNo());
		List<Long> userList = new ArrayList<>();
		if (user1 != null){
			userList.add(user1.getId());
		}
		if (user2 != null){
			userList.add(user2.getId());
		}

		String title = "";
		if (isEdit){
			title = "更正：";
		}
		if (isComplete){
			title += "有關 （" + seal_type + sealHandover.getSealNo() + "） 的交接登記已於" + now + "完成；交出人：" + sealHandover.getHandoverPersonName() + "；接收人：" + sealHandover.getReceiverName();
		}else{
			title += sealHandover.getHandoverPersonName() + "提交了" + "有關 （" + seal_type + sealHandover.getSealNo() + "） 的交接登記" + "，請登入系統進行確認";
		}
		Notice notice = new Notice();
		notice.setTitle(title);
		notice.setBusinessType("sealhandover");
		notice.setTargetIds(StringUtil.join(userList));
		return sendNotice(notice);
	}

	@Override
	public boolean sendPostChangeNotice(PostChange postChange, boolean isEdit) {
		Dept dept = deptService.getByOrgNo(postChange.getOrgNo());
		String title = "";
		if (isEdit){
			title = "更正：";
		}
		title += dept.getDeptName() + "機構已提交網點出納主管及專管員崗位變更記錄表，請登陸系統查詢";

		Notice notice = new Notice();
		notice.setTitle(title);
		notice.setBusinessType("postchange");
		notice.setTargetIds(postChange.getPersonId()+"");
		return sendNotice(notice);
	}

	@Override
	public boolean sendGoodsUseNotice(GoodsUse goodsUse, boolean isEdit) {
		//用戶1指派XXX請登入系統進行確認
		String title = "";
		if (isEdit){
			title = "更正：";
		}
		title += goodsUse.getFillingName() + "提交了使用及出入庫登記表，請登入系統進行確認";

		Notice notice = new Notice();
		notice.setTitle(title);
		notice.setBusinessType("goodsuse");
		notice.setTargetIds(goodsUse.getPersonId()+"");
		return sendNotice(notice);
	}

	@Override
	public boolean sendChecklistNotice(String cycle, Dept dept) {
		List<String> deptIds = new ArrayList<>();
		Dept parentDept = deptService.getById(dept.getParentId());
		if (parentDept.getOrgNo().startsWith("999")){
			deptIds.add(parentDept.getId() + "");
		}
		deptIds.add(dept.getId() + "");
		List<Role> roleList = roleService.getRolesByAlias("manager");
		List<String> roleIds = roleList.stream().map(role -> role.getId()+"").collect(Collectors.toList());
		List<User> users = userService.getUsersByDeptIdsRoleIds(deptIds, roleIds);
		List<String> userIds = users.stream().map(user -> user.getId() + "").collect(Collectors.toList());
		List<String> userEhrs = users.stream().map(user -> user.getEhr() + "").collect(Collectors.toList());
		List<String> userNames = users.stream().map(user -> user.getName() + "").collect(Collectors.toList());
		if (users.size() > 0){
			System.out.println(dept.getDeptName() + ":" + StringUtil.join(userNames));
		}

		String checkType = "每月";
		if (cycle.equals("day")){
			checkType = "每日";
		}else if (cycle.equals("week")){
			checkType = "每週";
		}

		String title = dept.getDeptName() + "尚未完成" + checkType + "核對工作";
		Notice notice = new Notice();
		notice.setTitle(title);
		notice.setBusinessType("checklist");
		notice.setDeptId(dept.getId() + "");
		notice.setRoleId(StringUtil.join(roleIds));
		notice.setTargetIds(StringUtil.join(userIds));

		// 發送行信通知
		HangxinResultBean hangxinResultBean = hangxinUtil.sendMsg(userEhrs, "提示進度", title);
		System.out.println(JSONUtil.toJsonStr(hangxinResultBean));
		return sendNotice(notice);
//		return true;
	}

	private String getCategoryName(KeyPwd keyPwd){
		List<String> categoryStrList = new ArrayList<>();
		String[] categorys = keyPwd.getCategory().split(",");
		for (int i = 0; i < categorys.length; i++) {
			String category = categorys[i];
			String value = dictService.getValue("key_type", category);
			String[] split = category.split("_");
			String key_type = dictService.getValue("key_type", split[0] + "_" + split[1] + "_" + split[2]);
			categoryStrList.add(key_type + "-" + value);
		}
		return StringUtil.join(categoryStrList, " | ");

		/*String category = keyPwd.getCategory();
		String value = dictService.getValue("key_type", category);
		String[] split = category.split("_");
		String key_type = dictService.getValue("key_type", split[0] + "_" + split[1] + "_" + split[2]);
		return key_type + "-" + value;*/
	}


}
