package com.xxl.job.executor.service.jobhandler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.executor.entity.LeaderMsg;
import com.xxl.job.executor.entity.Threads;
import com.xxl.job.executor.entity.json.LeaderInfoJson;
import com.xxl.job.executor.service.LeaderInfoJsonService;
import com.xxl.job.executor.service.LeaderMsgService;
import com.xxl.job.executor.service.ThreadsService;
import com.xxl.job.executor.util.Result;
import com.xxl.job.executor.util.SmsUtils;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Slf4j
@RestController
public class LeaderMsgXxlJob {

    @Resource
    private LeaderMsgService leaderMsgService;

    @Autowired
    private LeaderInfoJsonService leaderInfoJsonService;

    @Autowired
    private SmsUtils smsUtils;
    @Resource
    private ThreadsService threadsService;

    /**
     * 1、简单任务示例（Bean模式）
     */
    @XxlJob("HlbeLingDaoPaser")
    public void HlbeLingDaoPaser() throws Exception {
        List<Threads> threadsList = threadsService.list();
        //XxlJobHelper.log("获取到的参数列表："+threadsList.toString());
        for (Threads threads : threadsList) {
            boolean getdata = getdata(threads.getFid(),threads.getTypeId(),"");
            if (!getdata){
                XxlJobHelper.log("当前参数执行失败"+threads);
            }
            XxlJobHelper.log("领导人:"+threads.getName()+"留言任务执行成功");
        }
        return ;
    }

    /**
     * 1、定时更新领导人列表
     */
    @XxlJob("getAllLeaderInfoTask")
    public void getAllLeaderInfoTask() throws Exception {
        try {
            leaderInfoJsonService.getAllLeaderInfo(18);
        }catch (Exception e){
            e.printStackTrace();
        }
        return ;
    }

    /**
     * 2、定时更新领导人信箱
     */
    @XxlJob("getAllLeaderInfoMsg")
    public void getAllLeaderInfoMsg() throws Exception {
        List list = new ArrayList();
        list.add(5);//5 建言
        list.add(2);//2 投诉/求助
        list.add(1);//1 咨询
        for (int i = 0; i <list.size() ; i++) {
            Integer typeId = Integer.parseInt(list.get(i)+"");
            String lastItem = "";
            QueryWrapper<LeaderInfoJson> qw=new QueryWrapper<>();
            qw.eq("has_child",0);

            try {
                List<LeaderInfoJson> leaderInfoJsonList = leaderInfoJsonService.list(qw);
                for (LeaderInfoJson leaderInfoJson : leaderInfoJsonList) {
                    String fid = leaderInfoJson.getFid()+"";
                    List<LeaderMsg> leaderMsgs = leaderMsgService.getLeaderMsgInfo(fid, typeId, lastItem);
                    boolean b = true;
                    if(!ObjectUtils.isEmpty(leaderMsgs)){
                        for (LeaderMsg msg:leaderMsgs) {
                            msg.setCrtime(new Date(msg.getDateline()*1000));
                            if (leaderMsgService.getById(msg.getTid())==null){
                                msg.setStatus(0);
                                leaderMsgService.saveOrUpdate(msg);
                            }
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }
        return ;
    }

    /**
     * 3、定时更新孙绍骋\王莉霞信箱
     */
    @XxlJob("getSpecialLeaderInfoMsg")
    public void getSpecialLeaderInfoMsg() throws Exception {
        // param parse
        String param = XxlJobHelper.getJobParam();
        if (param==null || param.trim().length()==0) {
            XxlJobHelper.log("param["+ param +"] invalid.");
            XxlJobHelper.handleFail();
            return;
        }
        String[] fidArr = param.split(",");

        List list = new ArrayList();
        list.add(5);//5 建言
        list.add(2);//2 投诉/求助
        list.add(1);//1 咨询
        for (int i = 0; i <list.size() ; i++) {
            Integer typeId = Integer.parseInt(list.get(i)+"");
            String lastItem = "";
            QueryWrapper<LeaderInfoJson> qw=new QueryWrapper<>();
            qw.eq("has_child",0);
            qw.in("fid",fidArr);
            try {
                List<LeaderInfoJson> leaderInfoJsonList = leaderInfoJsonService.list(qw);
                for (LeaderInfoJson leaderInfoJson : leaderInfoJsonList) {
                    String fid = leaderInfoJson.getFid()+"";
                    List<LeaderMsg> leaderMsgs = leaderMsgService.getLeaderMsgInfo(fid, typeId, lastItem);
                    boolean b = true;
                    if(!ObjectUtils.isEmpty(leaderMsgs)){
                        for (LeaderMsg msg:leaderMsgs) {
                            msg.setCrtime(new Date(msg.getDateline()*1000));
                            if (leaderMsgService.getById(msg.getTid())==null){
                                msg.setStatus(0);
                                leaderMsgService.saveOrUpdate(msg);
                            }
                        }

//                        b = b && leaderMsgService.saveOrUpdateBatch(leaderMsgs);
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return ;
    }

    /**
     * 3、定时发短信
     */
    @XxlJob("sentSms")
    public void sentSms() throws Exception {
        // param parse
        String param = XxlJobHelper.getJobParam();
        if (param==null || param.trim().length()==0) {
            XxlJobHelper.log("param["+ param +"] invalid.");
            XxlJobHelper.handleFail();
            return;
        }

        try {
            String[] paramArr = param.split(";");
            String[] fidArr = paramArr[0].split(",");
            String[] mobileArr = paramArr[1].split(",");

            QueryWrapper<LeaderMsg> qw=new QueryWrapper<>();
            qw.eq("status",0);
            qw.in("fid",fidArr);
            List<LeaderMsg> listLeaderMsg = leaderMsgService.list(qw);
            if(!ObjectUtils.isEmpty(listLeaderMsg)){
                for (LeaderMsg leaderMsg : listLeaderMsg) {
                    String forumName = leaderMsg.getForumName();
                    Long tid = leaderMsg.getTid();
                    String typeName = leaderMsg.getTypeName();
                    for (int i = 0; i < mobileArr.length; i++) {
                        try {
                            String messageInfo = forumName+"收到一条"+typeName+"，详情查看http://liuyan.people.com.cn/threads/content?tid="+tid;
                            SendSmsResponse smsResponse = null;
                            smsResponse = smsUtils.sendSms(mobileArr[i],messageInfo,2);
                            String smsCode = smsResponse.getBody().getCode();
                            if("OK".equals(smsCode)){
                                log.info("sms sent success："+mobileArr[i]);
                                leaderMsg.setStatus(1);
                                leaderMsgService.saveOrUpdate(leaderMsg);
                            }else{
                                log.info("sms sent fail"+mobileArr[i]+",message："+messageInfo);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }

        return ;
    }


    @GetMapping("/getdata")
    public boolean getdata(String fid, int typeId, String lastItem){
        if (ObjectUtils.isEmpty(lastItem)){
            lastItem="";
        }
        List<LeaderMsg> leaderMsgs = leaderMsgService.getLeaderMsgInfo(fid, typeId, lastItem);

        boolean b = true;
        if(!ObjectUtils.isEmpty(leaderMsgs)){
            for (LeaderMsg msg:leaderMsgs
            ) {
                msg.setCrtime(new Date(msg.getDateline()*1000));
            }
            b = b && leaderMsgService.saveOrUpdateBatch(leaderMsgs);
        }
        return b;
    }

    @GetMapping("/savedata")
    public String savedata(){

        List list = new ArrayList();
        list.add(5);//5 建言
        list.add(2);//2 投诉/求助
        list.add(1);//1 咨询
        for (int i = 0; i <list.size() ; i++) {
            Integer typeId = Integer.parseInt(list.get(i)+"");
            String lastItem = "";
            QueryWrapper<LeaderInfoJson> qw=new QueryWrapper<>();
            qw.eq("has_child",0);
            List<LeaderInfoJson> leaderInfoJsonList = leaderInfoJsonService.list(qw);
            for (LeaderInfoJson leaderInfoJson : leaderInfoJsonList) {
                String fid = leaderInfoJson.getFid()+"";
                List<LeaderMsg> leaderMsgs = leaderMsgService.getLeaderMsgInfo(fid, typeId, lastItem);
                boolean b = true;
                if(!ObjectUtils.isEmpty(leaderMsgs)){
                    for (LeaderMsg msg:leaderMsgs
                    ) {
                        msg.setCrtime(new Date(msg.getDateline()*1000));
                    }
                    b = b && leaderMsgService.saveOrUpdateBatch(leaderMsgs);
                }
            }
        }
        return "完成";
    }



    /**
     * 一键获取所有领导人信息
     * @param fid
     * @return
     */
    @GetMapping("getAllLeaderInfo")
    public Result getAllLeaderInfo(Integer fid){
        if (fid==null){
            return Result.ERROR("fid不可为空");
        }
        return leaderInfoJsonService.getAllLeaderInfo(fid);

    }
}
