package com.yh.saas.plugin.configuration.announcement.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alipay.sofa.runtime.api.annotation.SofaReference;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.winsea.svc.base.base.entity.CommonCompany;
import com.winsea.svc.base.base.entity.CommonDepartment;
import com.winsea.svc.base.base.entity.CommonStaff;
import com.winsea.svc.base.base.entity.CommonStaffRole;
import com.winsea.svc.base.base.service.ICommonCompanyService;
import com.winsea.svc.base.base.service.ICommonDepartmentService;
import com.winsea.svc.base.base.service.ICommonRoleService;
import com.winsea.svc.base.base.service.ICommonStaffRoleService;
import com.winsea.svc.base.base.service.ICommonStaffService;
import com.winsea.svc.base.base.util.tree.TreeWrapper;
import com.winsea.svc.base.security.util.AuthSecurityUtils;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.common.support.util.StringUtils;
import com.yh.saas.common.support.util.uniqueness.UniquenessChecker;
import com.yh.saas.plugin.configuration.announcement.entity.AnnoIssueInfo;
import com.yh.saas.plugin.configuration.announcement.entity.AnnoReadUserInfo;
import com.yh.saas.plugin.configuration.announcement.entity.Recipient;
import com.yh.saas.plugin.configuration.announcement.entity.view.DeptStaffTreeView;
import com.yh.saas.plugin.configuration.announcement.mapper.AnnoIssueInfoMapper;
import com.yh.saas.plugin.configuration.announcement.service.IAnnoIssueInfoService;
import com.yh.saas.plugin.configuration.announcement.service.IAnnoReadUserInfoService;
import com.yh.saas.plugin.configuration.exception.EnterpriseErrorCodeEnums;

/**
 * <p>
 * 公告模块 - 公告详情 - 业务实现类
 * </p>
 *
 * @Auther ZhangMingYu
 * @since 2019年8月14日15:59:36
 */
@Service
public class AnnoIssueInfoServiceImpl extends ServiceImpl<AnnoIssueInfoMapper, AnnoIssueInfo>
		implements IAnnoIssueInfoService {

	@Autowired
	private AnnoIssueInfoMapper annoIssueInfoMapper;

	@Autowired
	private IAnnoReadUserInfoService readUserInfoService;

	@SofaReference
	private ICommonStaffService staffService;

	@SofaReference
	private ICommonDepartmentService departmentService;

	@SofaReference
	private ICommonCompanyService companyService;

	@SofaReference
	private ICommonRoleService roleService;

	@SofaReference
	private ICommonStaffRoleService staffRoleService;

	private static final Integer number = 3;

	/**
	 * 公告 待发布 待接收一览
	 *
	 * @param annoIssueInfo 查询条件
	 * @return
	 */
	@Override
	public Page<AnnoIssueInfo> queryPage(AnnoIssueInfo annoIssueInfo) {
		// 当前登录人主要角色
		CommonStaffRole staffRole = staffRoleService.getMajorRole(AuthSecurityUtils.getCurrentUserInfo().getUserId());
		annoIssueInfo.setCompId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
		annoIssueInfo.setLoginDeptId(roleService.selectById(staffRole.getRoleId()).getDeptId());
		annoIssueInfo.setLoginDeptId(roleService.selectById(staffRole.getRoleId()).getDeptId());
		Page<AnnoIssueInfo> annoIssueInfoPage = annoIssueInfo.getQueryPage();
		List<AnnoIssueInfo> announcementVos = annoIssueInfoMapper.queryPage(annoIssueInfo, annoIssueInfoPage);

		return annoIssueInfoPage.setRecords(announcementVos);
	}

	/**
	 * 首页获取公告 前三条
	 *
	 * @return
	 */
	@Override
	public List<AnnoIssueInfo> queryList() {
		String loginUserId = AuthSecurityUtils.getCurrentUserInfo().getUserId();

		AnnoIssueInfo annoIssueInfo = new AnnoIssueInfo();
		annoIssueInfo.setLoginUserId(loginUserId);
		annoIssueInfo.setOrderColunm("aii." + AnnoIssueInfo.CommonQueryFields.CREATE_DATE);
		annoIssueInfo.setCurrentPage(1);
		annoIssueInfo.setPageSize(number);
		annoIssueInfo.setOrder("desc");

		return annoIssueInfoMapper.queryList(annoIssueInfo, annoIssueInfo.getQueryPage());
	}

	/**
	 * 查询详情
	 *
	 * @param annoIssueInfo 查询条件
	 * @return
	 */
	@Override
	public AnnoIssueInfo queryInfo(AnnoIssueInfo annoIssueInfo) {
		AnnoIssueInfo issueInfo = selectById(annoIssueInfo);
		List<CommonDepartment> departmentList = new ArrayList<>();
		if (StringUtils.isEmpty(issueInfo.getReleaseRange())) {
			return issueInfo;
		}
		List<Recipient> recipients = JSON.parseArray(issueInfo.getReleaseRange(), Recipient.class);
		for (Recipient recipient : recipients) {
			for (String userIds : recipient.getUserIds()) {
//                CommonStaff staff = staffService.selectOne(new EntityWrapper<CommonStaff>().eq(CommonStaff.QueryFields.STAFF_ID, userIds));
				CommonDepartment department = departmentService.selectOne(
						new EntityWrapper<CommonDepartment>().eq(CommonDepartment.QueryFields.DEPT_ID, userIds));

				if (null != department) {
					department
							.setUnderCompName(
									companyService
											.selectOne(new EntityWrapper<CommonCompany>()
													.eq(CommonCompany.QueryFields.COMP_ID, department.getUnderCompId()))
											.getCompName());
					departmentList.add(department);
				}
			}
		}

		issueInfo.setDepartments(departmentList);

//        AnnoReadUserInfo annoReadUserInfo = new AnnoReadUserInfo();
//        annoReadUserInfo.setReadUserId(AuthSecurityUtils.getCurrentUserInfo().getUserId());
//        annoReadUserInfo.setAnnouncementId(annoIssueInfo.getId());
//        readUserInfoService.haveSee(annoReadUserInfo);
		return issueInfo;
	}

	@Override
	@Transactional
	public boolean create(AnnoIssueInfo annoIssueInfo) {
		annoIssueInfo.setId(IdGenerator.generateUUID());
		annoIssueInfo.setCompId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
		annoIssueInfo.setIssueDate(new Date());

		// 获取用户名称
//        CommonStaff commonStaff = staffService.getInfo(annoIssueInfo.getIssueUserId());
//        annoIssueInfo.setIssueUserName(commonStaff.getStaffName());

		List<Recipient> recipients = annoIssueInfo.getRecipients();
		annoIssueInfo.setReleaseRange(JSON.toJSONString(recipients));

		if (!StringUtils.isEmpty(annoIssueInfo.getIsIssue()) && "1".equals(annoIssueInfo.getIsIssue())) {
			release(annoIssueInfo);
		}

		return annoIssueInfo.insert();
	}

	@Override
	@Transactional
	public void chagneInfo(AnnoIssueInfo annoIssueInfo) {
		AnnoIssueInfo annoIssue = selectById(annoIssueInfo.getId());
		annoIssueInfo.setIssueDate(new Date());
		if (!annoIssue.getIssueUserId().equals(AuthSecurityUtils.getCurrentUserInfo().getUserId())) {
			throw new UniquenessChecker.UniquenessException(
					EnterpriseErrorCodeEnums.ANNOUNCEMENT_NOT_ISSUE_USER_ID.getValue(),
					EnterpriseErrorCodeEnums.ANNOUNCEMENT_NOT_ISSUE_USER_ID.getDesc());
		}
		annoIssueInfo.setCompId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
		List<Recipient> recipients = annoIssueInfo.getRecipients();
		annoIssueInfo.setReleaseRange(JSON.toJSONString(recipients));

		if (!StringUtils.isEmpty(annoIssueInfo.getIsIssue()) && "1".equals(annoIssueInfo.getIsIssue())) {
			release(annoIssueInfo);
		}

		updateById(annoIssueInfo);
	}

	@Override
	@Transactional
	public void remove(AnnoIssueInfo annoIssueInfo) {
		AnnoIssueInfo annoIssue = selectById(annoIssueInfo.getId());
		if (!annoIssue.getIssueUserId().equals(AuthSecurityUtils.getCurrentUserInfo().getUserId())) {
			throw new UniquenessChecker.UniquenessException(
					EnterpriseErrorCodeEnums.ANNOUNCEMENT_NOT_ISSUE_USER_ID.getValue(),
					EnterpriseErrorCodeEnums.ANNOUNCEMENT_NOT_ISSUE_USER_ID.getDesc());
		}
		annoIssueInfoMapper.remove(annoIssueInfo.getId());
		readUserInfoService.remove(annoIssueInfo.getId());
	}

	/**
	 * 发布
	 */
	private void release(AnnoIssueInfo annoIssueInfo) {
		List<Recipient> recipients = annoIssueInfo.getRecipients();
		List<AnnoReadUserInfo> annoReadUserInfos = new ArrayList<>();

		if (!CollectionUtils.isEmpty(recipients)) {
			recipients.forEach(recipient -> recipient.getUserIds().forEach(userId -> {
				if (!userId.equals(annoIssueInfo.getIssueUserId())) {
					AnnoReadUserInfo annoReadUserInfo = new AnnoReadUserInfo();
					annoReadUserInfo.setAnnouncementId(annoIssueInfo.getId());
					annoReadUserInfo.setReadUserId(userId);
					annoReadUserInfos.add(annoReadUserInfo);
				}
			}));

			readUserInfoService.createAll(annoReadUserInfos);
		}
	}

	/**
	 * 获取公司下组织架构
	 */
	@Override
	public List getCompDepaStaff() {
		String compId = AuthSecurityUtils.getCurrentUserInfo().getCompId();

		List<DeptStaffTreeView> deptStaffTreeViews = new ArrayList<>();
		// 获取公司下所有部门

		CommonCompany company = companyService
				.selectOne(new EntityWrapper<CommonCompany>().eq(CommonCompany.QueryFields.COMP_ID, compId));

		DeptStaffTreeView deptStaffTreeView1 = new DeptStaffTreeView();
		deptStaffTreeView1.setId(company.getCompId());
		deptStaffTreeView1.setParentId("-1");
		deptStaffTreeView1.setName(company.getCompName());
		deptStaffTreeView1.setChildren(new ArrayList<>());
		deptStaffTreeViews.add(deptStaffTreeView1);

		List<CommonDepartment> departments = departmentService
				.selectList(new EntityWrapper<CommonDepartment>().eq(CommonDepartment.QueryFields.COMP_ID, compId));
		departments.forEach(department -> {
			DeptStaffTreeView deptStaffTreeView = new DeptStaffTreeView();
			deptStaffTreeView.setId(department.getDeptId());
			if (StringUtils.isEmpty(department.getParentDeptId())) {
				deptStaffTreeView.setParentId(department.getCompId());
			} else {
				deptStaffTreeView.setParentId(department.getParentDeptId());
			}
			deptStaffTreeView.setName(department.getDeptName());
			deptStaffTreeView.setChildren(new ArrayList<>());
			deptStaffTreeView.setStaffs(staffService.selectList(
					new EntityWrapper<CommonStaff>().eq(CommonStaff.QueryFields.DEPT_ID, department.getDeptId())));
			deptStaffTreeViews.add(deptStaffTreeView);
		});

		TreeWrapper<DeptStaffTreeView> deptStaffTreeViewTreeWrapper = new TreeWrapper<>(deptStaffTreeViews);

		return deptStaffTreeViewTreeWrapper.polymerize();
	}

	/**
	 * 获取租户下公司部门
	 */
	@Override
	public List<DeptStaffTreeView> getTenantCompDeptInfo() {
		String tenantId = AuthSecurityUtils.getCurrentUserInfo().getTenantId();// 租户id

		List<DeptStaffTreeView> deptStaffTreeViews = new ArrayList<>();
		List<CommonCompany> companyList = companyService
				.selectList(new EntityWrapper<CommonCompany>().eq(CommonCompany.QueryFields.TENANT_ID, tenantId));
		companyList.forEach(company -> {
			DeptStaffTreeView deptStaffTreeView1 = new DeptStaffTreeView();
			deptStaffTreeView1.setId(company.getCompId());
			deptStaffTreeView1.setParentId("-1");
			deptStaffTreeView1.setName(company.getCompName());
			deptStaffTreeView1.setShortName(company.getCompSimpleName());

			// 获取公司下所有部门
			List<CommonDepartment> departments = departmentService.selectList(new EntityWrapper<CommonDepartment>()
					.eq(CommonDepartment.QueryFields.UNDER_COMP_ID, company.getCompId()));
			List<DeptStaffTreeView> childList = new ArrayList<>();
			departments.forEach(dept -> {
				DeptStaffTreeView deptDetail = new DeptStaffTreeView();
				deptDetail.setId(dept.getDeptId());
				deptDetail.setName(dept.getDeptName());
				childList.add(deptDetail);
			});
			deptStaffTreeView1.setChildren(childList);
			deptStaffTreeViews.add(deptStaffTreeView1);
		});
		return deptStaffTreeViews;
	}
}
