package com.dcsoft.system.service.impl;

import com.dcsoft.common.core.exception.ServiceException;
import com.dcsoft.common.core.utils.DateUtils;
import com.dcsoft.common.core.utils.StringUtils;
import com.dcsoft.common.datascope.annotation.DataScope;
import com.dcsoft.system.domain.SysBranch;
import com.dcsoft.system.domain.SysPeopleOther;
import com.dcsoft.system.domain.vo.JjDivisionVo;
import com.dcsoft.system.mapper.SysBranchMapper;
import com.dcsoft.system.mapper.SysPeopleOtherMapper;
import com.dcsoft.system.service.ISysPeopleOtherService;
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 static com.dcsoft.common.core.utils.PageUtils.startPage;


/**
 * 人员管理Service业务层处理
 *
 * @author nichun
 * @date 2023-03-08
 */
@Service
public class SysPeopleOtherServiceImpl implements ISysPeopleOtherService
{
    @Autowired
    private SysPeopleOtherMapper sysPeopleOtherMapper;

    @Autowired
    private SysBranchMapper sysBranchMapper;


    /**
     * 查询人员管理
     *
     * @param id 人员管理主键
     * @return 人员管理
     */
    @Override
    public SysPeopleOther selectSysPeopleOtherById(Long id)
    {
        return sysPeopleOtherMapper.selectSysPeopleOtherById(id);
    }

    /**
     * 查询人员管理列表
     *
     * @param sysPeople 人员管理
     * @return 人员管理
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysPeopleOther> selectSysPeopleOtherList(SysPeopleOther sysPeople)
    {
        List<String> listStr = new ArrayList<>();
        if(!"0".equals(sysPeople.getBranchId()) && StringUtils.isNotEmpty(sysPeople.getBranchId())) {
            List<JjDivisionVo> list = sysBranchMapper.selectBranchTreeOther(sysPeople);
            List<JjDivisionVo> list1 = new ArrayList<>();
            getParentNode(list1, list, sysPeople.getBranchId());
            listStr = list1.stream().map(JjDivisionVo::getId).collect(Collectors.toList());
            listStr.add(sysPeople.getBranchId());
        }
//        if(org.apache.commons.lang3.StringUtils.isNotEmpty(sysPeople.getBranchId())) {
//            listStr.add(sysPeople.getBranchId());
//        }
        startPage();
        sysPeople.setDelFlag(0L);
        return sysPeopleOtherMapper.selectSysPeopleOtherList(sysPeople, listStr);
    }


    @Override
    public List<SysPeopleOther> queryPeopleList(SysPeopleOther sysPeople) {
        List<String> listStr = new ArrayList<>();
        if(!"0".equals(sysPeople.getBranchId()) && StringUtils.isNotEmpty(sysPeople.getBranchId())) {
            List<JjDivisionVo> list = sysBranchMapper.selectBranchTreeOther(sysPeople);
            List<JjDivisionVo> list1 = new ArrayList<>();
            getParentNode(list1, list, sysPeople.getBranchId());
            listStr = list1.stream().map(JjDivisionVo::getId).collect(Collectors.toList());
            listStr.add(sysPeople.getBranchId());
        }

        sysPeople.setDelFlag(0L);
        List<SysPeopleOther> sysPeople1 = sysPeopleOtherMapper.selectSysPeopleOtherList(sysPeople, listStr);
        for (SysPeopleOther people : sysPeople1) {
            people.setName(people.getName() + "-" + people.getPhone());
        }
        return sysPeople1;
    }


    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysPeopleOther> selectSysPeopleOtherLists(SysPeopleOther sysPeople)
    {
        List<String> listStr = new ArrayList<>();
        if(!"0".equals(sysPeople.getBranchId()) && StringUtils.isNotEmpty(sysPeople.getBranchId())) {
            List<JjDivisionVo> list = sysBranchMapper.selectBranchTreeOther(sysPeople);
            List<JjDivisionVo> list1 = new ArrayList<>();
            getParentNode(list1, list, sysPeople.getBranchId());
            listStr = list1.stream().map(JjDivisionVo::getId).collect(Collectors.toList());
            listStr.add(sysPeople.getBranchId());
        }
        sysPeople.setDelFlag(0L);
        return sysPeopleOtherMapper.selectSysPeopleOtherList(sysPeople, listStr);
    }

    private void getParentNode(List<JjDivisionVo> childMenu, List<JjDivisionVo> menuList, String pid) {
        menuList.stream()
                //过滤出父id等于参数的id
                .filter(menu -> StringUtils.isNotBlank(menu.getParentId()) && menu.getParentId().equals(pid))
                .forEach(menu -> {
                    //递归遍历下一级
                    getParentNode(childMenu, menuList, menu.getId());
                    //添加
                    childMenu.add(menu);
                });
    }

    /**
     * 新增人员管理
     *
     * @param sysPeople 人员管理
     * @return 结果
     */
    @Override
    public int insertSysPeopleOther(SysPeopleOther sysPeople)
    {
        sysPeople.setCreateTime(DateUtils.getNowDate());
        return sysPeopleOtherMapper.insertSysPeopleOther(sysPeople);
    }

    /**
     * 修改人员管理
     *
     * @param sysPeople 人员管理
     * @return 结果
     */
    @Override
    public int updateSysPeopleOther(SysPeopleOther sysPeople)
    {
        sysPeople.setUpdateTime(DateUtils.getNowDate());
        return sysPeopleOtherMapper.updateSysPeopleOther(sysPeople);
    }

    /**
     * 批量删除人员管理
     *
     * @param ids 需要删除的人员管理主键
     * @return 结果
     */
    @Override
    public int deleteSysPeopleOtherByIds(Long[] ids)
    {

        return sysPeopleOtherMapper.deleteSysPeopleOtherByIds(ids);
    }

    /**
     * 删除人员管理信息
     *
     * @param id 人员管理主键
     * @return 结果
     */
    @Override
    public int deleteSysPeopleOtherById(Long id)
    {
        return sysPeopleOtherMapper.deleteSysPeopleOtherById(id);
    }

    @Override
    public SysPeopleOther selectByGuid(SysPeopleOther sysPeople) {
        return sysPeopleOtherMapper.selectByGuid(sysPeople);
    }

    @Override
    public SysPeopleOther selectSysPeopleByUserId(Long userId) {
        return sysPeopleOtherMapper.selectSysPeopleOtherByUserId(userId);
    }

    @Override
    public SysPeopleOther selectSysPeopleByBranchUser(String branchName, String userName) {
        return sysPeopleOtherMapper.selectSysPeopleOtherByBranchUser(branchName,userName);
    }

    @Override
    public SysPeopleOther selectSysPeopleByPhoneUser(SysPeopleOther sysPeople) {
        return sysPeopleOtherMapper.selectSysPeopleOtherByPhoneUser(sysPeople);
    }

    @Override
    public List<SysPeopleOther> queryPeopleInfo() {
        return sysPeopleOtherMapper.queryPeopleInfo();
    }

    /**
     * 查询ids
     */
    @Override
    public List<SysPeopleOther> queryPeople(List<String> collectStr) {
        return sysPeopleOtherMapper.queryPeople(collectStr);
    }

    /**
     * 查询人员详情
     */
    @Override
    public SysPeopleOther queryPeopleDetails(String details) {
        return sysPeopleOtherMapper.queryPeopleDetails(details);
    }

    @Override
    public int updateSysPeoples(SysPeopleOther sysPeople) {
        //规则下发
        return sysPeopleOtherMapper.updateSysPeopleOther(sysPeople);
    }

    @Override
    public int insertSysPeoples(SysPeopleOther sysPeople) {
         int i=sysPeopleOtherMapper.insertSysPeopleOther(sysPeople);
        return i;
    }

    @Override
    public int deleteSysPeopleOtherByGuid(String guid) {
        //规则下发
        return sysPeopleOtherMapper.deleteSysPeopleOtherByGuid(guid);
    }

    @Override
    public void updatePeople(SysPeopleOther people) {
        sysPeopleOtherMapper.updatePeople(people);
    }

    @Override
    public String selectDoorNo(Long id) {
        return sysPeopleOtherMapper.selectDoorNo(id);
    }

    @Override
    public String selectPeopleById(String card) {
        return sysPeopleOtherMapper.selectPeopleById(card);
    }

    @Override
    public void updatePeopleInfo(SysPeopleOther sysPeople) {
        sysPeopleOtherMapper.updatePeopleInfo(sysPeople);
    }

    @Override
    public SysPeopleOther queryPeopleById(String id) {
        return sysPeopleOtherMapper.queryPeopleById(id);
    }

    @Override
    public SysPeopleOther selectSysPeopleByOpenId(String openid) {
        return sysPeopleOtherMapper.selectSysPeopleOtherByOpenId(openid);
    }

    @Override
    public SysPeopleOther selectSysPeopleByGh(String phone,String name) {
        return sysPeopleOtherMapper.selectSysPeopleOtherGh(phone,name);
    }

    @Override
    public SysPeopleOther queryPeopleName(String phone) {
        return sysPeopleOtherMapper.queryPeopleName(phone);
    }




    /**
     * 导入用户数据
     *
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importPeople(List<SysPeopleOther> userList, boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SysPeopleOther user : userList)
        {
            try
            {
                // 验证是否存在这个用户
                SysPeopleOther u = sysPeopleOtherMapper.selectSysPeopleOtherByPhoneUser(user);
                SysBranch branch=new SysBranch();
                branch.setName(user.getBranchName());
                List<SysBranch> branchlist=sysBranchMapper.selectSysBranchList(branch);
                if(branchlist.size()>0){
                    user.setBranchId(branchlist.get(0).getId());
                }
                if (StringUtils.isNull(u))
                {
                    this.insertSysPeopleOther(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、手机号 " + user.getPhone() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    this.updateSysPeopleOther(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、手机号 " + user.getPhone() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、手机号 " + user.getPhone() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、手机号 " + user.getPhone() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }


}
