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.WechatDepartment;
import cn.com.ctop.oa.modules.entity.WechatUserList;
import cn.com.ctop.oa.modules.mapper.WechatUserListMapper;
import cn.com.ctop.oa.modules.service.IWechatDepartmentService;
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.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxl.job.core.enums.NoEn;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 企业微信用户
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2020-09-15
 */
@Service
@Slf4j
public class WechatUserListServiceImpl extends ServiceImpl<WechatUserListMapper, WechatUserList> implements IWechatUserListService {
    @Autowired
    private IWechatTokenService tokenService;
    @Autowired
    private IWechatDepartmentService departmentService;
    @Autowired
    private WechatUserListMapper wechatUserListMapper;

    @Override
    public void getUserList() {
        try {
            Map<String, Object> qywxAccessToken = tokenService.getQYWXAccessToken();
            if ((Integer) qywxAccessToken.get("code") != 0) {
                log.error("企业微信获取token失败,返回信息：{}", qywxAccessToken.get("message"));
                throw new Exception("企业微信获取token失败");
            }
            TreeMap<String, Object> params = new TreeMap<>();
            params.put("access_token", qywxAccessToken.get("accessToken"));
            List<WechatDepartment> list = departmentService.queryList(NoEn.NO0.valueInt());
            if (Check.isNull(list)) {
                return;
            }
            for (WechatDepartment department : list) {
                params.remove("department_id");
                String departId = department.getDepartId();
                params.put("department_id", departId);
                String resultStr = HttpUtils.httpGetRequest(QYWxConstant.QYWX_USER_SIMPLELIST, null, params);
                JSONObject resultJson = JSONObject.parseObject(resultStr);
                Integer errcode = resultJson.getInteger("errcode");
                if (errcode == 0) {
                    JSONArray userlist = resultJson.getJSONArray("userlist");
                    if (!Check.isNull(userlist)) {
                        for (int i = 0; i < userlist.size(); i++) {
                            JSONObject userJson = userlist.getJSONObject(i);
                            if (!Check.isNull(userJson)) {
                                String userid = userJson.getString("userid");
                                String id = departId + "_" + userid;
                                WechatUserList userList = new WechatUserList();
                                userList.setId(id);
                                userList.setDepartId(departId);
                                userList.setUserId(userid);
                                userList.setUserName(userJson.getString("name"));
                                this.saveOrUpdate(userList);
                            }
                        }
                    }
                } else {
                    throw new Exception("企业微信获取用户列表失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void getYRUserList() {
        try {
            Map<String, Object> qywxAccessToken = tokenService.getYRCompanyToken();
            if ((Integer) qywxAccessToken.get("code") != 0) {
                log.error("企业微信获取token失败,返回信息：{}", qywxAccessToken.get("message"));
                throw new Exception("企业微信获取token失败");
            }
            TreeMap<String, Object> params = new TreeMap<>();
            params.put("access_token", qywxAccessToken.get("accessToken"));
            List<WechatDepartment> list = departmentService.queryList(NoEn.NO1.valueInt());
            if (Check.isNull(list)) {
                return;
            }
            for (WechatDepartment department : list) {
                params.remove("department_id");
                String departId = department.getDepartId();
                params.put("department_id", departId);
                String resultStr = HttpUtils.httpGetRequest(QYWxConstant.QYWX_USER_SIMPLELIST, null, params);
                JSONObject resultJson = JSONObject.parseObject(resultStr);
                Integer errcode = resultJson.getInteger("errcode");
                if (errcode == 0) {
                    JSONArray userlist = resultJson.getJSONArray("userlist");
                    if (!Check.isNull(userlist)) {
                        for (int i = 0; i < userlist.size(); i++) {
                            JSONObject userJson = userlist.getJSONObject(i);
                            if (!Check.isNull(userJson)) {
                                String userid = userJson.getString("userid");
                                String id = departId + "_" + userid;
                                WechatUserList userList = new WechatUserList();
                                userList.setId(id);
                                userList.setDepartId(departId);
                                userList.setUserId(userid);
                                userList.setDataType(NoEn.NO1.valueInt());
                                userList.setUserName(userJson.getString("name"));
                                this.saveOrUpdate(userList);
                            }
                        }
                    }
                } else {
                    throw new Exception("企业微信获取用户列表失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<WechatUserList> queryList(int dataType) {
        return wechatUserListMapper.queryList(dataType);
    }

    @Override
    public WechatUserList getInfoByUserId(String userId) {
        QueryWrapper<WechatUserList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.orderByDesc("create_time");
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }
}
