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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yangtz.cs.liu.campus.domain.schooloffical.SchoolOfficial;
import yangtz.cs.liu.campus.domain.schooloffical.SchoolOfficialFlow;
import yangtz.cs.liu.campus.domain.temp.OfficalTemplate;
import yangtz.cs.liu.campus.mapper.schooloffical.SchoolOfficialFlowMapper;
import yangtz.cs.liu.campus.mapper.schooloffical.SchoolOfficialMapper;
import yangtz.cs.liu.campus.mapper.teacher.SchoolTeacherMapper;
import yangtz.cs.liu.campus.service.schooloffical.ISchoolOfficalService;
import yangtz.cs.liu.campus.service.schooloffical.ISchoolOfficialFlowService;
import yangtz.cs.liu.campus.vo.schoolOfficial.SchoolOfficialFlowVo;
import yangtz.cs.liu.wechat.service.api.IWxApiService;

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

import static yangtz.cs.liu.campus.constant.OfficalConstant.*;

@Service
public class ISchoolOfficialFlowImpl extends ServiceImpl<SchoolOfficialFlowMapper, SchoolOfficialFlow> implements ISchoolOfficialFlowService {

    @Autowired
    private SchoolOfficialFlowMapper schoolOfficialFlowMapper;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IWxApiService wxApiService;

    @Autowired
    private SchoolOfficialMapper officialMapper;

    @Autowired
    private SchoolTeacherMapper teacherMapper;

    @Override
    public boolean flow(SchoolOfficialFlow schoolOfficialFlow) {

 //       schoolOfficialFlowMapper.

        return true;
    }

    @Override
    public int updateSchoolOfficialFlow(SchoolOfficialFlow schoolOfficialFlow) {

        return schoolOfficialFlowMapper.updateById(schoolOfficialFlow);
    }

    //根据主表id选择状态为已完成的子表信息
    @Override
    public List<SchoolOfficialFlowVo> getReviewList(Long id) {
        return schoolOfficialFlowMapper.getDoneList(id,DONE);
    }

    //修改批阅人意见，状态等
    @Override
    public int review(SchoolOfficialFlow flow) {
        //获取要修改的批阅人详情
        LambdaQueryWrapper<SchoolOfficialFlow> lqw = new LambdaQueryWrapper<>();
        lqw
                .eq(SchoolOfficialFlow::getOfficialId,flow.getOfficialId())
                .eq(SchoolOfficialFlow::getReceiveType,flow.getReceiveType())
                .eq(SchoolOfficialFlow::getReceiveUser,flow.getReceiveUser())
                .eq(SchoolOfficialFlow::getState,flow.getState())
                ;
        SchoolOfficialFlow entity = schoolOfficialFlowMapper.selectList(lqw).get(0);

        //添加意见，完成时间，修改该条数据的状态为已完成
        entity.setOpinion(flow.getOpinion());
        entity.setState(DONE);
        entity.setFinishTime(DateUtils.getNowDate());
        if(schoolOfficialFlowMapper.updateById(entity) > 0){
            //批阅人操作完成，流转到发起人
            LambdaQueryWrapper<SchoolOfficialFlow> init  = new LambdaQueryWrapper<>();
            init.eq(SchoolOfficialFlow::getOfficialId,flow.getOfficialId())
                    .eq(SchoolOfficialFlow::getReceiveType,INITIATOR);
            //获取发起人
            SchoolOfficialFlow initiator = schoolOfficialFlowMapper.selectList(init).get(0);
            initiator.setReceiveTime(DateUtils.getNowDate());
            initiator.setState(UNDONE);
            int num = schoolOfficialFlowMapper.updateById(initiator);

            /******* 需要发送模板消息到 发起人 ******/
            OfficalTemplate template = new OfficalTemplate();
            template.setFirst("您好，您有一个新的公文需要处理");
            //String openId = userService.getOpenIdByUserId(initiator.getReceiveUser());
            String openId = teacherMapper.getOpenIdByUserId(initiator.getReceiveUser());
            template.setToUserOpenId(openId);
            //公文信息
            SchoolOfficial schoolOffical = officialMapper.selectById(flow.getOfficialId());
            template.setTitle(schoolOffical.getIssuedName());
            template.setFinishTime(schoolOffical.getDeadline());
            template.setContent("请选择批阅人或传阅人");
            template.setRemark("请您前往电脑端进行处理");
            String s = wxApiService.sendOfficalTemplate(template);
            return num;
        }
        return 0;
    }

    /**
     * 根据未发文主表id，查询其批阅人
     * */
    @Override
    public SchoolOfficialFlow getReviewByOfficialId(Long officialId, String receiveType) {
        LambdaQueryWrapper<SchoolOfficialFlow> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolOfficialFlow::getOfficialId,officialId).eq(SchoolOfficialFlow::getReceiveType,receiveType);
        return schoolOfficialFlowMapper.selectOne(lqw);
    }

    //发起人操作
    @Override
    public int chooseReview(Long id, Long userId, Long[] userIds) {
        //公文信息
        SchoolOfficial schoolOffical = officialMapper.selectById(id);
        //批阅人不为空
        if(StringUtils.isNotNull(userId)){
            SchoolOfficialFlow flow = new SchoolOfficialFlow();
            flow.setOfficialId(id);
            flow.setReceiveUser(userId);
            flow.setReceiveTime(DateUtils.getNowDate());
            flow.setReceiveType(REVIEWER);
            flow.setState(UNDONE);
            if(schoolOfficialFlowMapper.insert(flow) > 0){
                /******* 需要发送模板消息到 批阅人 ******/
                OfficalTemplate template = new OfficalTemplate();
                template.setFirst("您好，您有一个新的公文需要批阅");
                //String openId = userService.getOpenIdByUserId(userId);
                String openId = teacherMapper.getOpenIdByUserId(userId);
                template.setToUserOpenId(openId);
                //公文信息
                template.setTitle(schoolOffical.getIssuedName());
                template.setFinishTime(schoolOffical.getDeadline());
                template.setContent("请领导批阅");
                template.setRemark("请您前往电脑端进行处理");
                String s = wxApiService.sendOfficalTemplate(template);
                return editInitiator(id);
            }
        }

        //批阅人为空，传阅人不为空
        int num = 0;
        for(Long user : userIds){
            SchoolOfficialFlow circulator = new SchoolOfficialFlow();
            circulator.setOfficialId(id);
            circulator.setReceiveUser(user);
            circulator.setReceiveTime(DateUtils.getNowDate());
            circulator.setReceiveType(CIRCULATOR);
            circulator.setState(UNDONE);
           if(schoolOfficialFlowMapper.insert(circulator) > 0){
               num++;
               /******* 需要发送模板消息到 传阅人 ******/
               OfficalTemplate template = new OfficalTemplate();
               template.setFirst("您好，您有一个新的公文需要查看");
               //String openId = userService.getOpenIdByUserId(user);
               String openId = teacherMapper.getOpenIdByUserId(user);
               template.setToUserOpenId(openId);
               //公文信息
               template.setTitle(schoolOffical.getIssuedName());
               template.setFinishTime(schoolOffical.getDeadline());
               template.setContent("请查看");
               template.setRemark("请您前往电脑端进行查看");
               String s = wxApiService.sendOfficalTemplate(template);
           }
        }
        if(userIds.length == num){
            return editInitiator(id);
        }
        //失败
        return 0;
    }

    //修改传阅人状态
    @Override
    public int editState(Long id, Long userId, String receiveType) {
        LambdaQueryWrapper<SchoolOfficialFlow> lqw = new LambdaQueryWrapper<>();
        lqw
                .eq(SchoolOfficialFlow::getOfficialId,id)
                .eq(SchoolOfficialFlow::getReceiveUser,userId)
                .eq(SchoolOfficialFlow::getReceiveType,receiveType)
                ;
        SchoolOfficialFlow flow = schoolOfficialFlowMapper.selectOne(lqw);
        flow.setState(DONE);
        flow.setOpinion("已阅");
        flow.setFinishTime(DateUtils.getNowDate());
        return schoolOfficialFlowMapper.updateById(flow);
    }

    //发起人操作后，修改发起人那条数据状态
    public int editInitiator(Long id){
        //修改发起人状态
        LambdaQueryWrapper<SchoolOfficialFlow> init  = new LambdaQueryWrapper<>();
        init.eq(SchoolOfficialFlow::getOfficialId,id)
                .eq(SchoolOfficialFlow::getReceiveType,INITIATOR);
        //获取发起人
        SchoolOfficialFlow initiator = schoolOfficialFlowMapper.selectList(init).get(0);
        initiator.setFinishTime(DateUtils.getNowDate());
        initiator.setState(DONE);
        return schoolOfficialFlowMapper.updateById(initiator);
    }
}
