package com.jeeplus.modules.wexinpackage.access.service;

import com.alibaba.fastjson.JSONObject;
import com.jeeplus.common.utils.JedisUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.sys.dao.OfficeDao;
import com.jeeplus.modules.sys.dao.UserDao;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.service.RoleService;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.service.UserService;
import com.jeeplus.modules.wexinpackage.access.entity.ChangeNumber;
import com.jeeplus.modules.wexinpackage.access.util.access.AccessTokenUtil;
import com.jeeplus.modules.wexinpackage.access.util.access.AddressBookUtil;
import com.jeeplus.modules.wexinpackage.access.util.access.ContactUtil;
import com.jeeplus.modules.wexinpackage.access.util.access.WeChatParamsUtil;
import com.jeeplus.modules.workstaff.dao.WorkStaffBasicInfoDao;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
import com.jeeplus.modules.workstaff.service.WorkStaffBasicInfoService;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 操作用户Service
 */
@Service
public class WeChatCallbackService {
    @Autowired
    private UserService userService;
    @Autowired
    private OfficeService officeService;
    @Autowired
    private OfficeDao officeDao;
    @Autowired
    private WorkStaffBasicInfoService workStaffBasicInfoService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private WorkStaffBasicInfoDao workStaffBasicInfoDao;
    @Autowired
    private UserDao userDao;

    //操作 :判断事件类型
    public void getMapOperation(String sMsg, HttpServletRequest request){
        Document doc = null;
        try {
            doc = DocumentHelper.parseText(sMsg);
            Element root = doc.getRootElement();
            // 获取根节点下的所有元素
            List list = root.elements();
            Map<String,String> map = new HashMap<String, String>();
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    Element child = (Element) list.get(i);
                    //xml转Map
                    map.put(child.getName(),child.getTextTrim());
                }
            }
            ChangeNumber changeNumber = ContactUtil.map2Object(map, ChangeNumber.class);
            if (null!=changeNumber){
                //获取通讯口事件 判断事件类型
                if (changeNumber.getEvent().equals(ContactUtil.CHANGE_CONTACT)) {
                    getJudgeCDUSType(changeNumber,request);
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
    //判断事件类型 增删改查
    public void getJudgeCDUSType(ChangeNumber changeNumber,HttpServletRequest request){
        switch (changeNumber.getChangeType()){
            case ContactUtil.UPDATE_USER:
                getUpdateTotal(changeNumber,request);
                break;
            case ContactUtil.CREATE_USER:
                String s = JedisUtils.get(changeNumber.getUserID()+"create");
                if (null != s){
                    if (!s.equals(changeNumber.getUserID())){
                        JedisUtils.set(changeNumber.getUserID()+"create",changeNumber.getUserID(),10000);
                        getCreateTotal(changeNumber,request);
                    }
                }else {
                    JedisUtils.set(changeNumber.getUserID()+"create",changeNumber.getUserID(),10000);
                    getCreateTotal(changeNumber,request);
                }
                break;
            case ContactUtil.DELETE_USER:
                    getDeleteTotal(changeNumber);
                break;
        }
    }
    //增加操作
    public void getCreateTotal(ChangeNumber changeNumber,HttpServletRequest request){
        Office office = new Office();
        String department = changeNumber.getDepartment();
        String[] split = department.split(",");
        if (split.length>1){
            department = split[0];
            if (department.equals("1")){
                department = split[1];
            }
        }
        if (department.equals("1")){
            changeNumber.setDepartment("2");
        }
        changeNumber.setDepartment(department);
        office.setWxOfficeId(changeNumber.getDepartment());
        List<Office> offices = officeDao.findListByWxName(office);
        WorkStaffBasicInfo workStaffBasicInfo = new WorkStaffBasicInfo();
        List<Role> byOfficeId = null;
        if (null!=offices && offices.size()>0){
            byOfficeId = roleService.getByOfficeId(offices.get(0).getId());
        }
        String roleId = "";
        if (null!=byOfficeId && byOfficeId.size()>0){
            roleId = byOfficeId.get(0).getId();
        }else {
            roleId = "1";
        }
        WorkStaffBasicInfo createWorkStaffBasicInfo = ContactUtil.getCreateWorkStaffBasicInfo(roleId,offices.get(0),workStaffBasicInfo, changeNumber);
        try {
            //可变动
            Office branchOffice = new Office();
            branchOffice.setId(workStaffBasicInfo.getCompany().getId());
            workStaffBasicInfo.setBranchOffice(branchOffice);
            workStaffBasicInfo.setNo(getNo(createWorkStaffBasicInfo));
            User user = new User();
            user = this.createUser(workStaffBasicInfo);
            User user1 = userService.findUniqueByProperty("mobile", workStaffBasicInfo.getMobile());
            if (null==user1){
                user.setWeChatId(changeNumber.getUserID());
                boolean b = userService.save(user, request, null);
                workStaffBasicInfoService.save(createWorkStaffBasicInfo, request);//保存
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //修改操作
    public void getUpdateTotal(ChangeNumber changeNumber,HttpServletRequest request){
        Office office = new Office();
        List<Office> offices = null;
        if (null!=changeNumber.getDepartment()){
            String department = changeNumber.getDepartment();
            String[] split = department.split(",");
            if (split.length>1){
                department = split[0];
                if (department.equals("1")){
                    department = split[1];
                }
            }
            if (department.equals("1")){
                changeNumber.setDepartment("2");
            }
            changeNumber.setDepartment(department);
            office.setWxOfficeId(changeNumber.getDepartment());
            offices = officeDao.findListByWxName(office);
        }else {
            office.setName("财务部");
            offices = officeDao.findListByCompanyName(office);
        }
        WorkStaffBasicInfo workStaffBasicInfo = new WorkStaffBasicInfo();
        List<Role> byOfficeId = null;
        if (null!=offices && offices.size()>0){
            byOfficeId = roleService.getByOfficeId(offices.get(0).getId());
        }
        String roleId = "";
        if (null!=byOfficeId && byOfficeId.size()>0){
            roleId = byOfficeId.get(0).getId();
        }else {
            roleId = "1";
        }
        WorkStaffBasicInfo createWorkStaffBasicInfo = ContactUtil.getCreateWorkStaffBasicInfo(roleId,offices.get(0),workStaffBasicInfo, changeNumber);
        String userNo = userDao.findUserNo(changeNumber.getUserID());
        WorkStaffBasicInfo no = workStaffBasicInfoService.findNo(userNo);
        WorkStaffBasicInfo t = workStaffBasicInfoService.get(no.getId());//从数据库取出记录的值
        createWorkStaffBasicInfo.setIsNewRecord(false);
        try {
            MyBeanUtils.copyBeanNotNull2Bean(createWorkStaffBasicInfo, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
            t.setIsNewRecord(false);
            workStaffBasicInfoService.save(t,request);//保存
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除操作
    public void getDeleteTotal(ChangeNumber changeNumber){
        String userNo = userDao.findUserNo(changeNumber.getUserID());
        WorkStaffBasicInfo workStaffBasicInfo = workStaffBasicInfoService.findNo(userNo);
        if (null!=workStaffBasicInfo){
            workStaffBasicInfoService.delete(workStaffBasicInfo);
        }
    }

    //查询操作
    public void getSelectTotal(){

    }

    public String getNo(WorkStaffBasicInfo workStaffBasicInfo){
        String no = workStaffBasicInfoDao.queryMaxNoWithCompany(workStaffBasicInfo);
        String newNo = "000000";
        if(StringUtils.isNotBlank(no)){
            Integer integer = Integer.valueOf(no);
            integer+=1;
            no = String.valueOf(integer);
        }
        newNo = newNo+no;
        return newNo;
    }

    private User createUser(WorkStaffBasicInfo workStaffBasicInfo) {
        User user = new User();
        user.setOffice(workStaffBasicInfo.getOffice());
        user.setCompany(workStaffBasicInfo.getCompany());
        user.setComId(workStaffBasicInfo.getCompany().getId());
        user.setNo(workStaffBasicInfo.getNo());
        user.setName(workStaffBasicInfo.getName());
        user.setMobile(workStaffBasicInfo.getMobile());
        user.setNewPassword("123456");
        user.setLoginName(workStaffBasicInfo.getMobile());
        user.setEmail(workStaffBasicInfo.getEmail());
        user.setSex(workStaffBasicInfo.getGender());
        user.setLoginFlag("1");
        user.setFirstFlag("0");
        return user;
    }
}
