package com.hssx.cloudmodel.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hssx.cloudmodel.constant.Constant;
import com.hssx.cloudmodel.entity.*;
import com.hssx.cloudmodel.entity.vo.MouldEquipmentVO;
import com.hssx.cloudmodel.entity.vo.MouldVO;
import com.hssx.cloudmodel.entity.vo.ProjectVO;
import com.hssx.cloudmodel.entity.vo.UserVO;
import com.hssx.cloudmodel.mapper.*;
import com.hssx.cloudmodel.service.MouldService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hssx.cloudmodel.util.HttpKit;
import com.hssx.cloudmodel.util.HttpRespMsg;
import com.hssx.cloudmodel.util.ListUtil;
import com.hssx.cloudmodel.util.WechatTemplateMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
/**
 * 
 * 服务实现类
 * 
 *
 * @author 吴涛涛
 * @since 2019-07-30
 */
@Service
@Slf4j
public class MouldServiceImpl extends ServiceImpl implements MouldService {
    @Resource
    MouldMapper mouldMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    PowerMapper powerMapper;
    @Resource
    ProjectMapper projectMapper;
    @Resource
    ProjectApproveMapper projectApproveMapper;
    @Resource
    CustomCompanyMapper customCompanyMapper;
    @Resource
    CompanyMapper companyMapper;
    @Resource
    ProjectUserMapper projectUserMapper;
    @Resource
    NewsNoticeMapper newsNoticeMapper;
    @Resource
    NewsNoticeUserMapper newsNoticeUserMapper;
    @Override
    public HttpRespMsg addAndUpdateMould(Mould mould, User user) {
        HttpRespMsg msg = new HttpRespMsg();
        if (mould.getId() != null) {
            //修改
            Mould m = mouldMapper.selectOne(new QueryWrapper().eq("model_no", mould.getModelNo()));
            if ((m != null && m.getId() == mould.getId()) || m == null) {
                Company company = companyMapper.selectById(mould.getProduceCompanyId());
                mould.setArea(company.getCompanyAddress());
                mouldMapper.updateById(mould);
            } else {
                msg.setError("当前模具编号已存在,请重新输入其他模具编号");
            }
        } else {
            //查询当前模具编号的模具是否存在
            Integer count = mouldMapper.selectCount(new QueryWrapper().eq("model_no", mould.getModelNo()));
            if (count > 0) {
                msg.setError("当前模具编号已存在,请重新输入其他模具编号");
            } else {
                mould.setCreatorId(user.getId());
                mould.setCompanyId(user.getCompanyId());
                mouldMapper.insert(mould);
            }
        }
        return msg;
    }
    @Override
    public HttpRespMsg getMoildDetail(MouldVO mouldVO) {
        HttpRespMsg msg = new HttpRespMsg();
        Map map = new HashMap<>();
        MouldVO mould = mouldMapper.getDetailById(mouldVO);
        map.put("vo", mould);
        ProjectVO vo = projectMapper.getProjectById(mould.getProjectId());
        User currentUser = userMapper.selectOne(new QueryWrapper().eq("head_imgurl", mouldVO.getToken()));
        if (null == mould.getProjectId()) {
            map.put("update", 0);
            map.put("download", 0);
            map.put("view", 0);
            map.put("approve", 0);
        } else {
            List list = customCompanyMapper.selectList(new QueryWrapper().eq("project_id", mould.getProjectId()));
            map.put("customCompany", list);
            if (Constant.SYS_PARENT_ID == currentUser.getParentId()) {
                //当前人超级管理员 ,对项目只可以浏览
                map.put("update", 0);
                map.put("download", 0);
                map.put("view", 1);
                map.put("approve", 0);
            } else if (Constant.SYS_ID == currentUser.getParentId()) {
                //当前为系统管理员
                map.put("update", 1);
                map.put("download", 1);
                map.put("view", 1);
                map.put("approve", 0);
            } else if (vo.getManagerId() == currentUser.getId()) {
                //当前人是该项目的项目经理
                Integer approve = 0;
                if (projectApproveMapper.selectCount(new QueryWrapper().eq("approver_id", currentUser.getId())) > 0) {
                    //查看当前项目经理是否为审批人
                    approve = 1;
                }
                map.put("update", 1);
                map.put("download", 1);
                map.put("view", 1);
                map.put("approve", approve);
            } else {
                //该项目的参与人
                Integer update = 0;
                Integer download = 0;
                Integer view = 0;
                Integer approve = 0;
                List powers = powerMapper.selectList(new QueryWrapper().eq("project_id", mould.getProjectId()).eq("user_id", currentUser.getId()));
                if (powers.size() > 0) {
                    for (Power power : powers) {
                        if (power.getPowerType() == 0) {
                            update = 1;
                        } else if (power.getPowerType() == 1) {
                            download = 1;
                        } else if (power.getPowerType() == 2) {
                            view = 1;
                        } else {
                            approve = 1;
                        }
                    }
                }
                map.put("update", update);
                map.put("download", download);
                map.put("view", view);
                map.put("approve", approve);
            }
        }
        msg.data = map;
        return msg;
    }
    @Override
    public HttpRespMsg maintenanceReminder() throws Exception {
        HttpRespMsg msg = new HttpRespMsg();
        //查询所有被分配到项目的模具
        List moulds = mouldMapper.selectList(new QueryWrapper().isNotNull("project_id"));
        for (Mould mould : moulds) {
            List counts = ListUtil.convertIntegerIdsArrayToList(mould.getMaintainCount());
            Collections.sort(counts);
            Integer noticeCount = 0;
            if (counts.size() > 0) {
                for (Integer count : counts) {
                    if (count <= mould.getRunTimes()) {
                        noticeCount = count;
                    }
                }
            }
            if (noticeCount != 0) {
                //需要保养
                Mould m = new Mould();
                m.setId(mould.getId());
                m.setIsMaintain(1);
                mouldMapper.updateById(m);
//                //提示保养,向模具资产方人员公众号推送消息
//                User user = userMapper.selectOne(new QueryWrapper().eq("parent_id", Constant.SYS_ID).eq("company_id", mould.getCompanyId()));
//                MouldEquipmentVO mouldEquipmentVO = new MouldEquipmentVO();
//                mouldEquipmentVO.setPlanType(Constant.PLAN_TYPE);
//                mouldEquipmentVO.setArea(mould.getArea());
//                mouldEquipmentVO.setName(mould.getModelName());
//                msg = sendMaintainTemplateMessage(Constant.MAINTAIN_NOTICE_TEMPLATE_ID, user.getOpenid(), Constant.WECHAT_APPID, Constant.WECHAT_SECRET, mouldEquipmentVO);
                //添加通知消息
                Project project = projectMapper.selectById(mould.getProjectId());
                //查询到参与该项目的人
                List userIds = new ArrayList<>();
                userIds.add(project.getCreatorId());
                userIds.add(project.getManagerId());
                List projectUsers = projectUserMapper.selectList(new QueryWrapper().eq("project_id", project.getId()));
                for (ProjectUser projectUser : projectUsers) {
                    userIds.add(projectUser.getUserId());
                }
                List projectApproves = projectApproveMapper.selectList(new QueryWrapper().eq("project_id", project.getId()));
                for (ProjectApprove projectApprove : projectApproves) {
                    userIds.add(projectApprove.getApproverId());
                }
                List users = userMapper.selectList(new QueryWrapper().in("id", userIds));
                //查询到之前模具保养的消息
                NewsNotice oldNews = newsNoticeMapper.selectOne(new QueryWrapper().eq("ref_id", mould.getId()).eq("notice_type", 1));
                NewsNotice newsNotice = new NewsNotice();
                if(oldNews != null){
                    NewsNotice newNews = new NewsNotice();
                    newNews.setId(oldNews.getId());
                    oldNews.setIndate(LocalDateTime.now());
                    newsNoticeMapper.updateById(oldNews);
                    newsNoticeUserMapper.updateNewsNoticeUserByNewsNoticeId(oldNews.getId());
//                    for (User u : users) {
//                        //添加通知的消息
//                        NewsNoticeUser newsNoticeUser = new NewsNoticeUser();
//                        newsNoticeUser.setNewsId(oldNews.getId());
//                        newsNoticeUser.setUserId(u.getId());
//                        newsNoticeUser.setIsRead(0);
//                        newsNoticeUserMapper.updateById(newsNoticeUser);
//                    }
                }else{
                    newsNotice.setNoticeType(Constant.MAINTAIN_TYPE);
                    newsNotice.setProjectId(project.getId());
                    newsNotice.setProjectName(project.getProjectName());
                    newsNotice.setRefId(mould.getId());
                    newsNotice.setContent(Constant.MAIN_TAIN_NOTICE);
                    newsNoticeMapper.insert(newsNotice);
                    for (User u : users) {
                        //添加通知的消息
                        NewsNoticeUser newsNoticeUser = new NewsNoticeUser();
                        newsNoticeUser.setNewsId(newsNotice.getId());
                        newsNoticeUser.setUserId(u.getId());
                        newsNoticeUserMapper.insert(newsNoticeUser);
                    }
                }
            }
        }
        return msg;
    }
    @Override
    public HttpRespMsg delMoule(Mould mould) {
        HttpRespMsg msg = new HttpRespMsg();
        Mould newMould = mouldMapper.selectById(mould.getId());
        if (null != mould.getProjectId()) {
            msg.setError("该模具已被应用到项目,不提供删除操作");
        } else {
            mouldMapper.deleteById(newMould.getId());
        }
        return msg;
    }
    @Override
    public HttpRespMsg isMaintain(Mould mould) {
        HttpRespMsg msg = new HttpRespMsg();
        if (mould.getId() != null) {
            mouldMapper.updateById(mould);
        } else {
            msg.setError("模具id不存在");
        }
        return msg;
    }
    @Override
    public HttpRespMsg maintainMouldList(UserVO userVO) {
        return null;
    }
    //告警模板推送通用接口
    /**
     * templateId 模板id,touserOpenId 被推送者的openId,appId微信公众号的appId
     * firstData 推送标题
     */
    public HttpRespMsg sendEmergencyTemplateMessage(String templateId, String touserOpenId, String appId, String secret, MouldEquipmentVO mouldEquipmentVO) throws Exception {
        HttpRespMsg msg = new HttpRespMsg();
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + appId + "&secret=" + secret;
        String resp;
        String resp1;
        resp1 = HttpKit.get(url, true);
        resp1 = StringEscapeUtils.unescapeJava(resp1);
        JSONObject json = (JSONObject) JSON.parse(resp1);
        // 获取值赋值给全局变量
        if (!json.containsKey("errcode")) {
            String newAccessToken = json.getString("access_token");
            String url1 = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="
                    + newAccessToken;
            WechatTemplateMessage wechat = new WechatTemplateMessage();
            wechat.setTemplate_id(templateId);
            wechat.setTouser(touserOpenId);
            wechat.setAppid(appId);
            Map> data = new HashMap<>();
            Map first = new HashMap<>();
            Map value1 = new HashMap<>();
            Map value2 = new HashMap<>();
            Map value3 = new HashMap<>();
            Map value4 = new HashMap<>();
            Map remark = new HashMap<>();
            // 推送信息主体
            first.put("value", "告警通知");//firstData推送标题
            data.put("first", first);
            value1.put("value", mouldEquipmentVO.getEquipmentName());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            data.put("keyword1", value1);
            value2.put("value", mouldEquipmentVO.getEmergencyType());
            data.put("keyword2", value2);
            value3.put("value", sdf.format(new Date()));
            data.put("keyword3", value3);
            value4.put("value", mouldEquipmentVO.getEmergencyContent());
            data.put("keyword4", value4);
            remark.put("value", "请尽快检查该设备");
            data.put("remark", remark);
            wechat.setData(data);
            String jsonString = JSONObject.toJSONString(wechat);
            // System.out.println("jsonString"+jsonString);
            resp = HttpKit.post(url1, jsonString);
            // System.out.println("resp0"+resp);
            resp = StringEscapeUtils.unescapeJava(resp);
            // System.out.println("resp"+resp);
            json = (JSONObject) JSON.parse(resp);
        }
        return msg;
    }
    //保养
    /**
     * templateId 模板id,touserOpenId 被推送者的openId,appId微信公众号的appId
     * firstData 推送标题
     */
    public HttpRespMsg sendMaintainTemplateMessage(String templateId, String touserOpenId, String appId, String secret, MouldEquipmentVO mouldEquipmentVO) throws Exception {
        HttpRespMsg msg = new HttpRespMsg();
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                + appId + "&secret=" + secret;
        String resp;
        String resp1;
        resp1 = HttpKit.get(url, true);
        resp1 = StringEscapeUtils.unescapeJava(resp1);
        JSONObject json = (JSONObject) JSON.parse(resp1);
        // 获取值赋值给全局变量
        if (!json.containsKey("errcode")) {
            String newAccessToken = json.getString("access_token");
            String url1 = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="
                    + newAccessToken;
            WechatTemplateMessage wechat = new WechatTemplateMessage();
            wechat.setTemplate_id(templateId);
            wechat.setTouser(touserOpenId);
            wechat.setAppid(appId);
            Map> data = new HashMap<>();
            Map first = new HashMap<>();
            Map value1 = new HashMap<>();
            Map value2 = new HashMap<>();
            Map value3 = new HashMap<>();
            Map value4 = new HashMap<>();
            Map remark = new HashMap<>();
            // 推送信息主体
            first.put("value", "你好,你有新的保养通知");//firstData推送标题
            data.put("first", first);
            value1.put("value", mouldEquipmentVO.getEquipmentName());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
            data.put("keyword1", value1);
            value2.put("value", mouldEquipmentVO.getArea());
            data.put("keyword2", value2);
            value3.put("value", sdf.format(new Date()));
            data.put("keyword3", value3);
            value4.put("value", mouldEquipmentVO.getPlanType());
            data.put("keyword4", value4);
            remark.put("value", "模具初始模次不满足运行了");
            data.put("remark", remark);
            wechat.setData(data);
            String jsonString = JSONObject.toJSONString(wechat);
            // System.out.println("jsonString"+jsonString);
            resp = HttpKit.post(url1, jsonString);
            // System.out.println("resp0"+resp);
            resp = StringEscapeUtils.unescapeJava(resp);
            // System.out.println("resp"+resp);
            json = (JSONObject) JSON.parse(resp);
        }
        return msg;
    }
}