package com.nbclass.activity.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nbclass.activity.constant.Const;
import com.nbclass.activity.mapper.WxDepartmentMapper;
import com.nbclass.activity.mapper.WxUserMapper;
import com.nbclass.activity.model.WxDepartment;
import com.nbclass.activity.model.WxUser;
import com.nbclass.activity.service.WxUserService;
import com.nbclass.system.model.User;
import com.nbclass.system.service.UserService;
import com.nbclass.util.HttpUtils;
import com.nbclass.util.PasswordHelper;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class WxUserServiceImpl implements WxUserService {
	
	@Resource
	private WxUserMapper wxUserMapper;
	
	@Resource
    private UserService userService;
	
	@Resource
	private WxDepartmentMapper deptMapper;
	
	
	@Transactional
	@Override
	public void merge(List<WxUser> userList){
		if(userList == null || userList.size() == 0)return;
		
		List<String> dbUserIds = wxUserMapper.getUserIds(); // 查询数据库已有的数据
		List<String> existIds = new ArrayList<String>();
		for (WxUser wxUser : userList) {
			User account = new User();
			account.setUserId(wxUser.getName()); // 将姓名存储到userid字段
			account.setUsername(wxUser.getUserid()); // 企业微信userid，作为登录账号
			account.setPassword("password");
			account.setEmail(wxUser.getEmail());
			account.setPhone(wxUser.getMobile());
			account.setSex(StringUtils.isBlank(wxUser.getGender()) ? null : Integer.parseInt(wxUser.getGender()));
			account.setStatus(1);
			account.setPassword("szxgl.cn"); // 默认登录密码
			PasswordHelper.encryptPassword(account);
			
			existIds.add(wxUser.getUserid());
			if(dbUserIds.contains(wxUser.getUserid())){
				wxUserMapper.updateByUserId(wxUser);
			}else{
				wxUserMapper.insertSelective(wxUser);
			}
			userService.updateQyWxUser(account);
		}
		// 删除当前企业微信不存在的用户
		if(existIds.size()>0)wxUserMapper.delOtherUsers(existIds);
	}
	
	@Override
	public void syncWxUser() {
		try {
			String url =  Const.QYWX_API_DOMAIN + "/open/api/user/list?secretKey=yunlei.888";
			JSONObject jsonObject = HttpUtils.httpPost(url);
			if(jsonObject !=null && jsonObject.getIntValue("ret") == 0){
				List<WxUser> userList = new ArrayList<WxUser>();
				JSONArray jsonArray = jsonObject.getJSONArray("list");
				if(jsonArray!=null && jsonArray.size() > 0){
					/*
					for(int i=0; i<jsonArray.size(); i++){
						JSONObject obj = jsonArray.getJSONObject(i);
						WxUser wxUser = new WxUser();
						wxUser.setUserid(obj.getString("userID"));
						wxUser.setName(obj.getString("name"));
						wxUser.setMobile(obj.getString("Mobile"));
						wxUser.setDepartment(obj.getString("Department"));
						wxUser.setPosition(obj.getString("Position"));
						wxUser.setGender(obj.getString("Gender"));
						wxUser.setEmail(obj.getString("Email"));
						wxUser.setIsleader(obj.getString("IsLeader"));
						wxUser.setAvatar(obj.getString("Avatar"));
						wxUser.setEnglish_name(obj.getString("EnglishName"));
						wxUser.setStatus(obj.getInteger("Status"));
						userList.add(wxUser);
					}
					*/
					for (Object object : jsonArray) {
						WxUser wxUser = JSON.toJavaObject((JSONObject)object, WxUser.class);
						userList.add(wxUser);
					}
				}
				merge(userList);
				log.info("同步企业成员成功，成员数量为："+userList.size());
			}else{
				log.error("同步企业成员出错: "+jsonObject);
			}
		} catch (Exception e) {
			log.error("同步企业成员异常", e);
		}
	}

	@Override
	public void syncWxDepartment() {
		try {
			String url =  Const.QYWX_API_DOMAIN + "/open/api/department/list?secretKey=yunlei.888";
			JSONObject jsonObject = HttpUtils.httpPost(url, "POST");
			if(jsonObject !=null && jsonObject.getIntValue("ret") == 0){
				List<WxDepartment> list = new ArrayList<WxDepartment>();
				JSONArray jsonArray = jsonObject.getJSONArray("list");
				if(jsonArray!=null && jsonArray.size() > 0){
					for (Object object : jsonArray) {
						WxDepartment wxDepartment = JSON.toJavaObject((JSONObject)object, WxDepartment.class);
						list.add(wxDepartment);
					}
				}
				if(list.size() > 0)deptMapper.insertBatch(list);
				log.info("同步企业部门成功，部门数量为："+list.size());
			}else{
				log.error("同步企业部门出错: "+jsonObject);
			}
		} catch (Exception e) {
			log.error("同步企业部门异常", e);
		}
	}
	
	public static void main(String[] args) {
		String jsonstr = "{\"id\":1,\"Name\":\"信广龙\",\"Order\":100000000,\"parentId\":5}";
		WxDepartment wxUser = JSON.toJavaObject(JSONObject.parseObject(jsonstr), WxDepartment.class);
		System.out.println(JSON.toJSON(wxUser));
	}
	
}
