package cn.com.ctop.oa.modules.service.impl;

import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.oa.modules.constant.QYWxConstant;
import cn.com.ctop.oa.modules.entity.WechatCheckinData;
import cn.com.ctop.oa.modules.entity.WechatCheckinSubData;
import cn.com.ctop.oa.modules.entity.WechatUserList;
import cn.com.ctop.oa.modules.mapper.WechatCheckinDataMapper;
import cn.com.ctop.oa.modules.service.IWechatCheckinDataService;
import cn.com.ctop.oa.modules.service.IWechatTokenService;
import cn.com.ctop.oa.modules.service.IWechatUserListService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xxl.job.core.enums.NoEn;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static org.jeecg.common.constant.GeneralConstant.*;

/**
 * 员工考勤
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2020-09-15
 */
@Service
@Slf4j
public class WechatCheckinDataServiceImpl extends ServiceImpl<WechatCheckinDataMapper, WechatCheckinData> implements IWechatCheckinDataService {
    @Autowired
    private IWechatTokenService tokenService;
    @Autowired
    private IWechatUserListService userListService;
    @Autowired
    private WechatCheckinDataMapper wechatCheckinDataMapper;

    @Override
    public void getCheckinData(String starttime, String endtime) {
        try {
            Map<String, Object> qywxAccessToken = tokenService.getOAAccessToken();
            if ((Integer) qywxAccessToken.get(CODE) != 0) {
                log.error("员工考勤获取token失败,返回信息：{}", qywxAccessToken.get(MESSAGE));
                throw new Exception("员工考勤获取token失败");
            }
            List<WechatUserList> list = userListService.queryList(NoEn.NO0.valueInt());
            if (Check.isNull(list)) {
                return;
            }
            for (WechatUserList userList : list) {
                JSONObject params = new JSONObject();
                String userId = userList.getUserId();
                String departId = userList.getDepartId();
                params.put("opencheckindatatype", 3);
                JSONArray userArr = new JSONArray();
                userArr.add(userId);
                params.put("useridlist", userArr);
                params.put(API_START_TIME, DateUtils.timeToStamp(starttime));
                params.put(API_END_TIME, DateUtils.timeToStamp(endtime));
                String resultStr = HttpUtils.httpPostRequestTest(QYWxConstant.QYWX_CHECKIN_DATA + "?access_token=" + qywxAccessToken.get(ACCESS_TOKEN), params.toJSONString(), null);
                JSONObject resultJson = JSONObject.parseObject(resultStr);
                if (resultJson.getInteger(ERR_CODE) == 0) {
                    JSONArray checkindata = resultJson.getJSONArray("checkindata");
                    if (!Check.isNull(checkindata)) {
                        StringBuffer buf = null;
                        String checkinType = "";
                        String checkinTypeCode = "";
                        for (int i = 0; i < checkindata.size(); i++) {
                            JSONObject jsonObject = checkindata.getJSONObject(i);
                            if (!Check.isNull(jsonObject)) {
                                WechatCheckinData checkinData = new WechatCheckinData();
                                checkinType = jsonObject.getString("checkin_type");
                                //1上班，2下班
                                checkinTypeCode = "上班打卡".equals(checkinType) ? NoEn.NO1.valueStr() : NoEn.NO2.valueStr();
                                //下班打卡时间
                                Long checkinTimeStamp = jsonObject.getLong("checkin_time");
                                Date checkDate = DateUtils.stampToTime(checkinTimeStamp);
                                String dateStr = DateUtils.formatDate(checkDate);
                                long dateLong = DateUtils.timeToStamp(dateStr + DAY_BEGIN);
                                //判断上班是否是周一，周一打卡时间超过9.35则算迟到
                                String exceptionType = jsonObject.getString("exception_type");
                                if (NoEn.NO1.valueStr().equals(checkinTypeCode)) {
                                    if ("星期一".equals(DateUtils.getWhatDay(checkinTimeStamp))) {
                                        long toTime = DateUtils.timeToStamp(dateStr + " 09:35:00");
                                        if (checkinTimeStamp > toTime) {
                                            exceptionType = Check.isNull(exceptionType) ? "时间异常" : exceptionType;
                                        }
                                    }
                                }
                                buf = new StringBuffer();
                                String id = buf.append(userId).append("_").append(checkinTypeCode).append("_").append(dateLong).toString();
                                checkinData.setId(id);
                                checkinData.setDepartId(departId);
                                checkinData.setUserId(userId);
                                checkinData.setCheckinType(checkinType);
                                checkinData.setCheckinTime(checkDate);
                                Long dateStamp = DateUtils.timeToStamp(dateStr + " 21:30:00"); // 每天九点半时间戳
                                if (checkinTimeStamp >= dateStamp) {
                                    checkinData.setOvertimeOrNot(1);
                                    String overtimeStr = DateUtils.formatDate(checkDate) + " 19:00:00";
                                    Long overtimeStamp = DateUtils.timeToStamp(overtimeStr); // 每天九点半时间戳
                                    Double overtime = Double.valueOf(checkinTimeStamp - overtimeStamp) / 3600;
                                    checkinData.setOvertime(overtime);
                                }
                                checkinData.setWifiname(jsonObject.getString("wifiname"));
                                checkinData.setNotes(jsonObject.getString("notes"));
                                checkinData.setLat(jsonObject.getString("lng"));
                                checkinData.setLocationDetail(jsonObject.getString("location_detail"));
                                checkinData.setGroupName(jsonObject.getString("groupname"));
                                checkinData.setDeviceid(jsonObject.getString("deviceid"));
                                checkinData.setExceptionType(exceptionType);
                                checkinData.setLocationTitle(jsonObject.getString("location_title"));
                                checkinData.setWifimac(jsonObject.getString("wifimac"));
                                checkinData.setMediaids(jsonObject.getJSONArray("mediaids").toJSONString());
                                checkinData.setLat(jsonObject.getString("lat"));
                                this.saveOrUpdate(checkinData);
                            }
                        }
                    }
                } else {
                    log.error("获取打卡数据异常,返回数据-> {} ；入参-> {}", resultJson, params.toJSONString());
                }
            }
        } catch (Exception e) {
            log.error("员工考勤入库异常，", e);
        }
    }


    @Override
    public void getYRCheckinData(String starttime, String endtime) {
        try {
            Map<String, Object> qywxAccessToken = tokenService.getYROAToken();
            if ((Integer) qywxAccessToken.get(CODE) != 0) {
                log.error("员工考勤获取token失败,返回信息：{}", qywxAccessToken.get(MESSAGE));
                throw new Exception("员工考勤获取token失败");
            }
            List<WechatUserList> list = userListService.queryList(NoEn.NO1.valueInt());
            if (Check.isNull(list)) {
                return;
            }
            for (WechatUserList userList : list) {
                JSONObject params = new JSONObject();
                String userId = userList.getUserId();
                String departId = userList.getDepartId();
                params.put("opencheckindatatype", 3);
                JSONArray userArr = new JSONArray();
                userArr.add(userId);
                params.put("useridlist", userArr);
                params.put(API_START_TIME, DateUtils.timeToStamp(starttime));
                params.put(API_END_TIME, DateUtils.timeToStamp(endtime));
                String resultStr = HttpUtils.httpPostRequestTest(QYWxConstant.QYWX_CHECKIN_DATA + "?access_token=" + qywxAccessToken.get(ACCESS_TOKEN), params.toJSONString(), null);
                JSONObject resultJson = JSONObject.parseObject(resultStr);
                if (resultJson.getInteger(ERR_CODE) == 0) {
                    JSONArray checkindata = resultJson.getJSONArray("checkindata");
                    if (!Check.isNull(checkindata)) {
                        StringBuffer buf = null;
                        String checkinType = "";
                        String checkinTypeCode = "";
                        for (int i = 0; i < checkindata.size(); i++) {
                            JSONObject jsonObject = checkindata.getJSONObject(i);
                            if (!Check.isNull(jsonObject)) {
                                WechatCheckinData checkinData = new WechatCheckinData();
                                checkinType = jsonObject.getString("checkin_type");
                                //1上班，2下班
                                checkinTypeCode = "上班打卡".equals(checkinType) ? NoEn.NO1.valueStr() : NoEn.NO2.valueStr();
                                String exceptionType = jsonObject.getString("exception_type");
                                //下班打卡时间
                                Long checkinTimeStamp = jsonObject.getLong("checkin_time");
                                Date checkDate = DateUtils.stampToTime(checkinTimeStamp);
                                String dateStr = DateUtils.formatDate(checkDate);
                                long dateLong = DateUtils.timeToStamp(dateStr + DAY_BEGIN);
                                //判断上班是否是周一，周一打卡时间超过9.35则算迟到
                                if (NoEn.NO1.valueStr().equals(checkinTypeCode)) {
                                    if ("星期一".equals(DateUtils.getWhatDay(checkinTimeStamp))) {
                                        long toTime = DateUtils.timeToStamp(dateStr + " 10:00:00");
                                        if (checkinTimeStamp > toTime) {
                                            exceptionType = Check.isNull(exceptionType) ? "时间异常" : exceptionType;
                                        }
                                    }
                                }
                                buf = new StringBuffer();
                                String id = buf.append(userId).append("_").append(checkinTypeCode).append("_").append(dateLong).toString();
                                checkinData.setId(id);
                                checkinData.setDepartId(departId);
                                checkinData.setUserId(userId);
                                checkinData.setCheckinType(checkinType);
                                checkinData.setCheckinTime(checkDate);
                                Long dateStamp = DateUtils.timeToStamp(dateStr + " 21:30:00"); // 每天九点半时间戳
                                if (checkinTimeStamp >= dateStamp) {
                                    checkinData.setOvertimeOrNot(1);
                                    String overtimeStr = DateUtils.formatDate(checkDate) + " 19:00:00";
                                    Long overtimeStamp = DateUtils.timeToStamp(overtimeStr); // 每天九点半时间戳
                                    Double overtime = Double.valueOf(checkinTimeStamp - overtimeStamp) / 3600;
                                    checkinData.setOvertime(overtime);
                                }
                                checkinData.setWifiname(jsonObject.getString("wifiname"));
                                checkinData.setNotes(jsonObject.getString("notes"));
                                checkinData.setLat(jsonObject.getString("lng"));
                                checkinData.setLocationDetail(jsonObject.getString("location_detail"));
                                checkinData.setGroupName(jsonObject.getString("groupname"));
                                checkinData.setDeviceid(jsonObject.getString("deviceid"));
                                checkinData.setExceptionType(exceptionType);
                                checkinData.setLocationTitle(jsonObject.getString("location_title"));
                                checkinData.setWifimac(jsonObject.getString("wifimac"));
                                checkinData.setMediaids(jsonObject.getJSONArray("mediaids").toJSONString());
                                checkinData.setLat(jsonObject.getString("lat"));
                                checkinData.setDataType(NoEn.NO1.valueInt());
                                this.saveOrUpdate(checkinData);
                            }
                        }
                    }
                } else {
                    log.error("获取打卡数据异常,返回数据-> {} ；入参-> {}", resultJson, params.toJSONString());
                }
            }
        } catch (Exception e) {
            log.error("员工考勤入库异常，", e);
        }
    }


    @Override
    public PageInfo<WechatCheckinSubData> selectPageList(Map<String, Object> paramsMap) {
        Integer pageNo = (Integer) paramsMap.get(PAGE_NO);
        if (null == pageNo || pageNo == 0) {
            pageNo = 1;
        }
        Integer pageSize = (Integer) paramsMap.get(PAGE_SIZE);
        if (null == pageSize || pageSize == 0) {
            pageSize = 10;
        }
        String startTime = (String) paramsMap.get(START_TIME);
        if (!Check.isNull(startTime)) {
            startTime += DAY_BEGIN;
            paramsMap.put(START_TIME, startTime);
        }
        String stopTime = (String) paramsMap.get(STOP_TIME);
        if (!Check.isNull(stopTime)) {
            stopTime += DAY_END;
            paramsMap.put(STOP_TIME, stopTime);
        }
        PageHelper.startPage(pageNo, pageSize);
        List<WechatCheckinSubData> list = wechatCheckinDataMapper.selectPageList(paramsMap);
        return new PageInfo<>(list);
    }
}
