package com.testor.module.notice.service.impl;


import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.file.model.dto.FileDTO;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.biz.sys.user.model.domain.SysUser;
import com.testor.biz.sys.user.service.SysUserService;
import com.testor.module.isRead.model.domain.TSysIsRead;
import com.testor.module.isRead.service.TSysIsReadService;
import com.testor.module.notice.dao.TSysNoticeDao;
import com.testor.module.notice.model.domain.DetailNotice;
import com.testor.module.notice.model.domain.TSysFile;
import com.testor.module.notice.model.domain.TSysNotice;
import com.testor.module.notice.model.dto.TSysNoticeDelParam;
import com.testor.module.notice.model.dto.TSysNoticeParam;
import com.testor.module.notice.service.TSysFileService;
import com.testor.module.notice.service.TSysNoticeService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.exception.BusinessException;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * noticeService业务层处理
 *
 * @author tong-framework
 * @date 2022-04-27 18:10:12
 */
@Service
public class TSysNoticeServiceImpl extends SuperServiceImpl<TSysNoticeDao, TSysNotice> implements TSysNoticeService {
    @Autowired(required = false)
    private TSysNoticeDao tSysNoticeDao;
    @Autowired
    private TSysFileService tSysFileService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysOrgService sysOrgService;
    @Autowired
    private TSysIsReadService tSysIsReadService;

    @Override
    public BaseResponse<TSysNotice> addEntity(TSysNotice addRequest) throws Exception{
        BaseResponse<TSysNotice> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(addRequest)) {
            String loginName = "";
            try {
                loginName = ContextUtils.getLoginUser().getLoginName();
            } catch (Exception e) {
                throw new BusinessException("未登录");
            }
            String refId = addRequest.getRefId();
            LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysUser::getLoginName, loginName);
            wrapper.eq(SysUser::getStatus,"0");
            SysUser sysUser = sysUserService.getOne(wrapper);
            LambdaQueryWrapper<SysOrg> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysOrg::getOrgId, sysUser.getOrgId());
            queryWrapper.eq(SysOrg::getStatus,"0");
            SysOrg sysOrg = sysOrgService.getOne(queryWrapper);
            String id = IdHelper.getId32bit();
            TSysNotice data = BeanHelper.beanToBean(addRequest, TSysNotice.class);
            data.setId(id);
            data.setRefId(refId);
            data.setCreateBy(sysUser.getUserId());
            data.setUpdateBy(sysUser.getUserId());
//            data.setIsRead("0");
            data.setStatus("0");
            data.setOrgId(sysUser.getOrgId());
            data.setReleaseUnit(sysOrg.getOrgName());
            data.setLevel(sysOrg.getTreeLevel());
            data.setReceiverType("2");
            boolean result = this.save(data);
            TSysNotice newEntity = new TSysNotice();
            newEntity.setId(id);
            baseResponse.setData(newEntity);
        }
        return baseResponse;
    }

    @Override
    public BaseResponse getByIds(String id) {
        BaseResponse baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            TSysNotice data = this.getById(id);
            if (data == null) {
                baseResponse.setMsg("id不存在");
                return baseResponse;
            }
            String refId = data.getRefId();
            TSysFile tSysFile = tSysFileService.getById(refId);
            DetailNotice detailNotice = BeanHelper.beanToBean(data, DetailNotice.class);
            detailNotice.setFileName(tSysFile.getFileName());
            baseResponse.setData(detailNotice);
        }
        return baseResponse;
    }

    @Override
    public BaseResponse updateEntity(DetailNotice updateRequest)throws Exception {
        BaseResponse baseResponse = new BaseResponse<>();
        String id = updateRequest.getId();
        String refId = updateRequest.getRefId();
        if (id != null) {
            TSysNotice tSysNotice = BeanHelper.beanToBean(updateRequest, TSysNotice.class);
            LambdaQueryWrapper<TSysNotice> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TSysNotice::getId, tSysNotice.getId());
            TSysNotice one = this.getOne(wrapper);
            if (!"0".equals(one.getStatus())) {
                throw new BusinessException("数据已删除");
            }
            if ("5".equals(updateRequest.getProcessStatus())) {
                tSysNotice.setReleaseTime(new Date());
            }
            try {
                String loginName = ContextUtils.getLoginUser().getLoginName();
                LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<>();
                query.eq(SysUser::getLoginName, loginName);
                SysUser sysUser = sysUserService.getOne(query);
                tSysNotice.setUpdateBy(sysUser.getUserId());
            } catch (Exception e) {
                e.printStackTrace();
            }
            boolean result = this.saveOrUpdate(tSysNotice, wrapper);
//            if (!result) {
//                baseResponse.setMsg("公告修改失败");
//                return baseResponse;
//            }
            baseResponse.setMsg("修改成功");
        }

        return baseResponse;
    }


    @Override
    @Transactional
    public BaseResponse deleteNotice(TSysNoticeDelParam tSysNoticeDelParam) throws Exception {
        BaseResponse baseResponse = new BaseResponse<>();
        String noticeId = tSysNoticeDelParam.getId();
        TSysNotice notice = this.getById(noticeId);
        if (notice == null || "1".equals(notice.getStatus())) {
            throw new BusinessException("数据不存在");
        }
        String refId = notice.getRefId();
        List<String> refIds = new ArrayList<>();
        if (org.apache.commons.lang.StringUtils.isNotBlank(refId)) {
            String[] split = refId.split(",");
            refIds= Arrays.asList(split);
            List<TSysFile> beans = tSysFileService.list(new QueryWrapper<TSysFile>().in("file_id", refIds));
            if (CollectionUtils.isEmpty(beans)||beans.size()==0) {
                throw new BusinessException("数据不存在");
            }
            for (TSysFile bean : beans) {
                bean.setStatus(BizConstants.STATUS_DELETE);
                tSysFileService.updateById(bean);
            }

        }

//        if (!("".equals(refId))) {
//            TSysFile tSysFile = tSysFileService.getById(refId);
//            if (tSysFile == null) {
//                throw new BusinessException("数据不存在");
//            }
//            if (tSysFile != null || !("1".equals(tSysFile.getStatus()))) {
//                tSysFile.setStatus(BizConstants.STATUS_DELETE);
//                tSysFileService.updateById(tSysFile);
//            }
//        }
        if (ObjectHelper.isNotEmpty(tSysNoticeDelParam) && StringHelper.isNotEmpty(noticeId)) {
            TSysNotice data = new TSysNotice();
            data.setId(noticeId);
            data.setStatus(BizConstants.STATUS_DELETE);
            boolean result = this.updateById(data);
            if (!result) {
                throw new BusinessException("数据不存在");
            }
            baseResponse.setMsg("删除成功");
        }
        return baseResponse;
    }

    @Override
    public BaseResponse detail(TSysNotice tSysNotice) throws Exception{
        BaseResponse<Object> response = new BaseResponse<>();
        String noticeId = tSysNotice.getId();
        if (ObjectHelper.isNotEmpty(tSysNotice) && StringHelper.isNotEmpty(noticeId)) {
            TSysNotice notice = this.getById(noticeId);
            if (notice == null || "1".equals(notice.getStatus())) {
//                response.setMsg("文章不存在");
//                return response;
                throw new BusinessException("数据不存在");
            }

            String refId = notice.getRefId();
            String[] split = null;
            DetailNotice detailNotice = new DetailNotice();
            if (refId != null) {
                split = refId.split(",");
                List<FileDTO> list = new ArrayList<>();
                if (split.length > 0) {
                    for (String s : split) {
                        FileDTO fileDTO = new FileDTO();
                        TSysFile tSysFile = tSysFileService.getById(s);
                        if (tSysFile != null && !(tSysFile.getStatus().equals("1"))) {
                            fileDTO.setFilePath(tSysFile.getFilePath());
                            fileDTO.setFileName(tSysFile.getFileName());
                            fileDTO.setFileDowName(tSysFile.getFileDowName());
                            fileDTO.setFileId(s);
                            list.add(fileDTO);
                        }
                    }
                    detailNotice.setFileDTOS(list);
                }
            }

            detailNotice.setId(notice.getId());
            detailNotice.setContent(notice.getContent());
            detailNotice.setReceiverObj(notice.getReceiverObj());
            detailNotice.setAcceptObj(notice.getAcceptObj());
            detailNotice.setTitle(notice.getTitle());
            detailNotice.setCreateDate(notice.getCreateDate());
            detailNotice.setUpdateDate(notice.getUpdateDate());
            detailNotice.setReleaseTime(notice.getReleaseTime());
            detailNotice.setProcessStatus(notice.getProcessStatus());
//            detailNotice.setIsRead(notice.getIsRead());
            detailNotice.setStatus(notice.getStatus());
            detailNotice.setRejectOpinion(notice.getRejectOpinion());
            detailNotice.setProcessId(notice.getProcessId());
            detailNotice.setOrgId(notice.getOrgId());
            detailNotice.setCreateBy(notice.getCreateBy());
            response.setData(detailNotice);
        } else {
//            response.setMsg("参数有误");
//            response.setCode(996);
//            return response;
            throw new BusinessException("参数异常");
        }
        return response;
    }


    @Override
    public BaseResponse getIsRead(TSysNotice tSysNotice) throws Exception{
        BaseResponse<Object> response = new BaseResponse<>();
        String noticeId = tSysNotice.getId();
        if (ObjectHelper.isNotEmpty(tSysNotice) && StringHelper.isNotEmpty(noticeId)) {
            TSysNotice notice = this.getById(noticeId);
            if (notice == null || "1".equals(notice.getStatus())) {
//                response.setMsg("文章不存在");
//                return response;
                throw new BusinessException("数据不存在");
            }

            //设置已读未读
            getNoticeIsRead(noticeId);

            String refId = notice.getRefId();
            String[] split = null;
            DetailNotice detailNotice = new DetailNotice();
            if (refId != null) {
                split = refId.split(",");
                List<FileDTO> list = new ArrayList<>();
                if (split.length > 0) {
                    for (String s : split) {
                        FileDTO fileDTO = new FileDTO();
                        TSysFile tSysFile = tSysFileService.getById(s);
                        if (tSysFile != null && !(tSysFile.getStatus().equals("1"))) {
                            fileDTO.setFilePath(tSysFile.getFilePath());
                            fileDTO.setFileName(tSysFile.getFileName());
                            fileDTO.setFileId(s);
                            list.add(fileDTO);
                        }
                    }
                    detailNotice.setFileDTOS(list);
                }
            }
            detailNotice.setId(notice.getId());
            detailNotice.setContent(notice.getContent());
            detailNotice.setReceiverObj(notice.getReceiverObj());
            detailNotice.setAcceptObj(notice.getAcceptObj());
            detailNotice.setTitle(notice.getTitle());
            detailNotice.setCreateDate(notice.getCreateDate());
            detailNotice.setUpdateDate(notice.getUpdateDate());
            detailNotice.setReleaseTime(notice.getReleaseTime());
            detailNotice.setProcessStatus(notice.getProcessStatus());
//            detailNotice.setIsRead(notice.getIsRead());
            detailNotice.setStatus(notice.getStatus());
            detailNotice.setRejectOpinion(notice.getRejectOpinion());
            detailNotice.setProcessId(notice.getProcessId());
            response.setData(detailNotice);
        } else {
//            response.setMsg("参数有误");
//            response.setCode(996);
//            return response;
            throw new BusinessException("参数异常");
        }
        return response;
    }

    public void getNoticeIsRead(String noticeId) {
        String loginUserId = ContextUtils.getLoginUserId();
        QueryWrapper<TSysIsRead> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(TSysIsRead.USER_ID,loginUserId)
                .eq(TSysIsRead.ARTICLE_ID,noticeId);
        TSysIsRead one = tSysIsReadService.getOne(queryWrapper);
        if (one == null) {
            String bit = IdHelper.getId32bit();
            TSysIsRead tSysIsRead = new TSysIsRead();
            tSysIsRead.setId(bit);
            tSysIsRead.setUserId(loginUserId);
            tSysIsRead.setArticleId(noticeId);
            tSysIsRead.setIsRead("1");
            tSysIsReadService.saveOrUpdate(tSysIsRead);
        }
    }

    @Override
    public BaseResponse<BaseResponseList<TSysNotice>> listEntity(TSysNoticeParam param, String startTime, String endTime) {
        BaseResponse<BaseResponseList<TSysNotice>> pages = getPages(param, startTime, endTime);
        return pages;
    }

    @Override
    public BaseResponse<BaseResponseList<TSysNotice>> listAllEntity(TSysNoticeParam param, String startTime, String endTime) {
        //BaseResponse<BaseResponseList<TSysNotice>> pages = getPages(param, startTime, endTime);
        return null;
    }

    public BaseResponse<BaseResponseList<TSysNotice>> getPages(TSysNoticeParam param, String startTime, String endTime) {
        BaseResponse<BaseResponseList<TSysNotice>> baseResponse = new BaseResponse<>();
        Long page =
                StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit =
                StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
        Page<TSysNotice> resultPage = new Page<>(page, limit);
        QueryWrapper<TSysNotice> queryWrapper = this.createQuery(param, startTime, endTime);
        Page<TSysNotice> resultList = this.page(resultPage, queryWrapper);
        BaseResponseList<TSysNotice> baseResponseList = new BaseResponseList<>();
        baseResponseList.setData(resultList.getRecords());
        baseResponseList.setTotal(resultList.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TSysNotice> createQuery(TSysNoticeParam queryParam, String startTime, String endTime) {
        QueryWrapper<TSysNotice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "0");
        if (!StringUtils.isEmpty(startTime)) {
            String start = startTime + " 00:00:00";
            queryWrapper.ge("create_date", start);
        }
        if (!StringUtils.isEmpty(endTime)) {
            String end = endTime + " 23:59:59";
            queryWrapper.le("create_date", end);
        }
        queryWrapper.orderByDesc("create_date");
        String loginName = "";
        try {
            loginName = ContextUtils.getLoginUser().getLoginName();
        } catch (Exception e) {
            e.printStackTrace();
        }
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUser::getLoginName, loginName);
        SysUser one = sysUserService.getOne(lambdaQueryWrapper);
        if (one != null) {
            String createBy = one.getUserId();
            if (StringHelper.isNotEmpty(createBy)) {
                queryWrapper.eq(TSysNotice.CREATE_BY, createBy);
            }
        }
        if (StringHelper.isNotEmpty(queryParam.getTitle())) {
            queryWrapper.like(TSysNotice.TITLE, queryParam.getTitle());
        }
        if (StringHelper.isNotEmpty(queryParam.getProcessStatus())) {
            queryWrapper.eq(TSysNotice.PROCESS_STATUS, queryParam.getProcessStatus());
        }
        if (StringHelper.isNotEmpty(queryParam.getCreateBy())) {
            queryWrapper.eq(TSysNotice.CREATE_BY, queryParam.getCreateBy());
        }
        if (StringHelper.isNotEmpty(queryParam.getContent())) {
            queryWrapper.eq(TSysNotice.CONTENT, queryParam.getContent());
        }
        if (StringHelper.isNotEmpty(queryParam.getReceiverObj())) {
            queryWrapper.eq(TSysNotice.RECEIVER_OBJ, queryParam.getReceiverObj());
        }
        if (StringHelper.isNotEmpty(queryParam.getRefId())) {
            queryWrapper.eq(TSysNotice.REF_ID, queryParam.getRefId());
        }
        if (StringHelper.isNotEmpty(queryParam.getRejectOpinion())) {
            queryWrapper.eq(TSysNotice.REJECT_OPINION, queryParam.getRejectOpinion());
        }
//        if (StringHelper.isNotEmpty(queryParam.getIsRead())) {
//            queryWrapper.eq(TSysNotice.IS_READ, queryParam.getIsRead());
//        }
        if (StringHelper.isNotEmpty(queryParam.getParentId())) {
            queryWrapper.eq(TSysNotice.PARENT_ID, queryParam.getParentId());
        }
        if (StringHelper.isNotEmpty(queryParam.getTenantId())) {
            queryWrapper.eq(TSysNotice.TENANT_ID, queryParam.getTenantId());
        }
        if (StringHelper.isNotEmpty(queryParam.getProcessId())) {
            queryWrapper.eq(TSysNotice.PROCESS_ID, queryParam.getProcessId());
        }
        if ("4".equals(queryParam.getProcessStatus())) {
            queryWrapper.eq(TSysNotice.PROCESS_STATUS, queryParam.getProcessStatus());
        } else {
            queryWrapper.ne(TSysNotice.PROCESS_STATUS,"4");
        }
        if (StringHelper.isNotEmpty(queryParam.getProcessStatus())) {
            queryWrapper.eq(TSysNotice.PROCESS_STATUS, queryParam.getProcessStatus());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TSysNotice.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TSysNotice.STATUS, BizConstants.STATUS_DELETE);
        }
        if (StringHelper.isNotEmpty(queryParam.getOrderBy())) {
            if (StringHelper.isNotEmpty(queryParam.getOrderType())
                    && BizConstants.ASC.equals(queryParam.getOrderType())) {
                queryWrapper.orderByAsc(queryParam.getOrderBy());
            } else {
                queryWrapper.orderByDesc(queryParam.getOrderBy());
            }
        } else {
            queryWrapper.orderByDesc(TSysNotice.UPDATE_DATE);
        }
        return queryWrapper;
    }

    public String getFileName(String pathName) {
        if (!pathName.contains("_")) {
            return null;
        }
        String[] s = pathName.split("_");
        String s1 = s[s.length - 2];
        String s4 = s[s.length - 1];
        String[] split1 = s4.split("\\.");
        String s3 = split1[split1.length - 1];
        String[] split = s1.split("\\/");
        String s2 = split[split.length - 1];
        String fileName = s2 + "." + s3;
        return fileName;
    }

    @Override
    public IPage<TSysNotice> getRead(TSysNoticeParam param, String startTime, String endTime, List<String> list, String loginUserId,String orgId) {
        Long page = StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit = StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
        Page<TSysNotice> resultPage = new Page<>(page, limit);
        return tSysNoticeDao.getRead(resultPage, param, startTime, endTime, list, loginUserId,orgId);
    }

    @Override
    public IPage<TSysNotice> getUnRead(TSysNoticeParam param, String startTime, String endTime, List<String> list, String loginUserId,String orgId) {
        Long page = StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit = StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
        Page<TSysNotice> resultPage = new Page<>(page, limit);
        return tSysNoticeDao.getUnRead(resultPage, param, startTime, endTime, list, loginUserId,orgId);
    }

    @Override
    public IPage<TSysNotice> getNewsAndNotice(TSysNoticeParam param , String orgId) {
        Long page = StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit = StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
        Page<TSysNotice> resultPage = new Page<>(page, limit);
        return tSysNoticeDao.getNewsAndNotice(resultPage, param , orgId);
    }
}
