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.core.utils.uuid.IdUtils;
import com.dcsoft.common.datascope.annotation.DataScope;
import com.dcsoft.system.api.domain.SysUser;
import com.dcsoft.system.domain.SysBranch;
import com.dcsoft.system.domain.SysPeople;
import com.dcsoft.system.domain.vo.JjDivisionVo;
import com.dcsoft.system.domain.vo.OfficialAccountVo;
import com.dcsoft.system.mapper.SysBranchMapper;
import com.dcsoft.system.mapper.SysPeopleMapper;
import com.dcsoft.system.service.ISysPeopleService;
import com.dcsoft.system.service.ISysSyncRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
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 SysPeopleServiceImpl implements ISysPeopleService
{
    @Autowired
    private SysPeopleMapper sysPeopleMapper;

    @Autowired
    private SysBranchMapper sysBranchMapper;

    @Autowired
    private ISysSyncRuleService syncRuleService;



    /**
     * 查询人员管理
     *
     * @param id 人员管理主键
     * @return 人员管理
     */
    @Override
    public SysPeople selectSysPeopleById(Long id)
    {
        return sysPeopleMapper.selectSysPeopleById(id);
    }

    /**
     * 查询人员管理列表
     *
     * @param sysPeople 人员管理
     * @return 人员管理
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysPeople> selectSysPeopleList(SysPeople sysPeople)
    {
        List<String> listStr = new ArrayList<>();
        if(!"1".equals(sysPeople.getBranchId())) {
            List<JjDivisionVo> list = sysBranchMapper.selectBranchTree(sysPeople);
            List<JjDivisionVo> list1 = new ArrayList<>();
            if(StringUtils.isNotEmpty(sysPeople.getBranchId())) {
                getParentNode(list1, list, sysPeople.getBranchId());
            } else {
                list1.addAll(list);
            }
            listStr = list1.stream().map(JjDivisionVo::getId).collect(Collectors.toList());
            listStr.add(sysPeople.getBranchId());
        }
        startPage();
        sysPeople.setDelFlag(0L);
        return sysPeopleMapper.selectSysPeopleList(sysPeople, listStr);
    }


    @Override
    public List<SysPeople> queryPeopleList(SysPeople sysPeople) {
        List<String> listStr = new ArrayList<>();
        if(!"0".equals(sysPeople.getBranchId()) && StringUtils.isNotEmpty(sysPeople.getBranchId())) {
            List<JjDivisionVo> list = sysBranchMapper.selectBranchTree(null);
            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<SysPeople> sysPeople1 = sysPeopleMapper.selectSysPeopleList(sysPeople, listStr);
        for (SysPeople people : sysPeople1) {
            people.setName(people.getName() + "-" + people.getPhone());
        }
        return sysPeople1;
    }

    @Override
    public SysPeople selectSysPeopleByGh(String gh) {
        return sysPeopleMapper.selectSysPeopleByGh(gh);
    }

    @Override
    public SysPeople selectSysPeopleByDoorNo(String doorNo) {
        return sysPeopleMapper.selectSysPeopleByDoorNo(doorNo);
    }

    @Override
    public SysPeople queryEmpowerRecord(String phone) {
        return sysPeopleMapper.queryEmpowerRecord(phone);
    }

    @Override
    public SysPeople queryPeopleByOpenid(String openid) {
        return sysPeopleMapper.queryPeopleByOpenid(openid);
    }

    /**
     * 通过职位标签查询人员信息
     * @param position
     * @return
     */
    @Override
    public List<SysPeople> queryPeopleByPosition(String position) {
        return sysPeopleMapper.queryPeopleByPosition(position);
    }

    @Override
    public List<SysPeople> querySysPeopleInfo(Long userId) {
        return sysPeopleMapper.querySysPeopleInfo(userId);
    }

    @Override
    public Long selectAppSysPeople(SysUser sysUser) {
        return sysPeopleMapper.selectAppSysPeople(sysUser);
    }

    @Override
    public List<SysPeople> selectSysPeopleListByIds(List<Long> list) {
        return sysPeopleMapper.selectSysPeopleListByIds(list);
    }

    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysPeople> selectSysPeopleLists(SysPeople sysPeople)
    {
        List<String> listStr = new ArrayList<>();
        if(!"0".equals(sysPeople.getBranchId())) {
            List<JjDivisionVo> list = sysBranchMapper.selectBranchTree(sysPeople);
            List<JjDivisionVo> list1 = new ArrayList<>();
            if(StringUtils.isNotEmpty(sysPeople.getBranchId())) {
                getParentNode(list1, list, sysPeople.getBranchId());
            } else {
                list1.addAll(list);
            }
            listStr = list1.stream().map(JjDivisionVo::getId).collect(Collectors.toList());
            listStr.add(sysPeople.getBranchId());
        }
        sysPeople.setDelFlag(0L);
        return sysPeopleMapper.selectSysPeopleList(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 insertSysPeople(SysPeople sysPeople)
    {
        sysPeople.setCreateTime(DateUtils.getNowDate());
        syncRuleService.addPeople(sysPeople,"add");
        return sysPeopleMapper.insertSysPeople(sysPeople);
    }

    /**
     * 修改人员管理
     *
     * @param sysPeople 人员管理
     * @return 结果
     */
    @Override
    public int updateSysPeople(SysPeople sysPeople)
    {
        sysPeople.setUpdateTime(DateUtils.getNowDate());
        if (!"10".equals(sysPeople.getWxFlag())) {
            syncRuleService.addPeople(sysPeople,"update");
        }
        return sysPeopleMapper.updateSysPeople(sysPeople);
    }

    /**
     * 批量删除人员管理
     *
     * @param ids 需要删除的人员管理主键
     * @return 结果
     */
    @Override
    public int deleteSysPeopleByIds(Long[] ids)
    {
        for(Long id:ids){
            SysPeople branch=new SysPeople();
            branch.setId(id);
            syncRuleService.addPeople(branch,"delete");
        }
        return sysPeopleMapper.deleteSysPeopleByIds(ids);
    }

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

    @Override
    public SysPeople selectByGuid(SysPeople sysPeople) {
        return sysPeopleMapper.selectByGuid(sysPeople);
    }

    @Override
    public SysPeople selectSysPeopleByUserId(Long userId) {
        return sysPeopleMapper.selectSysPeopleByUserId(userId);
    }

    @Override
    public SysPeople selectSysPeopleByBranchUser(String branchName, String userName) {
        return sysPeopleMapper.selectSysPeopleByBranchUser(branchName,userName);
    }

    @Override
    public SysPeople selectSysPeopleByPhoneUser(SysPeople sysPeople) {
        return sysPeopleMapper.selectSysPeopleByPhoneUser(sysPeople);
    }

    @Override
    public List<SysPeople> queryPeopleInfo() {
        return sysPeopleMapper.queryPeopleInfo();
    }

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

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

    @Override
    public int updateSysPeoples(SysPeople sysPeople) {
        //规则下发
        return sysPeopleMapper.updateSysPeople(sysPeople);
    }

    @Override
    public int insertSysPeoples(SysPeople sysPeople) {
         int i=sysPeopleMapper.insertSysPeople(sysPeople);
        return i;
    }

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

    @Override
    public void updatePeople(SysPeople people) {
        sysPeopleMapper.updatePeople(people);
    }

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

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

    @Override
    public void updatePeopleInfo(SysPeople sysPeople) {
        sysPeopleMapper.updatePeopleInfo(sysPeople);
    }

    @Override
    public OfficialAccountVo queryPeopleById(String id) {
        return sysPeopleMapper.queryPeopleById(id);
    }

    @Override
    public SysPeople selectSysPeopleByOpenId(String openid) {
        return sysPeopleMapper.selectSysPeopleByOpenId(openid);
    }

    @Override
    public SysPeople selectSysPeopleByGh(String phone,String name) {
        return sysPeopleMapper.selectSysPeopleGh(phone,name);
    }

    @Override
    public SysPeople queryPeopleName(String phone, List<String> collect) {
        return sysPeopleMapper.queryPeopleName(phone, collect);
    }




    /**
     * 导入用户数据
     *
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importPeople(List<SysPeople> 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 (SysPeople user : userList)
        {
            try
            {
                // 验证是否存在这个用户
                SysPeople u = sysPeopleMapper.selectSysPeopleByGh(user.getGh());
                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))
                {
                    user.setGuid(IdUtils.simpleUUID());
                    this.insertSysPeople(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、工号 " + user.getGh() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    this.updateSysPeople(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、工号 " + user.getGh() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、工号 " + user.getGh() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、工号 " + user.getGh() + " 导入失败：";
                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();
    }
}
