package com.mortals.xhx.module.dingding.attendance.service.impl;

import com.alibaba.fastjson.JSON;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.mortals.framework.common.Rest;
import com.mortals.framework.model.PageInfo;
import com.mortals.xhx.module.attendance.model.AttendanceRecordHikQuery;
import com.mortals.xhx.module.dingding.AbstractDingTalkService;
import com.mortals.xhx.module.dingding.attendance.service.IDingAttenanceService;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;


@Service("dingAttendanceService")
@Slf4j
public class DingAttendanceServiceImpl extends AbstractDingTalkService implements IDingAttenanceService {

    @Override
    public Rest<List<OapiAttendanceListResponse.Recordresult>> getAttendanceList(PageInfo pageInfo, List<String> userIdList, AttendanceRecordHikQuery hikQuery) {
        //todo 获取考勤列表
        try {
            DingTalkClient client = getDingTalkClient("/attendance/list");
            OapiAttendanceListRequest req = new OapiAttendanceListRequest();
            String attendanceDateStart = hikQuery.getAttendanceDateStart();
            String attendanceDateEnd = hikQuery.getAttendanceDateEnd();
            req.setWorkDateFrom(attendanceDateStart);
            req.setWorkDateTo(attendanceDateEnd);
            req.setUserIdList(userIdList);
            req.setOffset(Long.valueOf(pageInfo.getBeginIndex() + ""));
            req.setLimit(Long.valueOf(pageInfo.getPrePageResult() + ""));
            //log.info("req:{}", JSON.toJSONString(req));
            OapiAttendanceListResponse rsp = client.execute(req, getToken());

            // log.info("OapiV2UserGetbymobileResponse:{}", rsp.getBody());
            if (rsp.getErrcode() == 0) {
                if (rsp.getHasMore()) {
                    log.info("还有更多数据，递归调用,req:{}", JSON.toJSONString(req));
                    pageInfo.setCurrPage(pageInfo.getCurrPage() + 1);
                    Rest<List<OapiAttendanceListResponse.Recordresult>> attendanceList = getAttendanceList(pageInfo, userIdList, hikQuery);
                    rsp.getRecordresult().addAll(attendanceList.getData());
                    return Rest.ok("成功", rsp.getRecordresult());
                }
                return Rest.ok("成功", rsp.getRecordresult());
            } else {

                log.info("异常数据,rsp error:{}", JSON.toJSONString(rsp));
                return Rest.fail(String.format("code:%s,msg:%s", rsp.getErrcode(), rsp.getErrmsg()));
            }


        } catch (ApiException e) {
            log.info("获取考勤列表异常", e);
            return Rest.fail(e.getMessage());
        }

    }

    @Override
    public Rest<List<OapiAttendanceGetsimplegroupsResponse.AtGroupForTopVo>> getAttendanceGroupList(PageInfo pageInfo) {
        //todo 获取考勤组列表
        try {
            DingTalkClient client = getDingTalkClient("/topapi/attendance/getsimplegroups");
            OapiAttendanceGetsimplegroupsRequest req = new OapiAttendanceGetsimplegroupsRequest();
            req.setOffset(Long.valueOf(pageInfo.getBeginIndex() + ""));
            req.setSize(Long.valueOf(pageInfo.getPrePageResult() + ""));
            log.info("req:{}", JSON.toJSONString(req));
            OapiAttendanceGetsimplegroupsResponse rsp = client.execute(req, getToken());
            log.info("考勤组 Response:{}", rsp.getBody());
            if (rsp.getErrcode() == 0) {
                if (rsp.getResult().getHasMore()) {
                    log.info("还有更多数据，递归调用,req:{}", JSON.toJSONString(req));
                    pageInfo.setCurrPage(pageInfo.getCurrPage() + 1);
                    Rest<List<OapiAttendanceGetsimplegroupsResponse.AtGroupForTopVo>> rest = getAttendanceGroupList(pageInfo);
                    rsp.getResult().getGroups().addAll(rest.getData());
                    return Rest.ok("成功", rsp.getResult().getGroups());
                }

                return Rest.ok("成功", rsp.getResult().getGroups());
            } else {
                log.info("异常数据,rsp error:{}", JSON.toJSONString(rsp));
                return Rest.fail(String.format("code:%s,msg:%s", rsp.getErrcode(), rsp.getErrmsg()));
            }
        } catch (ApiException e) {
            log.info("获取考勤组异常", e);
            return Rest.fail(e.getMessage());
        }

    }

    @Override
    public Rest<List<String>> getGroupPersons(Long cursor, Long groupId) {

        //todo 获取考勤组人员列表
        try {
            DingTalkClient client = getDingTalkClient("/topapi/attendance/group/memberusers/list");
            OapiAttendanceGroupMemberusersListRequest req = new OapiAttendanceGroupMemberusersListRequest();
            req.setCursor(cursor);
            req.setOpUserId("manager");
            req.setGroupId(groupId);
            log.info("req:{}", JSON.toJSONString(req));
            OapiAttendanceGroupMemberusersListResponse rsp = client.execute(req, getToken());
            log.info("考勤组 Response:{}", rsp.getBody());
            if (rsp.getErrcode() == 0) {
                if (rsp.getResult().getHasMore()) {
                    log.info("还有更多数据，递归调用,req:{}", JSON.toJSONString(req));

                    Rest<List<String>> rest = getGroupPersons(rsp.getResult().getCursor(), groupId);

                    rsp.getResult().getResult().addAll(rest.getData());

                    return Rest.ok("成功", rsp.getResult().getResult());
                }

                return Rest.ok("成功", rsp.getResult().getResult());
            } else {
                log.info("异常数据,rsp error:{}", JSON.toJSONString(rsp));
                return Rest.fail(String.format("code:%s,msg:%s", rsp.getErrcode(), rsp.getErrmsg()));
            }
        } catch (ApiException e) {
            log.info("获取考勤组人员异常", e);
            return Rest.fail(e.getMessage());
        }

    }


    public Rest<List<OapiAttendanceShiftListResponse.TopMinimalismShiftVo>> getShiftList(Long cursor) {
        //todo 获取班次列表
        try {
            DingTalkClient client = getDingTalkClient("/topapi/attendance/shift/list");
            OapiAttendanceShiftListRequest req = new OapiAttendanceShiftListRequest();
            req.setCursor(cursor);
            req.setOpUserId("manager");
            log.info("req:{}", JSON.toJSONString(req));
            OapiAttendanceShiftListResponse rsp = client.execute(req, getToken());
            log.info("考勤班次 Response:{}", rsp.getBody());
            if (rsp.getErrcode() == 0) {
                if (rsp.getResult().getHasMore()) {
                    log.info("还有更多数据，递归调用,req:{}", JSON.toJSONString(req));
                    Rest<List<OapiAttendanceShiftListResponse.TopMinimalismShiftVo>> rest = getShiftList(rsp.getResult().getCursor());
                    rsp.getResult().getResult().addAll(rest.getData());
                    return Rest.ok("成功", rsp.getResult().getResult());
                }
                return Rest.ok("成功", rsp.getResult().getResult());
            } else {
                log.info("异常数据,rsp error:{}", JSON.toJSONString(rsp));
                return Rest.fail(String.format("code:%s,msg:%s", rsp.getErrcode(), rsp.getErrmsg()));
            }
        } catch (ApiException e) {
            log.info("获取班次异常", e);
            return Rest.fail(e.getMessage());
        }
    }

    public Rest<OapiAttendanceShiftQueryResponse.TopShiftVo> getShiftDetail(Long shiftId) {
        //todo 获取班次列表
        try {
            DingTalkClient client = getDingTalkClient("/topapi/attendance/shift/query");
            OapiAttendanceShiftQueryRequest req = new OapiAttendanceShiftQueryRequest();
            req.setShiftId(shiftId);
            req.setOpUserId("manager");
            log.info("req:{}", JSON.toJSONString(req));
            OapiAttendanceShiftQueryResponse rsp = client.execute(req, getToken());
            log.info("班次详细 Response:{}", rsp.getBody());
            if (rsp.getErrcode() == 0) {
                return Rest.ok("成功", rsp.getResult());
            } else {
                log.info("异常数据,rsp error:{}", JSON.toJSONString(rsp));
                return Rest.fail(String.format("code:%s,msg:%s", rsp.getErrcode(), rsp.getErrmsg()));
            }
        } catch (ApiException e) {
            log.info("获取班次异常", e);
            return Rest.fail(e.getMessage());
        }
    }

    public Rest<OapiV2UserGetResponse.UserGetResponse> getPersonDetail(String userId) {
        //todo 获取班次列表
        try {
            DingTalkClient client = getDingTalkClient("/topapi/v2/user/get");
            OapiV2UserGetRequest req = new OapiV2UserGetRequest();
            req.setUserid(userId);
            log.info("req:{}", JSON.toJSONString(req));
            OapiV2UserGetResponse rsp = client.execute(req, getToken());
            log.info("个人详细 Response:{}", rsp.getBody());
            if (rsp.getErrcode() == 0) {
                return Rest.ok("成功", rsp.getResult());
            } else {
                log.info("异常数据,rsp error:{}", JSON.toJSONString(rsp));
                return Rest.fail(String.format("code:%s,msg:%s", rsp.getErrcode(), rsp.getErrmsg()));
            }
        } catch (ApiException e) {
            log.info("获取异常", e);
            return Rest.fail(e.getMessage());
        }
    }


}