package com.muzhi.dingtalk.test.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.muzhi.dingtalk.test.entity.ErrorlogFangDe;
import com.muzhi.dingtalk.test.entity.vo.EmployeeFangDeDataVo;
import com.muzhi.dingtalk.test.entity.vo.EmployeeFangDeVo;
import com.muzhi.dingtalk.test.entity.vo.ErrorlogFangDeDataVo;
import com.muzhi.dingtalk.test.entity.vo.ErrorlogFangDeQuery;
import com.muzhi.dingtalk.test.exceptionhander.R;
import com.muzhi.dingtalk.test.mapper.ErrorlogFangDeMapper;
import com.muzhi.dingtalk.test.service.FangDeDingAccessTokenService;
import com.muzhi.dingtalk.test.service.FangDeTongbuService;
import com.muzhi.dingtalk.test.webservicezhengshi.IPsndocVO;
import com.muzhi.dingtalk.test.webservicezhengshi.IPsndocVOPortType;
import com.taobao.api.ApiException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;


@Api(description = "同步数据至数据库")
@RestController
@RequestMapping("/fangdetongbuservice/fangdetongbu")
@CrossOrigin//解决跨域问题
public class FangDeTongbuController {

    //TODO 根据NC接口同步数据

    @Autowired
    private FangDeDingAccessTokenService fangDeDingAccessTokenService;
    @Autowired
    private FangDeTongbuService fangDeTongbuService;

    @Autowired
    private ErrorlogFangDeMapper errorLogFangDeMapper;

    //【测试！！！】获取房德钉钉中的花名册数据并解析成json格式数据返回【离职】
    @ApiOperation(value = "获取房德员工花名册字段信息")
    @GetMapping("getFangDeHuamingceTest")
    public EmployeeFangDeDataVo getFangDeHuamingceTest(){

        EmployeeFangDeDataVo<EmployeeFangDeVo> fangDeHuamingceTest = fangDeTongbuService.getFangDeHuamingceTest();
        return fangDeHuamingceTest;
    }

    //【测试！！！】获取房德钉钉中的离职人员信息属于最后工作日为：2021-02-18 00:00:00的人员id【离职】
    @ApiOperation(value = "获取房德员工花名册字段信息")
    @GetMapping("getFangDeHuamingceLiZhiIdTest")
    public String getFangDeHuamingceLiZhiIdTest(){

        String fangDeHuamingceLiZhiIdTest = fangDeTongbuService.getFangDeHuamingceLiZhiIdTest();
        return fangDeHuamingceLiZhiIdTest;
    }

    //【测试！！！】获取房德钉钉中的花名册数据并解析成json格式数据返回【离职】
    @ApiOperation(value = "获取房德员工花名册字段信息")
    @GetMapping("getFangDeHuamingceLiZhiTest")
    public EmployeeFangDeDataVo getFangDeHuamingceLiZhiTest(){

        EmployeeFangDeDataVo<EmployeeFangDeVo> fangDeHuamingceLiZhiTest = fangDeTongbuService.getFangDeHuamingceLiZhiTest();
        return fangDeHuamingceLiZhiTest;
    }






    //***以下为正式使用的方法***//
    //***以下为正式使用的方法***//
    //***以下为正式使用的方法***//


    //房德花名册数据返回指定格式【在职】
    @ApiOperation(value = "获取房德员工花名册字段信息")
    @GetMapping("getFangDeHuamingce")
    public EmployeeFangDeDataVo getFangDeHuamingce(){

        EmployeeFangDeDataVo<EmployeeFangDeVo> fangDeHuamingce = fangDeTongbuService.getFangDeHuamingce();
        return fangDeHuamingce;
    }

    //房德花名册数据返回指定格式【离职】
    @ApiOperation(value = "获取房德员工花名册字段信息")
    @GetMapping("getFangDeHuamingceLiZhi")
    public EmployeeFangDeDataVo getFangDeHuamingceLiZhi(){

        EmployeeFangDeDataVo<EmployeeFangDeVo> fangDeHuamingceLiZhi = fangDeTongbuService.getFangDeHuamingceLiZhi();
        return fangDeHuamingceLiZhi;
    }



    //同步房德花名册数据至NC接口
    @ApiOperation(value = "同步在职人员花名册数据至NC接口")
    @PostMapping("addFangDeHuamingceToNC")
//    @Scheduled(cron = "0 1 15 * * ?")//每天下午15：01触发（也就是下午3点触发）
    @Scheduled(cron = "0 0 0 * * ?")//每天00：00触发（也就是凌晨0点整触发）
    public void addFangDeHuamingceToNC(){
        //先清空错误日志表的数据
        errorLogFangDeMapper.delete(null);

        IPsndocVO iPsndocVO = new IPsndocVO();

        IPsndocVOPortType iPsndocVOPortType = iPsndocVO.getIPsndocVOSOAP11PortHttp();

        //房德的钉钉中在职人员同步NC接口
        String bodyZZ = iPsndocVOPortType.savePsndocVO(JSONObject.toJSONString(fangDeTongbuService.getFangDeHuamingce()));
        System.out.println("NC接口返回结果（在职）：" + bodyZZ);

        //通过fastjson工具转换成json对象,逐层解析
        JSONObject jsonObject = JSON.parseObject(bodyZZ);
        JSONArray returndata = jsonObject.getJSONArray("returndata");

        ErrorlogFangDe errorLogFangDe = new ErrorlogFangDe();

        for (int i = 0; i<returndata.size(); i++){

            //错误标识
            errorLogFangDe.setCode(returndata.getJSONObject(i).getString("code"));
            System.out.println("错误标识：" + returndata.getJSONObject(i).getString("code"));
            //错误信息
            errorLogFangDe.setMsg(returndata.getJSONObject(i).getString("msg"));
            System.out.println("错误信息：" + returndata.getJSONObject(i).getString("msg"));

            String data = returndata.getJSONObject(i).getString("data");
            JSONObject jsonObject1 = JSON.parseObject(data);

            //员工状态
            errorLogFangDe.setStatus(jsonObject1.getString("status"));
            System.out.println("员工状态：" + jsonObject1.getString("status"));
            //员工ID
            errorLogFangDe.setId1(jsonObject1.getString("code"));
            System.out.println("员工ID：" + jsonObject1.getString("code"));
            //员工姓名
            errorLogFangDe.setName(jsonObject1.getString("name"));
            System.out.println("员工姓名：" + jsonObject1.getString("name"));
            //同步时间
            errorLogFangDe.setTs(jsonObject1.getString("ts"));
            System.out.println("同步时间：" + jsonObject1.getString("ts"));

            errorLogFangDeMapper.insert(errorLogFangDe);
        }

        //同步完成后将同步页面链接发送到通知消息，用来点击跳转查看同步日志信息
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request req = new OapiMessageCorpconversationAsyncsendV2Request();
            req.setAgentId(1164969760L);

            //TODO 发送通知消息给指定人员id（云璞牧之、云璞甘草、房德丁文波）
            req.setUseridList("011033176057775267,1951251420023804,1504243329847569");

            req.setToAllUser(false);
            OapiMessageCorpconversationAsyncsendV2Request.Msg obj1 = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
            obj1.setMsgtype("link");
            OapiMessageCorpconversationAsyncsendV2Request.Link obj2 = new OapiMessageCorpconversationAsyncsendV2Request.Link();
            long time = new Date().getTime();
            String time1 = String.valueOf(time);
            obj2.setPicUrl(time1);

            //TODO 消息通知点击的链接：房德服务器路径118.178.17.233:8091
            obj2.setMessageUrl("dingtalk://dingtalkclient/action/openapp?corpid=ding81b4dfad3a436bd735c2f4657eb6378f&container_type=work_platform&app_id=0_1164969760&redirect_type=jump&redirect_url=http://47.99.48.105:8091/index.html");

            obj2.setText("人员档案同步至NC的日志信息，详细内容请点击跳转至指定页面查看。");
            obj2.setTitle("人员档案同步完成");
            obj1.setLink(obj2);
            req.setMsg(obj1);
            OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(req, fangDeDingAccessTokenService.getFangDeAccessToken());
            System.out.println(rsp.getBody());
        } catch (ApiException e) {
            e.printStackTrace();
        }


//        //房德的钉钉中离职人员同步NC接口
//        String bodyLZ = iPsndocVOPortType.savePsndocVO(JSONObject.toJSONString(fangDeTongbuService.getFangDeHuamingceLiZhiTest()));
//        System.out.println("NC接口返回结果（离职）：" + bodyLZ);
    }

    //从本地错误日志表中查询房德同步NC的错误日志信息并处理成layui（前端页面）需要的json格式
    @ApiOperation(value = "从本地错误日志表中查询房德同步NC的错误日志信息并处理成layui（前端页面）需要的json格式")
    @GetMapping("getErrorlogFangDe")
//    @Scheduled(cron = "0 1 15 * * ?")//每天下午15：01触发（也就是下午3点触发）
//    @Scheduled(cron = "0 0 0 * * ?")//每天00：00触发（也就是凌晨0点整触发）
    public ErrorlogFangDeDataVo<ErrorlogFangDe> getErrorlogFangDe(Integer page, Integer limit, ErrorlogFangDeQuery errorlogFangDeQuery){

        ErrorlogFangDeDataVo errorlogFangDeDataVo = new ErrorlogFangDeDataVo();
        errorlogFangDeDataVo.setCode(0);
        errorlogFangDeDataVo.setMsg("");
//        errorlogFangDeDataVo.setCount(errorLogFangDeMapper.selectCount(null));
        //将本地数据库中的错误日志表的数据放进data中
//        errorlogFangDeDataVo.setData(errorLogFangDeMapper.selectList(null));

        //分页查询,创建page对象
        Page<ErrorlogFangDe> errorlogFangDePage = new Page<>(page,limit);

        //构建查询条件
        QueryWrapper<ErrorlogFangDe> wrapper = new QueryWrapper<>();
        //多条件组合查询（类似mybatis中动态sql）
        String id = errorlogFangDeQuery.getId();
        String name = errorlogFangDeQuery.getName();
        String msg = errorlogFangDeQuery.getMsg();
        //判断条件值是否为空，如果不为空则拼接条件
        if (!StringUtils.isEmpty(id)) {
            //构建条件
            wrapper.like("id1", id);
        }
        if (!StringUtils.isEmpty(name)) {
            //构建条件
            wrapper.like("name", name);
        }
        if (!StringUtils.isEmpty(msg)) {
            //构建条件
            wrapper.like("msg", msg);
        }

//        //查询实体类表中所有的数据（全部）
//        List<ErrorlogFangDe> errorlogFangDeList = errorLogFangDeMapper.selectList(wrapper);
        IPage<ErrorlogFangDe> result = errorLogFangDeMapper.selectPage(errorlogFangDePage, wrapper);
        //查询分页信息记录（根据分页要求来查）
        List<ErrorlogFangDe> errorlogFangDeList = result.getRecords();
        //查询总数
        errorlogFangDeDataVo.setCount(result.getTotal());

        //将本地数据库中的错误日志表的数据放进data中
        errorlogFangDeDataVo.setData(errorlogFangDeList);

        return errorlogFangDeDataVo;
    }



    /**
     * 任务执行方法（在实际应用中要改成自己的逻辑代码）
     *Title: execute
     *Description:
     　 * @param request
     　 * @return
     */
    @RequestMapping(value = "execute")
    public String execute(HttpServletRequest request) {

        for (int i = 0; i <= 100; i++) {
            //for循环只是个例子，在实际业务中百分比要进行实际的计算，这里的i就当是百分比
            //将进度值存储到session中
            request.getSession().setAttribute("processvalue", i);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return "success";
    }
    /**
     * 获取session中的进度值
     *Title: getprocess
     *Description:
     　 * @param request
     　 * @return
     */
    @RequestMapping(value = "getprocess")
    public Object getprocess(HttpServletRequest request) {
        //从session将执行进度值取出来并返回给用户
        return request.getSession().getAttribute("processvalue");
    }



    //同步花名册数据至本地数据库
    @ApiOperation(value = "同步在职人员花名册数据至本地数据库")
    @PostMapping("addFangDeHuamingce")
//    @Scheduled(cron = "0 1 15 * * ?")//每天下午15：01触发（也就是下午3点触发）
//    @Scheduled(cron = "0 0 0 * * ?")//每天00：00触发（也就是凌晨0点整触发）
    public R addFangDeHuamingce(){
        //先删除清空employee表中的所有数据
        fangDeTongbuService.removeFangDeEmployee();

        //再执行插入花名册数据库表的接口
        String result = fangDeTongbuService.addFangDeHuamingce();
        return R.ok().data("zaizhi", result);
    }

    //同步离职人员花名册数据至数据库
    @ApiOperation(value = "同步离职人员花名册数据至本地数据库")
    @PostMapping("addFangDeLiZhiHuamingce")
//    @Scheduled(cron = "0 1 15 * * ?")//每天下午15：01触发（也就是下午3点触发）
//    @Scheduled(cron = "0 0 0 * * ?")//每天00：00触发（也就是凌晨0点整触发）
    public R addFangDeLiZhiHuamingce(){
        //先删除清空employee表中的所有数据
//        fangDeTongbuService.removeFangDeEmployee();

        //再执行插入花名册数据库表的接口
        String liZhiHuamingce = fangDeTongbuService.addFangDeLiZhiHuamingce();
        return R.ok().data("lizhi",liZhiHuamingce);
    }

//    //同步花名册数据至数据库
//    @ApiOperation(value = "同步在职、离职人员花名册数据至房德数据库")
//    @PostMapping("addFangDeHuamingce")
////    @Scheduled(cron = "0 1 15 * * ?")//每天下午15：01触发（也就是下午3点触发）
////    @Scheduled(cron = "0 0 0 * * ?")//每天00：00触发（也就是凌晨0点整触发）
//    public R addFangDeHuamingce(){
//        //先删除清空employee表中的所有数据
//        fangDeTongbuService.removeFangDeEmployee();
//
//        //再执行插入花名册数据库表的接口
//        String result = fangDeTongbuService.addFangDeHuamingce();
//        String liZhiHuamingce = fangDeTongbuService.addFangDeLiZhiHuamingce();
//        return R.ok().data("zaizhi", result).data("lizhi",liZhiHuamingce);
//    }
}
