package com.gz.service.system.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gz.dto.system.AdminDTO;
import com.gz.dto.system.DeptDTO;
import com.gz.mapper.system.AdminMapper;
import com.gz.mapper.system.DeptMapper;
import com.gz.rvo.system.AdminRVO;
import com.gz.service.system.AdminService;
import com.gz.utils.JwtUtils;
import com.gz.utils.PasswordUtils;
import com.gz.vo.system.AdminVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LiuchangLan
 * @date 2020/9/4 14:42
 */
@Slf4j
@Service
public class AdminServiceImpl implements AdminService {

    @Resource
    private AdminMapper adminMapper;

    @Resource
    private DeptMapper deptMapper;

    @Override
    public Integer insert(AdminDTO adminDTO) {
        // 盐
        adminDTO.setSalt(IdUtil.simpleUUID());
        // 加密后密码
        adminDTO.setPassword(PasswordUtils.encryption(adminDTO.getPassword(), adminDTO.getSalt()));
        // 创建人
        adminDTO.setCreated(JwtUtils.getCurrentUserJwtPayload().getId());
        // 执行入库
        return adminMapper.insertSelective(adminDTO);
    }

    @Override
    public Integer delete(String id) {
        return adminMapper.deleteById(id);
    }

    @Override
    public Integer update(AdminDTO adminDTO) {
        // 修改人
        adminDTO.setUpdated(JwtUtils.getCurrentUserJwtPayload().getId());
        // 修改时间
        adminDTO.setUpdateTime(DateUtil.now());
        // 执行入库
        return adminMapper.updateByPrimaryKeySelective(adminDTO);
    }

    @Override
    public PageInfo<AdminDTO> select(AdminVO adminVO) {
        // 包含分页参数执行分页
        if (adminVO.getPageNum() != null && adminVO.getPageSize() != null) {
            PageHelper.startPage(adminVO.getPageNum(), adminVO.getPageSize());
        }
        // 查询未删除的数据
        return new PageInfo<>(adminMapper.selectByPage(adminVO));
    }

    @Override
    public AdminDTO selectByPrimaryKey(String id) {
        AdminDTO adminDTO = adminMapper.selectByPrimaryKey(id);
        if (adminDTO.getRoleId() == null) {
            DeptDTO deptDTO = null;
            // 循环查找部门权限 没有就向上找 知道找到为止
            deptDTO = deptMapper.selectByPrimaryKey(adminDTO.getDeptId());
            while (deptDTO != null && null == deptDTO.getRoleId()) {
                deptDTO = deptMapper.selectByPrimaryKey(deptDTO.getParentId());
            }
            adminDTO.setRoleId(deptDTO.getRoleId());
        }
        return adminDTO;
    }

    @Override
    public Integer updateStatus(String id) {
        AdminDTO adminDTO = adminMapper.selectByPrimaryKey(id);
        if (adminDTO.getStatus().equals(0)) {
            adminDTO.setStatus(1);
        } else {
            adminDTO.setStatus(0);
        }
        return adminMapper.updateByPrimaryKeySelective(adminDTO);
    }

    @Override
    public Integer resetPassword(String id) {
        AdminDTO adminDTO = selectByPrimaryKey(id);
        // 盐
        adminDTO.setSalt(IdUtil.simpleUUID());
        // 加密后密码
        adminDTO.setPassword(PasswordUtils.encryption("123456", adminDTO.getSalt()));
        return update(adminDTO);
    }

    @Override
    public List<AdminDTO> selectAll() {
        return adminMapper.selectAll();
    }

    @Override
    public AdminRVO selectByPrimaryKeyDept(String id) {
        return adminMapper.selectByPrimaryKeyDept(id);
    }

    @Override
    @Transactional
    public Map<String,Object> synchronize(Map<String, Object> params) {
        try {
            // 发起同步的用户登录名
            String loginName = params.get("loginName").toString();
            // 发起同步时间
            String syncTime = params.get("syncTime").toString();
            // 同步内容描述
            Object syncDesc = params.get("syncDesc");
            // 同步的部门
            List<Map<String, Object>> org = new ArrayList<>();
            List<Map<String, Object>> position = new ArrayList<>();
            List<Map<String, Object>> user = new ArrayList<>();

            if (params.get("org") != null) {
                org = (List<Map<String, Object>>) params.get("org");
            }
            // 同步的职位
            if (params.get("position") != null) {
                position = (List<Map<String, Object>>) params.get("position");
            }
            // 同步的用户
            if (params.get("user") != null) {
                user = (List<Map<String, Object>>) params.get("user");
            }

            log.info("用户{}在{}发起了同步，发起了{}条部门信息、{}条职位信息、{}条用户信息", loginName, syncTime, org.size(), position.size(),user.size());
            log.info("接受到的参数:{}", JSON.toJSON(params));
            log.info("同步内容描述:{}", syncDesc);

            for (Map<String, Object> map : org) {
                String id = String.valueOf(map.get("guid"));
                DeptDTO deptPcDTO = new DeptDTO();
                deptPcDTO.setDeptName(String.valueOf(map.get("fullName")));
                deptPcDTO.setId(id);
                deptPcDTO.setParentId(String.valueOf(map.get("parentGuid")));
                deptPcDTO.setDeptOrder(Integer.parseInt(String.valueOf(map.get("sortno"))));
                String state = String.valueOf(map.get("state"));
                if ("1".equals(state)) {
                    if (deptMapper.existsWithPrimaryKey(id)) {
                        deptMapper.updateByPrimaryKeySelective(deptPcDTO);
                    }else {
                        deptMapper.insertSelective(deptPcDTO);
                    }
                }else if ("2".equals(state)) {
                    //删除
                    deptMapper.deleteByPrimaryKey(id);
                }
            }
            for (Map<String, Object> map : user) {
                AdminDTO adminDTO = new AdminDTO();

                adminDTO.setId(String.valueOf(map.get("guid") == null ? "" : map.get("guid")));
                adminDTO.setAdminName(String.valueOf(map.get("userName") == null ? "" : map.get("userName")));
                adminDTO.setAccount(String.valueOf(map.get("loginName") == null ? "" : map.get("loginName")));
                adminDTO.setPhone(String.valueOf(map.get("mobilephone") == null ? "" : map.get("mobilephone")));
                String state = String.valueOf(map.get("state") == null ? "" : map.get("state"));
                // 根据用户姓名和用户账号查询用户
                List<AdminDTO> adminVOS = this.adminMapper.selectByPage(new AdminVO(adminDTO.getAdminName(),adminDTO.getAccount()));
                //正常
                if ("1".equals(state)) {
                    List<String> deptids = (List<String>) map.get("orgGuid");
                    if (adminMapper.existsWithPrimaryKey(adminDTO.getId())) {
                        for (String deptid : deptids) {
                            adminDTO.setDeptId(deptid);
                            // 现有用户同步不改变用户角色（新增用户默认普通用户）
                            if(CollectionUtils.isNotEmpty(adminVOS)){
                                adminDTO.setRoleId(adminVOS.get(0).getRoleId());
                            }
                            adminMapper.updateByPrimaryKeySelective(adminDTO);
                        }
                    }else {
                        for (String deptid : deptids) {
                            adminDTO.setDeptId(deptid);
                            // 普通用户
                            adminDTO.setRoleId(8);
                            adminMapper.insertSelective(adminDTO);
                        }
                    }
                } else if ("2".equals(state)) {
                    //删除
                    adminMapper.deleteByPrimaryKey(adminDTO.getId());
                }
            }
            return new HashMap<String,Object>(){{
                put("data","成功");
                put("status","success");
            }};
        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap<String,Object>(){{
                put("data",e.getMessage());
                put("status","fail");
            }};
        }
    }
}
