package yangtz.cs.liu.campus.service.impl.schooloffical;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yangtz.cs.liu.campus.constant.OfficalConstant;
import yangtz.cs.liu.campus.domain.file.PubFile;
import yangtz.cs.liu.campus.domain.schooloffical.SchoolOfficial;
import yangtz.cs.liu.campus.domain.schooloffical.SchoolOfficialFlow;
import yangtz.cs.liu.campus.mapper.pubFile.PubFileMapper;
import yangtz.cs.liu.campus.mapper.schooloffical.SchoolOfficialFlowMapper;
import yangtz.cs.liu.campus.mapper.schooloffical.SchoolOfficialMapper;
import yangtz.cs.liu.campus.service.schooloffical.ISchoolOfficalService;
import yangtz.cs.liu.campus.vo.schoolOfficial.SchoolOfficialVo;

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

import static com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank;
import static com.ruoyi.common.utils.SecurityUtils.getUserId;
import static yangtz.cs.liu.campus.constant.OfficalConstant.*;

@Service
public class ISchoolOfficalImpl extends ServiceImpl<SchoolOfficialMapper, SchoolOfficial> implements ISchoolOfficalService {

    @Autowired
    SchoolOfficialMapper schoolOfficialMapper;

    @Autowired
    SchoolOfficialFlowMapper schoolOfficialFlowMapper;

    @Autowired
    PubFileMapper pubFileMapper;

    @Autowired
    SysUserMapper userMapper;


    /**
     * 查询所有内容（schoolofficial）
     *
     * @param schoolOfficial
     * @return
     */
    public List<SchoolOfficial> queryList(SchoolOfficial schoolOfficial) {
        LambdaQueryWrapper<SchoolOfficial> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(SchoolOfficial::getId);
        return schoolOfficialMapper.selectList(lqw);
    }
    /**
     * 设置暂存状态
     *
     * @param
     */
    @Override
    public void Temporary() {
        LambdaUpdateWrapper<SchoolOfficial> luw = new LambdaUpdateWrapper<>();
        luw.set(SchoolOfficial::getState, 0);
    }

    /**
     * 设置发文状态
     *
     * @param
     */
    @Override
    public void Message() {
        LambdaUpdateWrapper<SchoolOfficial> luw = new LambdaUpdateWrapper<>();
        luw.set(SchoolOfficial::getState, 1);
    }

    /**
     * 查询
     *列表
     * @param schoolOfficial
     * @return
     */
    @Override
    public List<SchoolOfficial> selectList(SchoolOfficial schoolOfficial) {
        LambdaQueryWrapper<SchoolOfficial> lqw = new LambdaQueryWrapper<>();
        lqw
                .like(isNotBlank(schoolOfficial.getIssuedNum()), SchoolOfficial::getIssuedNum, schoolOfficial.getIssuedNum())
                .like(isNotBlank(schoolOfficial.getIssuedName()), SchoolOfficial::getIssuedName, schoolOfficial.getIssuedName())
                .eq(isNotBlank(schoolOfficial.getState()), SchoolOfficial::getState, schoolOfficial.getState())
                .eq(isNotBlank(schoolOfficial.getUrgency()), SchoolOfficial::getUrgency, schoolOfficial.getUrgency());
        List<SchoolOfficial> list = schoolOfficialMapper.selectList(lqw);
        return list;
    }

    /**
     * 查询
     *列表
     * @param schoolOfficial
     * @return
     */
    @Override
    public List<SchoolOfficialVo> selectListVo(SchoolOfficial schoolOfficial) {
        //List<SchoolOfficialVo> list = schoolOfficialMapper.selectListVO(schoolOfficial,MKMC);
        List<SchoolOfficialVo> list = schoolOfficialMapper.selectListVO(schoolOfficial);
        for(SchoolOfficialVo vo : list){
            LambdaQueryWrapper<PubFile> lqw = new LambdaQueryWrapper<>();
            lqw.eq(PubFile::getYwid,vo.getId()).eq(PubFile::getMkmc,MKMC);
            List<PubFile> pubFiles = pubFileMapper.selectList(lqw);
            if(StringUtils.isNotNull(pubFiles) || pubFiles.size() > 0){
                vo.setFileList(pubFiles);
            }
        }
        return list;
    }

    /**
     * 修改(有id)
     *
     * @param schoolOfficialVo
     * @return
     */
    @Override
    public int updateSchoolOfficialById(SchoolOfficialVo schoolOfficialVo) {
        SchoolOfficial schoolOfficial = new SchoolOfficial();
        SchoolOfficialFlow schoolOfficialFlow = new SchoolOfficialFlow();
        schoolOfficial.setId(schoolOfficialVo.getId());
        schoolOfficial.setIssuedName(schoolOfficialVo.getIssuedName());
        schoolOfficial.setIssuedNum(schoolOfficialVo.getIssuedNum());
        schoolOfficial.setReceiveDate(schoolOfficialVo.getReceiveDate());
        schoolOfficial.setDeadline(schoolOfficialVo.getDeadline());
        schoolOfficial.setUrgency(schoolOfficialVo.getUrgency());
        schoolOfficial.setRemarks(schoolOfficialVo.getRemarks());
        schoolOfficial.setState(schoolOfficialVo.getState());
        schoolOfficialMapper.updateById(schoolOfficial);
        if (schoolOfficialMapper.updateById(schoolOfficial) == 1){
            schoolOfficialFlow.setOfficialId(schoolOfficialVo.getOfficialId());
            schoolOfficialFlow.setReceiveUser(schoolOfficialVo.getReceiveUser());
            schoolOfficialFlow.setOpinion(schoolOfficialVo.getOpinion());
            schoolOfficialFlow.setReceiveType(schoolOfficialVo.getReceiveType());
            return schoolOfficialFlowMapper.updateById(schoolOfficialFlow);
        }else {
            return 0;
        }
    }


    /**
     * 根据用户id查询
     *
     * @param id
     * @return
     */
    @Override
    public List<SchoolOfficial> selectListById(Long id) {
        LambdaQueryWrapper<SchoolOfficialFlow> lqw = new LambdaQueryWrapper<>();
        lqw
                .eq(SchoolOfficialFlow::getReceiveUser, id)
                .eq(SchoolOfficialFlow::getReceiveType, 0);
        SchoolOfficialFlow schoolOfficialFlow = schoolOfficialFlowMapper.selectOne(lqw);
        Long UserId = schoolOfficialFlow.getOfficialId();
        LambdaQueryWrapper<SchoolOfficial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SchoolOfficial::getId, UserId);
        List<SchoolOfficial> list = schoolOfficialMapper.selectList(lambdaQueryWrapper);
        return list;
    }

    /**
     * 修改时存储
     * @param schoolOfficialVo
     * @return
     */
    @Override
    public int storage(SchoolOfficialVo schoolOfficialVo) {
        SchoolOfficial schoolOfficial = new SchoolOfficial();
        BeanUtils.copyProperties(schoolOfficialVo, schoolOfficial);
        schoolOfficial.update();
        if (schoolOfficialMapper.updateById(schoolOfficial) > 0) {
            //存附件信息到文件表,修改时存在删除文件，没有文件，新增文件等多种情况，所以在修改的暂存或发文时，对附件先删后增
            LambdaQueryWrapper<PubFile> del = new LambdaQueryWrapper<>();
            del.eq(PubFile::getYwid,schoolOfficialVo.getId());
            pubFileMapper.delete(del);
            List<PubFile> fileList = schoolOfficialVo.getFileList();
            if(fileList!=null) {
                Long id = schoolOfficial.getId();
                for (PubFile pubFile : fileList) {
                    pubFile.setYwid(id);
                    pubFile.setMkmc(MKMC);
                    pubFile.setCreateTime(DateUtils.getNowDate());
                    pubFile.setUpdateTime(DateUtils.getNowDate());
                    pubFileMapper.insert(pubFile);
                }
            }
            //判断批阅人是否更换
            LambdaQueryWrapper<SchoolOfficialFlow> lqw = new LambdaQueryWrapper<>();
            lqw
                    .eq(SchoolOfficialFlow::getOfficialId,schoolOfficialVo.getId())
                    .eq(SchoolOfficialFlow::getReceiveType,REVIEWER);
            //查询出新增暂存时的批阅人
            SchoolOfficialFlow flow = schoolOfficialFlowMapper.selectOne(lqw);
            //没有更换
            if(flow.getReceiveUser().equals(schoolOfficialVo.getReceiveUser())){
                return 1;
            }
            //更换
            flow.setReceiveUser(schoolOfficialVo.getReceiveUser());
            return schoolOfficialFlowMapper.updateById(flow);
        }
        return 0;
    }

    /**
     * 新增时暂存
     * */
    @Override
    public int addStorage(SchoolOfficialVo schoolOfficialVo) {
        SchoolOfficial schoolOfficial = new SchoolOfficial();
        //将schoolOfficialVo的值copy到schoolOffical
        BeanUtils.copyProperties(schoolOfficialVo, schoolOfficial);
        schoolOfficial.insert();
        //新增，暂存成功
        if(schoolOfficialMapper.insert(schoolOfficial) > 0){
            //存附件信息到文件表
            List<PubFile> fileList = schoolOfficialVo.getFileList();
            if(fileList!=null){
                Long id = schoolOfficial.getId();
                for (PubFile pubFile : fileList) {
                    pubFile.setYwid(id);
                    pubFile.setMkmc(MKMC);
                    pubFile.setCreateTime(DateUtils.getNowDate());
                    pubFile.setUpdateTime(DateUtils.getNowDate());
                    pubFileMapper.insert(pubFile);
                }
            }

            SchoolOfficialFlow flow = new SchoolOfficialFlow();
            //设置批阅人
            flow.setOfficialId(schoolOfficial.getId());
            flow.setReceiveUser(schoolOfficialVo.getReceiveUser());
            flow.setReceiveType(REVIEWER);

            return schoolOfficialFlowMapper.insert(flow);
        }
        //新增暂存失败
        return 0;
    }

    /**
     * 新增时发文
     * */
    @Override
    public int addMessage(SchoolOfficialVo schoolOfficialVo) {
        SchoolOfficial schoolOfficial = new SchoolOfficial();
        BeanUtils.copyProperties(schoolOfficialVo, schoolOfficial);
        schoolOfficial.insert();
        //新增时，发文成功
        if(schoolOfficialMapper.insert(schoolOfficial) > 0){
            //存附件信息到文件表
            List<PubFile> fileList = schoolOfficialVo.getFileList();
            if(fileList!=null){
                Long id = schoolOfficial.getId();
                for (PubFile pubFile : fileList) {
                    pubFile.setYwid(id);
                    pubFile.setMkmc(MKMC);
                    pubFile.setCreateTime(DateUtils.getNowDate());
                    pubFile.setUpdateTime(DateUtils.getNowDate());
                    pubFileMapper.insert(pubFile);
                }
            }
            //新增批阅人
            SchoolOfficialFlow flow1 = new SchoolOfficialFlow();
            flow1.setOfficialId(schoolOfficial.getId());
            flow1.setReceiveUser(schoolOfficialVo.getReceiveUser());
            flow1.setReceiveTime(DateUtils.getNowDate());
            flow1.setReceiveType(REVIEWER);
            flow1.setState(UNDONE);
            schoolOfficialFlowMapper.insert(flow1);
            //新增发起人
            SchoolOfficialFlow flow2 = new SchoolOfficialFlow();
            flow2.setOfficialId(schoolOfficial.getId());
            flow2.setReceiveUser(getUserId());
            flow2.setReceiveType(INITIATOR);
            return schoolOfficialFlowMapper.insert(flow2);
        }
        //新增时，发文失败
        return 0;
    }

    /**
     * 修改时发文
     * */
    @Override
    public int editMessage(SchoolOfficialVo schoolOfficialVo) {
        SchoolOfficial schoolOfficial = new SchoolOfficial();
        BeanUtils.copyProperties(schoolOfficialVo, schoolOfficial);
        schoolOfficial.update();
        if (schoolOfficialMapper.updateById(schoolOfficial) > 0) {
            //存附件信息到文件表
            List<PubFile> fileList = schoolOfficialVo.getFileList();
            //存附件信息到文件表,修改时存在删除文件，没有文件，新增文件等多种情况，所以在修改的暂存或发文时，对附件先删后增
            LambdaQueryWrapper<PubFile> del = new LambdaQueryWrapper<>();
            del.eq(PubFile::getYwid,schoolOfficialVo.getId());
            pubFileMapper.delete(del);
            if(fileList!=null){
                Long id = schoolOfficial.getId();
                for (PubFile pubFile : fileList) {
                    pubFile.setYwid(id);
                    pubFile.setMkmc(MKMC);
                    pubFile.setCreateTime(DateUtils.getNowDate());
                    pubFile.setUpdateTime(DateUtils.getNowDate());
                    pubFileMapper.insert(pubFile);
                }
            }
            //判断批阅人是否更换
            LambdaQueryWrapper<SchoolOfficialFlow> lqw = new LambdaQueryWrapper<>();
            lqw
                    .eq(SchoolOfficialFlow::getOfficialId,schoolOfficialVo.getId())
                    .eq(SchoolOfficialFlow::getReceiveType,REVIEWER);
            //查询出暂存时的批阅人
            SchoolOfficialFlow flow1 = schoolOfficialFlowMapper.selectOne(lqw);
            //没有更换
            if(flow1.getReceiveUser().equals(schoolOfficialVo.getReceiveUser())){
                flow1.setReceiveTime(DateUtils.getNowDate());
                flow1.setState(UNDONE);
            }else{
                //更换
                flow1.setReceiveUser(schoolOfficialVo.getReceiveUser());
                flow1.setReceiveTime(DateUtils.getNowDate());
                flow1.setState(UNDONE);
            }
            schoolOfficialFlowMapper.updateById(flow1);

            //新增发起人
            SchoolOfficialFlow flow2 = new SchoolOfficialFlow();
            flow2.setOfficialId(schoolOfficial.getId());
            flow2.setReceiveUser(getUserId());
            flow2.setReceiveType(INITIATOR);
            return schoolOfficialFlowMapper.insert(flow2);
        }
        return 0;
    }

    //列表页发文
    @Override
    public int pub(Long id) {
        LambdaUpdateWrapper<SchoolOfficial> luw = new LambdaUpdateWrapper<>();
        luw.eq(SchoolOfficial::getId,id).set(SchoolOfficial::getState,FLOW);
        if(schoolOfficialMapper.update(null,luw) > 0){
            LambdaQueryWrapper<SchoolOfficialFlow> sof = new LambdaQueryWrapper<>();
            sof.eq(SchoolOfficialFlow::getOfficialId,id).eq(SchoolOfficialFlow::getReceiveType,REVIEWER);
            //批阅人
            SchoolOfficialFlow flow1 = schoolOfficialFlowMapper.selectList(sof).get(0);
            flow1.setReceiveTime(DateUtils.getNowDate());
            flow1.setState(UNDONE);
            schoolOfficialFlowMapper.updateById(flow1);

            //新增发起人
            SchoolOfficialFlow flow2 = new SchoolOfficialFlow();
            flow2.setOfficialId(id);
            flow2.setReceiveUser(getUserId());
            flow2.setReceiveType(INITIATOR);
            return schoolOfficialFlowMapper.insert(flow2);
        }
        //发文失败
        return 0;
    }

    @Override
    public int integration(SchoolOfficial schoolOfficial, SchoolOfficialFlow schoolOfficialFlow) {
        return 0;
    }

    //首页，我的任务
    @Override
    public List<SchoolOfficialVo> myTaskList(Long userId, String state, SchoolOfficial schoolOfficial) {
        List<SchoolOfficialVo> list = schoolOfficialMapper.myTaskList(userId,state, schoolOfficial);
        for(SchoolOfficialVo vo : list){
            LambdaQueryWrapper<PubFile> lqw = new LambdaQueryWrapper<>();
            lqw.eq(PubFile::getYwid,vo.getId()).eq(PubFile::getMkmc,MKMC);
            List<PubFile> pubFiles = pubFileMapper.selectList(lqw);
            if(StringUtils.isNotNull(pubFiles) || pubFiles.size() > 0){
                vo.setFileList(pubFiles);
            }
        }
        return list;
    }

    //判断所有传阅人是否都已查阅，若都，则将该公文状态改为已完结
    @Override
    public void judgeState(Long id) {
        LambdaQueryWrapper<SchoolOfficialFlow> lqw = new LambdaQueryWrapper<>();
        lqw
                .eq(SchoolOfficialFlow::getOfficialId,id)
                .eq(SchoolOfficialFlow::getReceiveType,CIRCULATOR);
        //查询出所有传阅人
        List<SchoolOfficialFlow> list = schoolOfficialFlowMapper.selectList(lqw);
        int num = 0;
        for(SchoolOfficialFlow flow : list){
            if(flow.getState().equals(DONE)){
                num++;
            }
        }

        if(num == list.size()){
            SchoolOfficial offical = schoolOfficialMapper.selectById(id);
            offical.setState(FINISH);
            schoolOfficialMapper.updateById(offical);
        }
    }

    //获取带附件的详情
    @Override
    public SchoolOfficialVo getInfo(Long id) {
        //return schoolOfficialMapper.getInfo(id,MKMC);
        SchoolOfficialVo vo = new SchoolOfficialVo();
        SchoolOfficial official = schoolOfficialMapper.selectById(id);
        BeanUtils.copyProperties(official,vo);

        //获取修改时选择批阅人id 姓名
        LambdaQueryWrapper<SchoolOfficialFlow> sof = new LambdaQueryWrapper<>();
        sof.eq(SchoolOfficialFlow::getOfficialId,id).eq(SchoolOfficialFlow::getReceiveType,REVIEWER);
        Long userId = schoolOfficialFlowMapper.selectList(sof).get(0).getReceiveUser();
        vo.setReceiveUser(userId);
        SysUser user = userMapper.selectUserById(userId);
        vo.setUserName(user.getUserName());
        //获取附件
        LambdaQueryWrapper<PubFile> lqw = new LambdaQueryWrapper<>();
        lqw.eq(PubFile::getYwid,official.getId()).eq(PubFile::getMkmc,MKMC);
        List<PubFile> pubFiles = pubFileMapper.selectList(lqw);
        if(StringUtils.isNotNull(pubFiles) || pubFiles.size() > 0){
            vo.setFileList(pubFiles);
        }
        return vo;
    }
}
