package com.yh.saas.plugin.news.service.impl;

import com.alipay.sofa.runtime.api.annotation.SofaReference;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.winsea.svc.base.base.entity.CommonRole;
import com.winsea.svc.base.base.entity.CommonStaff;
import com.winsea.svc.base.base.entity.CommonStaffRole;
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.security.util.AuthSecurityUtils;
import com.winsea.svc.notice.entity.NoticeTaskInfo;
import com.yh.saas.plugin.news.command.CircularManagementReceiveCommand;
import com.yh.saas.plugin.news.command.CircularManagementReceiveSearchCommand;
import com.yh.saas.plugin.news.constant.CircularConstant;
import com.yh.saas.plugin.news.entity.CircularManagementInfo;
import com.yh.saas.plugin.news.entity.CircularManagementReceive;
import com.yh.saas.plugin.news.enums.CircularStatusEnum;
import com.yh.saas.plugin.news.mapper.NewsCircularManagementReceiveMapper;
import com.yh.saas.plugin.news.service.INewsCircularManagementInfoService;
import com.yh.saas.plugin.news.service.INewsCircularManagementReceiveService;
import com.yh.saas.plugin.news.service.INewsOperationHisService;
import com.yh.saas.plugin.news.vo.CircularManagementReceiveVo;
import com.winsea.svc.notice.entity.NoticeNewsInfo;
import com.winsea.svc.notice.entity.base.BaseNotice;
import com.winsea.svc.notice.service.INoticeNewsService;
import com.winsea.svc.notice.service.INoticeService;
import com.winsea.svc.notice.service.INoticeTaskService;
import com.yh.saas.common.support.util.query.QueryUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 记录体系通函接收表 服务实现类
 * </p>
 *
 * @author wxg
 * @since 2019-10-15
 */
@Service
public class NewsCircularManagementReceiveServiceImpl
        extends ServiceImpl<NewsCircularManagementReceiveMapper, CircularManagementReceive>
        implements INewsCircularManagementReceiveService {

    @Autowired
    @Lazy
    private INewsCircularManagementInfoService circularManagementInfoService;

    @SofaReference
    private ICommonStaffRoleService staffRoleService;

    @SofaReference
    private ICommonStaffService staffService;

    @SofaReference
    private ICommonDepartmentService departmentService;

    @SofaReference
    private ICommonRoleService commonRoleService;

    @SofaReference
    private ICommonStaffService commonStaffService;

    @Autowired
    private INewsOperationHisService operationHisService;

    @SofaReference
    private INoticeService noticeService;

    @SofaReference
    private INoticeNewsService noticeNewsService;

    @SofaReference
    private INoticeTaskService taskService;

    @Override
    public Page<CircularManagementReceiveVo> queryCircularManagementReceiveList(
            CircularManagementReceiveSearchCommand example) {

        // 因为发给子公司的公司id不同，但只能取到主公司的id，所以只拿部门id筛选
        example.setCompId(null);
        String a = AuthSecurityUtils.getCurrentUserInfo().getCompId();
        if (StringUtils.isBlank(example.getVesselDeptId())) {
            return null;
        }
        // 将参数类转化成实体类
        CircularManagementReceive circularManagementReceive = new CircularManagementReceive();
        BeanUtils.copyProperties(example, circularManagementReceive);

        // 查询列表
        Wrapper<CircularManagementReceive> itemWrapper = QueryUtils.convertExampleToWrapper(circularManagementReceive);
        if (StringUtils.isNotBlank(circularManagementReceive.getSearchKeyword())) {
            itemWrapper.andNew(
                    CircularManagementInfo.QueryFields.THEME + " like {0} OR "
                            + CircularManagementInfo.QueryFields.CIRCULAR_CODE + " like {0}",
                    "%" + circularManagementReceive.getSearchKeyword() + "%");
        }

        if (example.getStartDate() != null) {
            itemWrapper.andNew("date_of_issue >= {0}", example.getStartDate());
        }
        if (example.getEndDate() != null) {
            itemWrapper.andNew("date_of_issue <= {0}", example.getEndDate());
        }
        if (StringUtils.isBlank(example.getOrderColunm())) {
            itemWrapper.orderBy(CircularManagementInfo.QueryFields.STATUS_ID, true);
            itemWrapper.orderBy(CircularManagementInfo.QueryFields.DATE_OF_ISSUE, false);
        }
        Page<CircularManagementReceive> pageList = this.selectPage(circularManagementReceive.getQueryPage(),
                itemWrapper);
        //pageList.setTotal(this.selectCount(itemWrapper));

        // 循环列表将实体类转换成VO
        Page<CircularManagementReceiveVo> resultList = new Page<>();
        List<CircularManagementReceiveVo> responseList = new ArrayList<>();
        pageList.getRecords().forEach(item -> {
            CircularManagementReceiveVo circularManagementReceiveVo = new CircularManagementReceiveVo();
            BeanUtils.copyProperties(item, circularManagementReceiveVo);

            CircularManagementInfo circularManagementInfo = circularManagementInfoService.selectById(item.getCircularId());
            if (null != circularManagementInfo) {
                CommonStaff commonStaff = commonStaffService.selectById(circularManagementInfo.getCreateUserId());
                if (null != commonStaff) {
                    circularManagementReceiveVo.setSender(circularManagementInfo.getDeptName() + " " + commonStaff.getStaffName());
                }
            }

            if (StringUtils.isNotBlank(circularManagementReceiveVo.getAttachmentPath())) {
                String[] attachmentPaths = circularManagementReceiveVo.getAttachmentPath().split(",");
                circularManagementReceiveVo.setAttachmentNum(String.valueOf(attachmentPaths.length));
            } else {
                circularManagementReceiveVo.setAttachmentNum("0");
            }

            if (StringUtils.isNotBlank(circularManagementReceiveVo.getReceiveAttachmentPath())) {
                String[] receiveAttachmentPaths = circularManagementReceiveVo.getReceiveAttachmentPath()
                        .split(",");
                circularManagementReceiveVo
                        .setReceiveAttachmentNum(String.valueOf(receiveAttachmentPaths.length));
            } else {
                circularManagementReceiveVo.setReceiveAttachmentNum("0");
            }

            responseList.add(circularManagementReceiveVo);
        });

        resultList.setRecords(responseList);
        resultList.setTotal(pageList.getTotal());
        resultList.setCurrent(pageList.getCurrent());
        resultList.setSize(pageList.getSize());

        return resultList;
    }

    @Override
    public List<CircularManagementReceiveVo> getInfoHisById(String cid) {
        Wrapper<CircularManagementReceive> itemWrapper = new EntityWrapper<>();
        itemWrapper.eq(CircularManagementReceive.QueryFields.CIRCULAR_ID, cid);
        itemWrapper.orderBy(CircularManagementReceive.QueryFields.RECEIVEDATE, false);
        List<CircularManagementReceive> circularManagementReceiveList = this.selectList(itemWrapper);
        List<CircularManagementReceiveVo> list = new ArrayList<>();
        circularManagementReceiveList.stream().forEach(circularManagementReceive -> {
            CircularManagementReceiveVo circularManagementReceiveVo = new CircularManagementReceiveVo();
            BeanUtils.copyProperties(circularManagementReceive, circularManagementReceiveVo);
            list.add(circularManagementReceiveVo);
        });
        return list;
    }

    /**
     * 清除通知通函提醒
     *
     * @param id
     */
//    private void saveDetailClearingTask(String id) {
//      // 查询出当前接收信息
//        CircularManagementReceive receiveInfo = this.selectById(id);
//        List<String> staffIds = circularManagementInfoService.getReceiveStaffIdList(receiveInfo);
//        if (CollectionUtils.isNotEmpty(staffIds)) {
//            staffIds.forEach(staffId ->
//                    staffTodoTaskService.changeInfo(staffId, CircularConstant.CIRCULAR_MANAGEMENT_RECEIVE, receiveInfo.getId(),
//                            CircularConstant.CIRCULAR, false)
//            );
//        }
//    }

    /**
     * 接收
     *
     * @param example
     * @return
     */
    @Override
    @Transactional
    public void receiveCircularManagementInfo(CircularManagementReceiveCommand example) {
        // 将参数类转化成实体类
        CircularManagementReceive circularManagementReceive = new CircularManagementReceive();
        BeanUtils.copyProperties(example, circularManagementReceive);

        CommonStaffRole staffRole = staffRoleService.getMajorRole(AuthSecurityUtils.getCurrentUserInfo().getUserId());
        CommonRole commonRole = commonRoleService.selectById(staffRole.getRoleId());
        CommonStaff commonStaff = staffService.getInfo(staffRole.getStaffId());

        // 设置接收状态
        circularManagementReceive.setCompId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
        circularManagementReceive.setStatusId(CircularStatusEnum.WAITINGFEEDBACK.getFlag());
        circularManagementReceive.setStatus(CircularStatusEnum.WAITINGFEEDBACK.getName());
        circularManagementReceive.setStatusEn(CircularStatusEnum.WAITINGFEEDBACK.getNameEn());
        circularManagementReceive.setReceiveDate(new Date());
        circularManagementReceive.setReceiverId(AuthSecurityUtils.getCurrentUserInfo().getUserId());
        circularManagementReceive.setReceivrDuty(commonRole.getRoleName());
        circularManagementReceive.setReceivrName(commonStaff.getStaffName());

        // 更新通知通函接收信息
        this.updateById(circularManagementReceive);

        // 查询通知通函接收信息
        circularManagementReceive = this.selectById(example.getId());

        Wrapper<CircularManagementReceive> itemWrapper = new EntityWrapper<>();
        itemWrapper.eq(CircularManagementReceive.QueryFields.CIRCULAR_ID, circularManagementReceive.getCircularId());
        int countAllItem = this.selectCount(itemWrapper);// 查询所有发送的通知
        itemWrapper.in(CircularManagementReceive.QueryFields.STATUS_ID, CircularStatusEnum.WAITINGFEEDBACK.getFlag(),CircularStatusEnum.WAITINGFEEDBACK.getFlag());
        int countItem = this.selectCount(itemWrapper);

        CircularManagementInfo circularManagementInfo = new CircularManagementInfo();
        circularManagementInfo.setId(circularManagementReceive.getCircularId());

        if (countAllItem - countItem > 0) {
            DecimalFormat decimalFormat = new DecimalFormat("##%");
            // 通知通函部分接收
            circularManagementInfo.setStatusId(CircularStatusEnum.PARTRECEIVED.getFlag());
            circularManagementInfo.setStatus(CircularStatusEnum.PARTRECEIVED.getName() + countItem + "/" + countAllItem);
            circularManagementInfo.setStatusEn(CircularStatusEnum.PARTRECEIVED.getNameEn() + countItem + "/" + countAllItem);
        } else {
            // 通知通函全部接收
            circularManagementInfo.setStatusId(CircularStatusEnum.ALLRECEIVED.getFlag());
            circularManagementInfo.setStatus(CircularStatusEnum.ALLRECEIVED.getName());
            circularManagementInfo.setStatusEn(CircularStatusEnum.ALLRECEIVED.getNameEn());
        }
        // 更新通知通函状态
        circularManagementInfoService.updateById(circularManagementInfo);
        // 清除当前部门或船舶下所有人待接收任务
//        saveDetailClearingTask(example.getId());
        noticeService.removeNotice(BaseNotice.NoticeStatus.ALL, null, example.getId(), null);

        NoticeTaskInfo noticeTask = new NoticeTaskInfo();
        noticeTask.setCompId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
        noticeTask.setBusinessCode(CircularConstant.CIRCULAR_MANAGEMENT_RECEIVE);
        noticeTask.setBusinessType(CircularConstant.CIRCULAR);
        noticeTask.setBusinessId(circularManagementReceive.getId());
        noticeTask.setAcceptType(BaseNotice.AcceptStatus.ROLE);
        noticeTask.setMessageContent(MessageFormat.format(CircularConstant.CIRCULAR_MESSAGE_04,
                circularManagementReceive.getDeptName(), circularManagementReceive.getTheme()));
        List<CommonRole> roleList = commonRoleService.selectList(new EntityWrapper<CommonRole>()
                .eq(CommonRole.QueryFields.COMP_ID,AuthSecurityUtils.getCurrentUserInfo().getCompId())
                .eq(CommonRole.QueryFields.DEPT_ID,circularManagementReceive.getDeptId())
                .eq("delete_flag","0"));
        List<String> roles = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(roleList)){
            roleList.forEach(commonRole1 -> {
                roles.add(commonRole1.getRoleId());
            });
        }
        taskService.createNoticeTask(roles, null, noticeTask);

    }

    /**
     * 反馈
     *
     * @param example
     * @return
     */
    @Override
    @Transactional
    public void feedbackCircularManagementInfo(CircularManagementReceiveCommand example) {
        // 将参数类转化成实体类
        CircularManagementReceive circularManagementReceive = new CircularManagementReceive();
        BeanUtils.copyProperties(example, circularManagementReceive);

        CommonStaffRole staffRole = staffRoleService.getMajorRole(AuthSecurityUtils.getCurrentUserInfo().getUserId());
        CommonRole commonRole = commonRoleService.selectById(staffRole.getRoleId());
        CommonStaff commonStaff = staffService.getInfo(staffRole.getStaffId());

        // 设置接收状态
        circularManagementReceive.setStatusId(CircularStatusEnum.FEEDBACK.getFlag());
        circularManagementReceive.setStatus(CircularStatusEnum.FEEDBACK.getName());
        circularManagementReceive.setStatusEn(CircularStatusEnum.FEEDBACK.getNameEn());
        circularManagementReceive.setReceiveDate(new Date());
        circularManagementReceive.setReceiverId(AuthSecurityUtils.getCurrentUserInfo().getUserId());
        circularManagementReceive.setReceivrDuty(commonRole.getRoleName());
        circularManagementReceive.setReceivrName(commonStaff.getStaffName());

        // 更新通知通函接收信息
        this.updateById(circularManagementReceive);
        // 清除当前部门或船舶下所有人待接收任务
        noticeService.removeNotice(BaseNotice.NoticeStatus.ALL, null, example.getId(), null);

        CircularManagementInfo info = circularManagementInfoService.selectById(this.selectById(circularManagementReceive.getId()).getCircularId());
        NoticeNewsInfo noticeNews = new NoticeNewsInfo();
        noticeNews.setCompId(info.getCompId());
        noticeNews.setBusinessId(info.getId());
        noticeNews.setBusinessCode(CircularConstant.CIRCULAR_MANAGEMENT_RECEIVE);
        noticeNews.setBusinessType(CircularConstant.CIRCULAR);
        noticeNews.setMessageContent(MessageFormat.format(CircularConstant.CIRCULAR_MESSAGE_03,
                info.getTheme(), circularManagementReceive.getVesselDeptName()));
        noticeNews.setAcceptType(BaseNotice.AcceptStatus.STAFF);
        //创建任务通知
        noticeNewsService.createNoticeNews(Arrays.asList(info.getCreateUserId()), null, noticeNews);

    }

    /**
     * 批量接收
     *
     * @param example
     */
    @Override
    @Transactional
    public void receiveInfos(CircularManagementReceiveCommand example) {
        List<String> idList = Arrays.asList(example.getId().split(","));
        if (CollectionUtils.isEmpty(idList)) {
            return;
        }
        for(int i=0;i<idList.size();i++){
            if (StringUtils.isNotEmpty(idList.get(i))) {
                CircularManagementReceiveCommand request = new CircularManagementReceiveCommand();
                request.setId(idList.get(i));
                receiveCircularManagementInfo(request);
            }
        }
    }

    /**
     * 保存
     *
     * @param example
     * @return
     */
    @Override
    @Transactional
    public void saveCircularManagementInfo(CircularManagementReceiveCommand example) {
        // 将参数类转化成实体类
        CircularManagementReceive circularManagementReceive = new CircularManagementReceive();
        BeanUtils.copyProperties(example, circularManagementReceive);
        // 更新通知通函接收信息
        this.updateById(circularManagementReceive);
    }

    /**
     * 接收明细
     *
     * @param id
     * @return
     */
    @Override
    public CircularManagementReceiveVo getReceiveDetail(String id) {
        CircularManagementReceiveVo receiveVo = new CircularManagementReceiveVo();
        CircularManagementReceive receive = this.selectById(id);
        CircularManagementInfo circularManagementInfo = circularManagementInfoService.selectById(receive.getCircularId());
        //添加备注
        if(StringUtils.isNotBlank(circularManagementInfo.getRemarks())){
            receive.setRemarks(circularManagementInfo.getRemarks());
        }
        //是否需要反馈
        String feedback = "";//需要反馈的部门或船舶id
        if(StringUtils.equals("1",receive.getVesselDeptType())){//船舶
            feedback = circularManagementInfo.getVesselIds();
        }else{
            feedback = circularManagementInfo.getDeptIds();
        }
        if(StringUtils.isNoneBlank(feedback) && StringUtils.contains(feedback, receive.getVesselDeptId())){
            receive.setLearnFeedback(true);
        }else{
            receive.setLearnFeedback(false);
        }
        BeanUtils.copyProperties(receive, receiveVo);
        receiveVo.setOperationHisVoList(operationHisService.getOperationHis(id));
        return receiveVo;
    }



    /**
     * 接收
     *
     * @param example
     * @return
     */
    @Override
    @Transactional
    public void receiveCircularManagement(CircularManagementReceiveCommand example) {
        // 将参数类转化成实体类
        CircularManagementReceive circularManagementReceive = new CircularManagementReceive();
        BeanUtils.copyProperties(example, circularManagementReceive);

        CommonStaffRole staffRole = staffRoleService.getMajorRole(AuthSecurityUtils.getCurrentUserInfo().getUserId());
        CommonRole commonRole = commonRoleService.selectById(staffRole.getRoleId());
        CommonStaff commonStaff = staffService.getInfo(staffRole.getStaffId());

        // 设置接收状态
        circularManagementReceive.setStatusId(CircularStatusEnum.RECEIVED.getFlag());
        circularManagementReceive.setStatus(CircularStatusEnum.RECEIVED.getName());
        circularManagementReceive.setStatusEn(CircularStatusEnum.RECEIVED.getNameEn());
        circularManagementReceive.setReceiveDate(new Date());
        circularManagementReceive.setReceiverId(AuthSecurityUtils.getCurrentUserInfo().getUserId());
        circularManagementReceive.setReceivrDuty(commonRole.getRoleName());
        circularManagementReceive.setReceivrName(commonStaff.getStaffName());

        // 更新通知通函接收信息
        this.updateById(circularManagementReceive);

        // 查询通知通函接收信息
        circularManagementReceive = this.selectById(example.getId());

        Wrapper<CircularManagementReceive> itemWrapper = new EntityWrapper<>();
        itemWrapper.eq(CircularManagementReceive.QueryFields.CIRCULAR_ID, circularManagementReceive.getCircularId());
        int countAllItem = this.selectCount(itemWrapper);// 查询所有发送的通知
        itemWrapper.eq(CircularManagementReceive.QueryFields.STATUS_ID, CircularStatusEnum.RECEIVED.getFlag());
        int countItem = this.selectCount(itemWrapper);

        CircularManagementInfo circularManagementInfo = new CircularManagementInfo();
        circularManagementInfo.setId(circularManagementReceive.getCircularId());

        if (countAllItem - countItem > 0) {
            DecimalFormat decimalFormat = new DecimalFormat("##%");
            // 通知通函部分接收
            circularManagementInfo.setStatusId(CircularStatusEnum.PARTRECEIVED.getFlag());
            circularManagementInfo.setStatus(CircularStatusEnum.PARTRECEIVED.getName() + countItem + "/" + countAllItem);
            circularManagementInfo.setStatusEn(CircularStatusEnum.PARTRECEIVED.getNameEn() + countItem + "/" + countAllItem);
        } else {
            // 通知通函全部接收
            circularManagementInfo.setStatusId(CircularStatusEnum.ALLRECEIVED.getFlag());
            circularManagementInfo.setStatus(CircularStatusEnum.ALLRECEIVED.getName());
            circularManagementInfo.setStatusEn(CircularStatusEnum.ALLRECEIVED.getNameEn());
        }
        // 更新通知通函状态
        circularManagementInfoService.updateById(circularManagementInfo);
        // 清除当前部门或船舶下所有人待接收任务
//        saveDetailClearingTask(example.getId());
        noticeService.removeNotice(BaseNotice.NoticeStatus.ALL, null, example.getId(), null);

        // 发送已提交的消息
//        NotificationStaffTodoTask task = new NotificationStaffTodoTask();
//        task.setBusinessId().setBusinessType().setBusinessCode()
//                .setMessageTitle(CircularConstant.CIRCULAR_MANAGEMENT_RECEIVE_CH).setMessageContent;
//        staffTodoTaskService.createMessage(, , task);

        CircularManagementInfo info = circularManagementInfoService.selectById(circularManagementReceive.getCircularId());
        NoticeNewsInfo noticeNews = new NoticeNewsInfo();
        noticeNews.setCompId(info.getCompId());
        noticeNews.setBusinessId(info.getId());
        noticeNews.setBusinessCode(CircularConstant.CIRCULAR_MANAGEMENT_POSTED);
        noticeNews.setBusinessType(CircularConstant.CIRCULAR);
        noticeNews.setMessageContent(MessageFormat.format(CircularConstant.CIRCULAR_MESSAGE_03,
                info.getTheme(), circularManagementReceive.getVesselDeptName()));
        noticeNews.setAcceptType(BaseNotice.AcceptStatus.STAFF);
        //创建任务通知
        noticeNewsService.createNoticeNews(Arrays.asList(info.getCreateUserId()), null, noticeNews);

    }
}
