package com.pqs9900.controller.message;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.njcn.enums.LogTypeEnum;
import com.njcn.pojo.commons.DatePojo;
import com.njcn.pojo.commons.HttpResult;
import com.njcn.pojo.commons.RedisDB;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.PubUtils;
import com.njcn.utils.SerializeUtil;
import com.njcn.utils.XssFilterUtil;
import com.njcn.utils.redis.JedisManager;
import com.pqs9900.pojo.message.MsgBaseConfDTO;
import com.pqs9900.pojo.message.MsgInfoDTO;
import com.pqs9900.pojo.message.MsgTemplateData;
import com.pqs9900.pojo.message.MsgTypeTemplateDTO;
import com.pqs9900.service.message.MessageService;
import com.pqs9900.service.message.SendMessageService;
import com.pqs9900.task.SendMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/message")
public class MessageController {
    private static final Logger logger = LoggerFactory.getLogger(MessageController.class);

    @Autowired
    private MessageService messageService;

    @Autowired
    private SendMessageService sendMessageService;

    @Autowired
    private SendMessage sendMessage;

    @Autowired
    JedisManager jedisManager;
    
    @PostMapping("test")
    public void test() {
        sendMessage.stop();
        sendMessage.start(sendMessage.getTaskRegistrar());
    }

    @PostMapping("sendMsg")
    @ResponseBody
    public HttpResult sendMsg(@RequestParam("msg") String msg, @RequestParam("phone") String phone) {
        HttpResult httpResult = new HttpResult();
        //正则校验
        if (!PubUtils.patternPhone(phone)) {
            httpResult.setMessage("手机格式不正确");
            httpResult.setCode(500);
            httpResult.setBody(null);
            return httpResult;
        }

        //xss处理
        msg = XssFilterUtil.dealString(msg);

        try {
            String res = messageService.sendMsg(msg, phone, null,null,null,0,null);
            if("发送成功".equals(res)){
                httpResult.setBody(null);
                httpResult.setCode(200);
                httpResult.setMessage(res);
            }else {
                httpResult.setBody(null);
                httpResult.setCode(500);
                httpResult.setMessage(res);
            }

        } catch (Exception e) {
            httpResult.setBody(null);
            httpResult.setCode(500);
            httpResult.setMessage(e.toString());
        }

        return httpResult;
    }

    /**
     * @Author chendaofei
     * @Description 获取短信基本配置
     * @Date 9:34 2020/5/14
     **/
    @GetMapping("getMsgConfig")
    @ResponseBody
    public HttpResult getMsgConfig() {
            MsgBaseConfDTO msgConfig = messageService.getMsgConfig();
            if (msgConfig != null) {
                return PubUtils.assignmentResult(msgConfig, 200, "获取短信基本配置成功");
            }else {
                return PubUtils.assignmentResult(null, 500, "暂无配置");
            }
    }

    /**
     * @Author chendaofei
     * @Description 更新短信基本配置
     * @Date 9:34 2020/5/14
     **/
    @PostMapping("updateMsgCofig")
    @ResponseBody
    public HttpResult updateMsgCofig(@RequestBody MsgBaseConfDTO msgBaseConfDTO) {
        try{
            if(msgBaseConfDTO.getIsSend()==null|| msgBaseConfDTO.getTimeInterval()==null||msgBaseConfDTO.getOffDay()==null||msgBaseConfDTO.getList()==null){
                return PubUtils.assignmentResult(null,500,"参数不可为空");
            }
            sendMessageService.updateMsgCofig(msgBaseConfDTO);
        }catch (Exception e){
            return PubUtils.assignmentResult(null,500,"配置失败");
        }
       return PubUtils.assignmentResult(null,200,"配置成功");
    }

    /**
     * @Author chendaofei
     * @Description 获取短信类型模板及时间模板
     * @Date 9:35 2020/5/14
     **/
    @GetMapping("getMsgDicdataList")
    @ResponseBody
    public HttpResult getMsgDicdataList() {
        List<MsgTypeTemplateDTO> list = new ArrayList<>();
        try {
            list = messageService.getMsgDicdataList();
            return PubUtils.assignmentResult(list, 200, "获取短信配置模板成功");
        } catch (Exception e) {
            return PubUtils.assignmentResult(null, 500, "获取失败");
        }
    }

    /**
     * @Author chendaofei
     * @Description 删除模板
     * @Date 9:36 2020/5/14
     **/
    @GetMapping("delMsgDicBytype")
    @ResponseBody
    public HttpResult delMsgDicBytype(HttpServletRequest request,String msgIndex) {
    	HttpResult result = new HttpResult();
        if (PubUtils.isBlank(msgIndex)) {
        	result = PubUtils.assignmentResult(null, 500, "参数不可为空");
        }
        String ip = PubUtils.getIpAddr(request);
        String username = TokenManager.getToken().getLoginName();

        byte[] value = jedisManager.getValueByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(username + ip));
        String key = SerializeUtil.deserialize(value, String.class);
        if(key.equals("success")){
            Integer res = messageService.delMsgDicBytype(msgIndex);
            if (res == 1) {
            	result = PubUtils.assignmentResult(null, 200, "删除成功!");
            }else{
            	result = PubUtils.assignmentResult(null, 500, "删除失败!");
            }
        }else{
        	result = PubUtils.assignmentResult(null, 500, "删除失败!密码验证失败");
        }

        jedisManager.deleteByKey(RedisDB.SHORT_TIME_QUERY, SerializeUtil.serialize(username + ip));
        return result;
    }

    /**
     * @Author chendaofei
     * @Description 更新短信模板是否启用
     * @Date 9:36 2020/5/14
     **/
    @PostMapping("updateMsgDicState")
    @ResponseBody
    public HttpResult updateMsgDicState(List<String> list) {
        HttpResult httpResult;
        try{
            String res = messageService.updateMsgDicState(list);
            if ("配置成功".equals(res)) {
                httpResult = PubUtils.assignmentResult(null, 200, res);
            }else {
                httpResult = PubUtils.assignmentResult(null, 500, "配置失败");
            }
        }catch (Exception e){
            httpResult = PubUtils.assignmentResult(null, 500, "配置失败");
        }
        return httpResult;
    }

    /**
     * @Author chendaofei
     * @Description 添加类型时间模板
     * @Date 9:37 2020/5/14
     **/
    @PostMapping("addMsgDicdata")
    @ResponseBody
    public HttpResult addMsgDicdata(Integer msgType, BigDecimal value1, BigDecimal value2, String msgName) {
        if (msgType == null || value1 == null || value2 == null || PubUtils.isBlank(msgName)) {
            return PubUtils.assignmentResult(null, 500, "参数不可为空");
        }
        if (value1.compareTo(value2) >= 0) {
            return PubUtils.assignmentResult(null, 500, "最小临界值不可大于等于最终临界值");
        }
        if (msgType == 1) {
            //时间模板
            if (new BigDecimal(value1.intValue()).compareTo(value1) != 0 || new BigDecimal(value2.intValue()).compareTo(value2) != 0) {
                return PubUtils.assignmentResult(null, 500, "时间格式有误");
            }
        }
        //xss
        msgName = XssFilterUtil.dealString(msgName);
        MsgTypeTemplateDTO msgTypeTemplateDTO = new MsgTypeTemplateDTO();
        msgTypeTemplateDTO.setMsgIndex(UUID.randomUUID().toString());
        msgTypeTemplateDTO.setMsgType(msgType);
        msgTypeTemplateDTO.setMsgName(msgName);
        msgTypeTemplateDTO.setValue1(value1);
        msgTypeTemplateDTO.setValue2(value2);
        try {
            String res = messageService.addMsgDicdata(msgTypeTemplateDTO);
            if ("添加成功".equals(res)) {
                return PubUtils.assignmentResult(null, 200, res);
            } else {
                return PubUtils.assignmentResult(null, 500, res);
            }
        } catch (Exception e) {
            return PubUtils.assignmentResult(null, 500, "添加失败,请联系管理员");
        }
    }

    /**
     * @Author chendaofei
     * @Description 查询短信信息列表
     * @Date 9:22 2020/5/20
     **/
    @GetMapping("getAllMsgList")
    @ResponseBody
    public HttpResult getAllMsgList(@RequestParam(required = false, value = "type") Integer type, @RequestParam(value = "startTime", required = false) String startTime, @RequestParam(value = "endTime", required = false) String endTime) {
        HttpResult httpResult;
        DatePojo datePojo;
        datePojo = PubUtils.validateDate(startTime, endTime, "getAllMsgList");
        if (!datePojo.getValidity()) {
            httpResult = PubUtils.assignmentResult(null, 500, "解析前台传递的时间有误");
            return httpResult;
        }
        Date be =datePojo.getStartTime();
       Date en = datePojo.getEndTime();
        List<MsgInfoDTO> list = messageService.getAllMsgList(type,be ,en);
        return PubUtils.assignmentResult(list, 200, "获取成功");
    }

    /**
     * @Author chendaofei
     * @Description 删除已发短信
     * @Date 11:50 2020/5/21
     **/
    @PostMapping("deleteMsgList")
    @ResponseBody
    public HttpResult deleteMsgList(@RequestBody List<String> list) {
        if (list == null || list.size() == 0) {
            return PubUtils.assignmentResult(null, 500, "id不可为空");
        }
        Boolean flag = messageService.deleteMsgList(list);
        if (flag) {
            return PubUtils.assignmentResult(null, 200, "删除成功");
        }
        return PubUtils.assignmentResult(null, 500, "删除失败");
    }

}
