package com.bonus.gs.sub.evaluate.evaluate.service;

import com.bonus.gs.sub.evaluate.evaluate.beans.OrganizationalBean;
import com.bonus.gs.sub.evaluate.evaluate.beans.TeamEvaluateBean;
import com.bonus.gs.sub.evaluate.evaluate.controller.OrganizationalController;
import com.bonus.gs.sub.evaluate.evaluate.dao.OrganizationalDao;
import com.bonus.gs.sub.evaluate.manager.utils.AjaxRes;
import com.bonus.gs.sub.evaluate.manager.utils.CipherHelper;
import com.bonus.gs.sub.evaluate.manager.utils.StringHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * @author 黑子
 */
@Service("OrganizationalService")
public class OrganizationalServiceImpl implements OrganizationalService {
    private static final Logger logger = Logger.getLogger(String.valueOf(OrganizationalController.class));
    @Autowired
    private OrganizationalDao mapper;
    public static String DEFEAT_P_ID = "0";

    /**
     * 上级节点下拉选
     *
     * @param bean
     * @return
     */
    @Override
    public List<OrganizationalBean> getDeptSelected(OrganizationalBean bean) {
        try {
            return mapper.getDeptSelected(bean);
        } catch (Exception e) {
        }
        return new ArrayList<>();
    }

    /**
     * 外包商下拉选
     *
     * @param bean
     * @return
     */
    @Override
    public List<OrganizationalBean> getOutSourceSelected(OrganizationalBean bean) {
        try {
            return mapper.getOutSourceSelected(bean);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return new ArrayList<>();
    }

    /**
     * 新增人员下拉选
     *
     * @param bean
     * @return
     */
    @Override
    public List<OrganizationalBean> getAddUserSelected(OrganizationalBean bean) {
        try {
            if (StringHelper.isNotEmpty(bean.getIsAdd())) {
                return mapper.getAddUserSelected(bean);
            } else {
                OrganizationalBean data = mapper.getDataDetails(bean);
                return mapper.getTeamUser(data);
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return new ArrayList<>();
    }

    /**
     * 查询树
     *
     * @param bean
     * @return
     */
    @Override
    public List<OrganizationalBean> getTreeList(OrganizationalBean bean) {
        try {
            List<OrganizationalBean> list = mapper.getTreeList(bean);
            return buildTree(list);

        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return new ArrayList<>();
    }

    /**
     * 新增数据
     *
     * @param bean
     * @return
     */
    @Override
    public AjaxRes addData(OrganizationalBean bean) {
        AjaxRes ar = new AjaxRes();
        try {
            if (bean.getLevel() == 0) {
                ar.setFailMsg("请选择层级");
                return ar;
            } else if (bean.getLevel() == 5) {
                int userNum = mapper.getUserNum(bean);
                if (userNum > 0) {
                    ar.setFailMsg("该人员已存在");
                    return ar;
                }
                int teamName = mapper.getTeamName(bean);
                if (teamName > 0) {
                    ar.setFailMsg("该班组名称已存在");
                    return ar;
                }
//                String pwrs = "gsks@123";// 随机密码,以后发邮箱
//                String pwrsMD5 = CipherHelper.generatePassword(pwrs);// 第一次加密md5，
//                String salt = CipherHelper.createSalt();
//                bean.setSalt(salt);
//                bean.setPassword(pwrsMD5);
            }else if (bean.getLevel() == 4){
                int count = mapper.getConsIsExistByPro(bean);
                if (count > 0) {
                    ar.setFailMsg("该承包商在此项目下已存在");
                    return ar;
                }
            }
            int num = mapper.addData(bean);
            if (num > 0) {
                ar.setSucceed("新增成功");
                return ar;
            }
            ar.setFailMsg("新增失败,请联系管理员");
            return ar;
        } catch (Exception e) {
            logger.error(e.toString(), e);
            ar.setFailMsg("新增失败,请联系管理员");
        }
        return ar;
    }


    public OrganizationalBean getParentInfo(OrganizationalBean bean) {
        OrganizationalBean vo = new OrganizationalBean();
        vo.setId(bean.getParentId());
        OrganizationalBean parentVo = mapper.getDataDetails(vo);
        return parentVo;
    }

    /**
     * 更新班组长
     *
     * @param bean
     * @return
     */
    @Override
    public AjaxRes updateLeader(OrganizationalBean bean) {
        AjaxRes ar = new AjaxRes();
        try {
            //新增
            bean.setDataSource("2");
            OrganizationalBean his = mapper.getDataDetails(bean);
            if (!his.getIdCard().equals(bean.getIdCard())) {
                int userNum = mapper.getUserNum(bean);
                if (userNum > 0) {
                    ar.setFailMsg("该人员已存在");
                    return ar;
                }
            }
            int num = mapper.updateData(bean);
            if (num > 0) {
                ar.setSucceed("修改成功");
                return ar;
            }

        } catch (Exception e) {
            logger.error(e.toString(), e);
            ar.setFailMsg("修改失败");
        }
        return ar;
    }

    /**
     * 依据id查询详情
     *
     * @param bean
     * @return
     */
    @Override
    public AjaxRes getDataDetails(OrganizationalBean bean) {
        AjaxRes ar = new AjaxRes();
        try {
            OrganizationalBean data = mapper.getDataDetails(bean);
            ar.setSucceed(data);
        } catch (Exception e) {
            ar.setSucceed(new OrganizationalBean());
            logger.error(e.toString(), e);
        }
        return ar;
    }

    /**
     * 人员出厂
     *
     * @param bean
     * @return
     */
    @Override
    public AjaxRes userOutData(OrganizationalBean bean) {
        AjaxRes ar = new AjaxRes();
        try {
            OrganizationalBean data = mapper.getDataDetails(bean);
            if (data.getLevel() != 5) {
                ar.setResMsg("外包商退场暂未开放!");
                return ar;
            }

            int num = mapper.userOutData(bean);
//            mapper.theTeamExits(bean);
            if (num > 0) {

                List<OrganizationalBean> userList = mapper.getUserList(data);
                if (userList != null && !userList.isEmpty()) {
                    userList.forEach(vo -> {
                        mapper.insertUserOutData(vo);
                    });
                }
                TeamEvaluateBean teamEvaluateBean = new TeamEvaluateBean();
                teamEvaluateBean.setTeamId(Integer.parseInt(data.getId()));
                teamEvaluateBean.setTeamName(data.getName());
                teamEvaluateBean.setParentId(Integer.parseInt(data.getParentId()));
                teamEvaluateBean.setPhone(data.getUserPhone());
                teamEvaluateBean.setUserName(data.getUserName());
                teamEvaluateBean.setIdCard(data.getIdCard());

                OrganizationalBean P2 = new OrganizationalBean();
                P2.setId(data.getParentId());
                OrganizationalBean data2 = mapper.getDataDetails(P2);
                teamEvaluateBean.setSubId(Integer.parseInt(data2.getTableId()));
                teamEvaluateBean.setSubName(data2.getName());

                OrganizationalBean P3 = new OrganizationalBean();
                P3.setId(data2.getParentId());
                OrganizationalBean data3 = mapper.getDataDetails(P3);
                teamEvaluateBean.setProId(Integer.parseInt(data3.getTableId()));
                teamEvaluateBean.setProName(data3.getName());
                teamEvaluateBean.setOrgRelId(bean.getId());
                mapper.insertTeamData(teamEvaluateBean);
                ar.setSucceed(teamEvaluateBean);
                ar.setMsg("退场成功");
            }
        } catch (Exception e) {
            ar.setResMsg("退场失败");
            logger.error(e.toString(), e);
        }
        return ar;
    }

    @Override
    public AjaxRes addDept(OrganizationalBean bean) {
        AjaxRes ar = new AjaxRes();
        try {
            if (bean.getLevel() == 0) {
                ar.setFailMsg("请选择层级");
                return ar;
            }
            int count = mapper.getTeamName(bean);
            if (count > 0) {
                if ("1".equals(bean.getOrgType())) {
                    ar.setFailMsg("该事业部已存在");
                } else if ("2".equals(bean.getOrgType())) {
                    ar.setFailMsg("该职能部门已存在");
                }
                return ar;
            }
            int num = mapper.addData(bean);
            if (num > 0) {
                ar.setSucceed("新增成功");
                return ar;
            }
            ar.setFailMsg("新增失败,请联系管理员");
            return ar;
        } catch (Exception e) {
            logger.error(e.toString(), e);
            ar.setFailMsg("新增失败,请联系管理员");
        }
        return ar;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxRes userOutDataFail(OrganizationalBean bean) {
        AjaxRes ar = new AjaxRes();
        try {
           mapper.updateUserOutStatus(bean);
           mapper.deleteUserOutData(bean);
            ar.setSucceed("退场失败");
        } catch (Exception e) {
            ar.setResMsg("退场失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ar;
    }

    public static List<OrganizationalBean> buildTree(List<OrganizationalBean> nodes) {
        // 根节点是没有父节点的节点
        List<OrganizationalBean> rootNodes = nodes.stream()
                .filter(node -> node.getParentId().equals(DEFEAT_P_ID))
                .collect(Collectors.toList());
        for (OrganizationalBean rootNode : rootNodes) {
            buildChildren(rootNode, nodes);
        }
        return rootNodes;
    }

    private static void buildChildren(OrganizationalBean parent, List<OrganizationalBean> nodes) {
        List<OrganizationalBean> children = nodes.stream()
                .filter(node -> node.getParentId() != null && node.getParentId().equals(parent.getId()))
                .collect(Collectors.toList());

        if (!children.isEmpty()) {
            for (OrganizationalBean vo:children){
                vo.setParentUserName(parent.getUserName());
            }
            parent.setChildren(children);
            for (OrganizationalBean child : children) {
                buildChildren(child, nodes);
            }
        }
    }
}
