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.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
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.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
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.domain.temp.OfficalTemplate;
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.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.dingding.utils.DingMessageUtils;
import yangtz.cs.liu.dingding.vo.DingMessageVo;
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;

    @Autowired
    private DingMessageUtils dingMessageUtils;

    @Value("${dd.message-uri}")
    private String messageUrl;

    @Value("${dd.pc-message-uri}")
    private String pcMessageUrl;

    @Autowired
    private PubFileMapper pubFileMapper;

    @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);

            /******* 需要发送模板消息到 发起人 ******/

            //获取钉钉用户id
            String ddUserId = teacherMapper.getDdUserIdByUserId(initiator.getReceiveUser());

            OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
            msg.setOa(new OapiMessageCorpconversationAsyncsendV2Request.OA());
            msg.getOa().setHead(new OapiMessageCorpconversationAsyncsendV2Request.Head());
            msg.getOa().getHead().setText("text");
            msg.getOa().getHead().setBgcolor("FF4BB3F9");
            msg.getOa().setBody(new OapiMessageCorpconversationAsyncsendV2Request.Body());
            msg.getOa().getBody().setAuthor("");
            msg.getOa().getBody().setContent("请您及时处理");
            msg.getOa().getBody().setTitle("您好，您有一个新的公文需要处理");
            msg.getOa().setPcMessageUrl(pcMessageUrl);
            msg.getOa().setMessageUrl(messageUrl);
            msg.setMsgtype("oa");
            DingMessageVo messageVo = new DingMessageVo();
            messageVo.setMsg(msg);
            messageVo.setToAllUser(false);
            messageVo.setUseridList(ddUserId);
            dingMessageUtils.sendMessage(messageVo);

//            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){
                /******* 需要发送模板消息到 批阅人 ******/

                //获取钉钉用户id
                String ddUserId = teacherMapper.getDdUserIdByUserId(userId);

                OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
                msg.setOa(new OapiMessageCorpconversationAsyncsendV2Request.OA());
                msg.getOa().setHead(new OapiMessageCorpconversationAsyncsendV2Request.Head());
                msg.getOa().getHead().setText("text");
                msg.getOa().getHead().setBgcolor("FF4BB3F9");
                msg.getOa().setBody(new OapiMessageCorpconversationAsyncsendV2Request.Body());
                msg.getOa().getBody().setAuthor("");
                msg.getOa().getBody().setContent("请您及时批阅");
                msg.getOa().getBody().setTitle("您好，您有一个新的公文需要批阅");
                msg.getOa().setPcMessageUrl(pcMessageUrl);
                msg.getOa().setMessageUrl(messageUrl);
                msg.setMsgtype("oa");
                DingMessageVo messageVo = new DingMessageVo();
                messageVo.setMsg(msg);
                messageVo.setToAllUser(false);
                messageVo.setUseridList(ddUserId);
                dingMessageUtils.sendMessage(messageVo);

//                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++;
               /******* 需要发送模板消息到 传阅人 ******/

               //获取钉钉用户id
               String ddUserId = teacherMapper.getDdUserIdByUserId(user);

               OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
               msg.setOa(new OapiMessageCorpconversationAsyncsendV2Request.OA());
               msg.getOa().setHead(new OapiMessageCorpconversationAsyncsendV2Request.Head());
               msg.getOa().getHead().setText("text");
               msg.getOa().getHead().setBgcolor("FF4BB3F9");
               msg.getOa().setBody(new OapiMessageCorpconversationAsyncsendV2Request.Body());
               msg.getOa().getBody().setAuthor("");
               msg.getOa().getBody().setContent("请您及时查看");
               msg.getOa().getBody().setTitle("您好，您有一个新的公文需要查看");
               msg.getOa().setPcMessageUrl(pcMessageUrl);
               msg.getOa().setMessageUrl(messageUrl);
               msg.setMsgtype("oa");
               DingMessageVo messageVo = new DingMessageVo();
               messageVo.setMsg(msg);
               messageVo.setToAllUser(false);
               messageVo.setUseridList(ddUserId);
               dingMessageUtils.sendMessage(messageVo);

//               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);
    }

    /**
     * 修改附件
     * @param pubFile
     * @return
     */
    @Override
    public int updateFile(PubFile pubFile) {
        return pubFileMapper.updateById(pubFile);
    }

    //发起人操作后，修改发起人那条数据状态
    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);
    }
}
