package com.dcsoft.system.service.impl;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dcsoft.common.core.domain.R;
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.file.FileUtils;
import com.dcsoft.common.core.utils.uuid.IdUtils;
import com.dcsoft.common.core.web.domain.AjaxResult;
import com.dcsoft.common.security.utils.SecurityUtils;
import com.dcsoft.system.api.RemoteFileService;
import com.dcsoft.system.api.domain.SysFile;
import com.dcsoft.system.api.domain.SysUser;
import com.dcsoft.system.domain.*;
import com.dcsoft.system.domain.vo.JjDivisionVo;
import com.dcsoft.system.face.domain.FaceImage;
import com.dcsoft.system.face.domain.FaceStudent;
import com.dcsoft.system.kq.domain.KqAdjust;
import com.dcsoft.system.kq.domain.KqGroup;
import com.dcsoft.system.kq.domain.KqGroupUser;
import com.dcsoft.system.kq.mapper.KqGroupMapper;
import com.dcsoft.system.kq.mapper.KqGroupUserMapper;
import com.dcsoft.system.mapper.*;
import com.dcsoft.system.service.ISysRuleService;
import com.dcsoft.system.service.ISysSyncRuleService;
import com.dcsoft.system.service.ISysUserService;
import com.dcsoft.system.uniubi.service.ISysSdkService;
import com.dcsoft.system.utils.ImageToBase64Utils;
import com.dcsoft.system.utils.PictureUtils;
import com.dcsoft.system.utils.ZipUtil;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.dcsoft.system.service.ISysPeopleService;
import com.dcsoft.common.datascope.annotation.DataScope;
import org.springframework.web.multipart.MultipartFile;

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 KqGroupUserMapper kqGroupUserMapper;

    @Autowired
    private KqGroupMapper kqGroupMapper;

    @Autowired
    private ISysSyncRuleService syncRuleService;


    @Autowired
    private SysPeoplePostMapper sysPeoplePostMapper;

    @Autowired
    private SysPeopleEquipmentMapper sysPeopleEquipmentMapper;


    @Autowired
    private ISysUserService userService;


    @Value("${artemis.url}")
    public String url;
    @Value("${artemis.appKey}")
    public String appKey;
    @Value("${artemis.appSecret}")
    public String appSecret;

    private static final String ARTEMIS_PATH = "/artemis";

    @Value("${image.excelShortPath}")
    public String excelShortPath;

    @Autowired
    private RemoteFileService remoteFileService;


    /**
     * 查询人员管理
     *
     * @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(!"0".equals(sysPeople.getBranchId()) && StringUtils.isNotEmpty(sysPeople.getBranchId())) {
            List<JjDivisionVo> list = sysBranchMapper.selectBranchTree();
            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 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();
            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.getGh());
        }
        return sysPeople1;
    }


    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysPeople> selectSysPeopleLists(SysPeople sysPeople)
    {
        List<String> listStr = new ArrayList<>();
        if(!"0".equals(sysPeople.getBranchId()) && StringUtils.isNotEmpty(sysPeople.getBranchId())) {
            List<JjDivisionVo> list = sysBranchMapper.selectBranchTree();
            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 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 sysPeoples=sysPeopleMapper.selectSysPeopleByGhs(sysPeople.getGh());
        if(sysPeoples!=null){
            sysPeopleMapper.deleteSysPeoplesById(sysPeoples.getId());
        }
        sysPeople.setCreateTime(DateUtils.getNowDate());
        sysPeople=hkCreatepeople(sysPeople);
        int i=sysPeopleMapper.insertSysPeople(sysPeople);
        //syncRuleService.addPeople(sysPeople,"add");
        //insertPeoplePost(sysPeople);
        //新建关联用户信息
        insertUser(sysPeople);
        return i;
    }

    private void insertUser(SysPeople sysPeople) {
        SysUser user=new SysUser();
        user.setUserId(sysPeople.getId());
        Long[] roles=new Long[]{100L};
        user.setRoleIds(roles);
        user.setUserName(sysPeople.getGh());
        user.setNickName(sysPeople.getName());
        user.setOpenid(sysPeople.getQwid());
        user.setDeptId(100L);
        user.setPassword(SecurityUtils.encryptPassword(sysPeople.getGh()));
        userService.insertUser(user);
        sysPeople.setUserId(sysPeople.getId());
        sysPeopleMapper.updateSysPeople(sysPeople);
    }

    private SysPeople hkCreatepeople(SysPeople sysPeople) {
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(url); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecret);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/resource/v2/person/single/add";
        Map<String, Object> paramMaps = new HashMap<String, Object>();// post请求Form表单参数
        paramMaps.put("personName", sysPeople.getName());
        if(StringUtils.isEmpty(sysPeople.getSex())){
            sysPeople.setSex("0");
        }
        paramMaps.put("gender", sysPeople.getSex());
        paramMaps.put("orgIndexCode", sysPeople.getBranchId());
        paramMaps.put("phoneNo", sysPeople.getPhone());
        paramMaps.put("certificateNo", sysPeople.getIdcard());
        paramMaps.put("jobNo", sysPeople.getGh());
        if(StringUtils.isNotEmpty(sysPeople.getAvatar())){
            String base64= ImageToBase64Utils.getImgUrlToBase64(sysPeople.getAvatar());
            JSONArray faces=new JSONArray();
            Map<String, Object> face = new HashMap<String, Object>();
            face.put("faceData", base64);
            faces.add(face);
            paramMaps.put("faces", faces );
        }
        String body = JSON.toJSON(paramMaps).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        String request = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        JSONObject jsons= JSONObject.parseObject(request);
        JSONObject jsons1=(JSONObject) jsons.get("data");
        String personId= (String) jsons1.get("personId");
        String faceId= (String) jsons1.get("faceId");
        sysPeople.setGuid(personId);
        sysPeople.setFaceGuid(faceId);
        sysPeople.setDown(1L);
        if(StringUtils.isNotEmpty(sysPeople.getDoorNo())){
            sysPeople=addCardBindings(sysPeople);
        }
        return sysPeople;
    }

    private SysPeople hkUpdatePeople(SysPeople sysPeople) {
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(url); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecret);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/resource/v1/person/single/update";
        Map<String, Object> paramMaps = new HashMap<String, Object>();// post请求Form表单参数
        paramMaps.put("personId", sysPeople.getGuid());
        paramMaps.put("personName", sysPeople.getName());
        paramMaps.put("gender", sysPeople.getSex());
        paramMaps.put("orgIndexCode", sysPeople.getBranchId());
        paramMaps.put("phoneNo", sysPeople.getPhone());
        paramMaps.put("certificateNo", sysPeople.getIdcard());
        paramMaps.put("jobNo", sysPeople.getGh());
        if(StringUtils.isNotEmpty(sysPeople.getAvatar())){
            SysPeople people=sysPeopleMapper.selectSysPeopleById(sysPeople.getId());
            if(!sysPeople.getAvatar().equals(people.getAvatar())){
                //添加人脸
                sysPeople=hkAddFace(sysPeople);
            }

        }
        String body = JSON.toJSON(paramMaps).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        String request = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        JSONObject jsons= JSONObject.parseObject(request);
        String jsons1= (String) jsons.get("msg");
        if("success".equals(jsons1)){
            sysPeople.setDown(1L);
        }
        if(StringUtils.isNotEmpty(sysPeople.getDoorNo())){
            //查询是否更换卡号
            SysPeople peopes= sysPeopleMapper.selectSysPeopleById(sysPeople.getId());
            if(StringUtils.isNotEmpty(peopes.getDoorNo())) {
                if(peopes.getDoorNo()!=sysPeople.getDoorNo()){
                    addCardDeletion(peopes);
                }
            }
            sysPeople=addCardBindings(sysPeople);
        }
        return sysPeople;
    }

    private SysPeople addCardBindings(SysPeople sysPeople) {
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(url); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecret);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/cis/v1/card/bindings";
        Map<String, Object> paramMaps = new HashMap<String, Object>();// post请求Form表单参数
        JSONArray list=new JSONArray();
        paramMaps.put("personId", sysPeople.getGuid());
        paramMaps.put("startDate", "2024-10-10");
        paramMaps.put("endDate", "2029-10-10");
        Map<String, Object> obj = new HashMap<String, Object>();
        obj.put("cardNo",sysPeople.getDoorNo());
        obj.put("personId",sysPeople.getGuid());
        obj.put("orgIndexCode",sysPeople.getBranchId());
        obj.put("cardType","1");
        list.add(obj);
        paramMaps.put("cardList",list);
        String body = JSON.toJSON(paramMaps).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        String request = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        JSONObject jsons= JSONObject.parseObject(request);
        String jsons1= (String) jsons.get("msg");
        if("success".equals(jsons1)){
            sysPeople.setDown(2L);
        }
        return sysPeople;
    }

    private SysPeople addCardDeletion(SysPeople sysPeople) {
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(url); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecret);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/cis/v1/card/deletion";
        Map<String, Object> paramMaps = new HashMap<String, Object>();// post请求Form表单参数
        JSONArray list=new JSONArray();
        paramMaps.put("personId", sysPeople.getGuid());
        paramMaps.put("cardNumber", sysPeople.getDoorNo());
        String body = JSON.toJSON(paramMaps).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        String request = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        JSONObject jsons= JSONObject.parseObject(request);
        String jsons1= (String) jsons.get("msg");
        if("success".equals(jsons1)){
            sysPeople.setDown(2L);
        }
        return sysPeople;
    }

    private SysPeople hkAddFace(SysPeople sysPeople) {
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(url); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecret);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/resource/v1/face/single/add";
        Map<String, Object> paramMaps = new HashMap<String, Object>();// post请求Form表单参数
        paramMaps.put("personId", sysPeople.getGuid());
        String base64= ImageToBase64Utils.getImgUrlToBase64(sysPeople.getAvatar());
        paramMaps.put("faceData", base64);
        String body = JSON.toJSON(paramMaps).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        String request = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        JSONObject jsons= JSONObject.parseObject(request);
        JSONObject jsons1=(JSONObject) jsons.get("data");
        if(jsons1!=null){
            String personId= (String) jsons1.get("personId");
            String faceId= (String) jsons1.get("faceId");
            sysPeople.setGuid(personId);
            sysPeople.setFaceGuid(faceId);
        }
        return sysPeople;
    }

    private SysPeople hkDetelePeople(SysPeople sysPeople) {
        ArtemisConfig config = new ArtemisConfig();
        config.setHost(url); // 代理API网关nginx服务器ip端口
        config.setAppKey(appKey);  // 秘钥appkey
        config.setAppSecret(appSecret);// 秘钥appSecret
        final String getCamsApi = ARTEMIS_PATH + "/api/resource/v1/person/batch/delete";
        Map<String, Object> paramMaps = new HashMap<String, Object>();// post请求Form表单参数
        JSONArray personIds=new JSONArray();
        personIds.add(sysPeople.getGuid());
        paramMaps.put("personIds",personIds);
        String body = JSON.toJSON(paramMaps).toString();
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);
            }
        };
        String request = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        JSONObject jsons= JSONObject.parseObject(request);
        return sysPeople;
    }

    /**
     * 新增用户岗位信息
     *
     * @param people 用户对象
     */
    public void insertPeoplePost(SysPeople people)
    {
        Long[] posts = people.getPostIds();
        if (StringUtils.isNotEmpty(posts))
        {
            // 新增用户与岗位管理
            List<SysPeoplePost> list = new ArrayList<SysPeoplePost>();
            for (Long postId : posts)
            {
                SysPeoplePost up = new SysPeoplePost();
                up.setPeopleId(people.getId());
                up.setPostId(postId);
                list.add(up);
            }
            sysPeoplePostMapper.batchPeoplePost(list);
        }
    }

    /**
     * 修改人员管理
     *
     * @param sysPeople 人员管理
     * @return 结果
     */
    @Override
    public int updateSysPeople(SysPeople sysPeople)
    {
        sysPeople.setUpdateTime(DateUtils.getNowDate());
       /* if (!"10".equals(sysPeople.getWxFlag())) {
            syncRuleService.addPeople(sysPeople,"update");
        }*/
        // 删除用户与岗位关联
        sysPeoplePostMapper.deletePeoplePostByPeopleId(sysPeople.getId());
        //insertPeoplePost(sysPeople);
        sysPeople=hkUpdatePeople(sysPeople);
        sysPeopleEquipmentMapper.deleteSysPeopleEquipmentByPeopleId(sysPeople.getId());
        if(StringUtils.isNotEmpty(sysPeople.getQwid())){
            SysUser user=userService.selectUserByUserName(sysPeople.getGh());
            user.setOpenid(sysPeople.getQwid());
            userService.updateOpenId(user);
        }
        return sysPeopleMapper.updateSysPeople(sysPeople);
    }

    /**
     * 批量删除人员管理
     *
     * @param ids 需要删除的人员管理主键
     * @return 结果
     */
    @Override
    public int deleteSysPeopleByIds(Long[] ids)
    {
        for(Long id:ids){
            SysPeople people=sysPeopleMapper.selectSysPeopleById(id);
            if(StringUtils.isNotEmpty(people.getGuid())){
                hkDetelePeople(people);
            }
        }
        return sysPeopleMapper.deleteSysPeopleByIds(ids);
    }

    /**
     * 删除人员管理信息
     *
     * @param id 人员管理主键
     * @return 结果
     */
    @Override
    public int deleteSysPeopleById(Long id)
    {
        SysPeople people=sysPeopleMapper.selectSysPeopleById(id);
        if(StringUtils.isNotEmpty(people.getGuid())){
            hkDetelePeople(people);
        }
        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 SysPeople 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) {
        return sysPeopleMapper.queryPeopleName(phone);
    }




    /**
     * 导入用户数据
     *
     * @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();
    }



    /**
     * 保存到考勤组人员
     *
     * @param people 用户数据列表
     * @return 结果
     */
    @Override
    public void insetKqGroupUser(SysPeople people) {
        KqGroupUser kqGroupUser=new KqGroupUser();
        kqGroupUser.setUserId(people.getId());
        List<KqGroupUser> userList=kqGroupUserMapper.selectKqGroupUserList(kqGroupUser);
        if(userList.size()==0){//不在考勤人员中
            KqGroup kqGroup=new KqGroup();
            kqGroup.setDeptId(people.getBranchId());
            List<KqGroup>  groups= kqGroupMapper.selectKqGroupList(kqGroup);
            if(groups.size()>0){
                kqGroupUser.setGroupId(groups.get(0).getGroupId());
                kqGroupUserMapper.insertKqGroupUser(kqGroupUser);
            }else{
                KqGroup kqGroups=new KqGroup();
                kqGroups.setIsMain("1");
                List<KqGroup>  groups1= kqGroupMapper.selectKqGroupList(kqGroups);
                if(groups1.size()>0){
                    kqGroupUser.setGroupId(groups1.get(0).getGroupId());
                    kqGroupUserMapper.insertKqGroupUser(kqGroupUser);
                }
            }
        }

    }

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

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



    @Override
    public StringBuffer importPicture(MultipartFile picture, Boolean isUpdateSupport) throws Exception {
        String qrCodeZIPName = UUID.randomUUID() + ".zip";
        StringBuffer sb = new StringBuffer();
        File file= FileUtils.byte2File(picture.getBytes(), excelShortPath,qrCodeZIPName);
        String s1=file.getName();
        String prefix = qrCodeZIPName.substring(qrCodeZIPName.lastIndexOf("."));
        int num = prefix.length();//得到后缀名长度
        String s2 = s1.substring(0, s1.length() - num);//得到文件名。去掉了后缀
        List<SysPeople> getOriginalPic = ZipUtil.getOriginalPic1(excelShortPath + s1, excelShortPath + s2);
        List<SysPeople> peopleDtoList =new ArrayList<>();
        List<String> errorList = new ArrayList<String>();
        List<String> existCode = new ArrayList<String>();
        for (int j = 0; j < getOriginalPic.size(); j++) {
            String fileName = getOriginalPic.get(j).getAvatar();
            String fix = fileName.substring(fileName.lastIndexOf("."));
            int number = fix.length();//得到后缀名长度
            String fileOtherName = fileName.substring(0, fileName.length() - number);//得到文件名。去掉了后缀
            //根据文件名查找学工信息
            SysPeople student=sysPeopleMapper.selectSysPeopleByGh(fileOtherName);
            if (student!=null) {
                //这里是存进数据库的url
                MultipartFile files= PictureUtils.getMultipartFile(getOriginalPic.get(j).getFile());
                if(isUpdateSupport){//是否核验人脸算法 是的话走人脸算法核验，有限流功能
                    R<SysFile> fileNames =remoteFileService.uploadMinio(files,student.getGh());
                    if(fileNames.getData()!=null){
                        if(StringUtils.isEmpty(fileNames.getData().getUrl())){
                            errorList.add(fileOtherName);
                        }else{
                            student.setAvatar(fileNames.getData().getUrl());
                            peopleDtoList.add(student);
                        }
                    }else{
                        errorList.add(fileOtherName);
                    }
                }else{
                    R<SysFile> fileNames =remoteFileService.uploadMinios(files,student.getGh());
                    if(fileNames.getData()!=null){
                        if(StringUtils.isEmpty(fileNames.getData().getUrl())){
                            errorList.add(fileOtherName);
                        }else{
                            String url=fileNames.getData().getUrl();
                            //url = url.substring(0,url.indexOf('?'));
                            student.setAvatar(url);
                            peopleDtoList.add(student);
                        }
                    }else{
                        errorList.add(fileOtherName);
                    }
                }
            }else{
                existCode.add(fileOtherName);
            }
        }

        if (existCode != null && existCode.size() > 0) {
            sb.append("工号为 " + existCode + " 的工号不存在数据库。");
        }
        if (errorList != null && errorList.size() > 0) {
            sb.append("工号为 " + errorList + " 的图片不存在或没有人脸。");
        }
        List<String> errorString = batchAdd(peopleDtoList);
        if (errorString.size() == 0) {
            return sb;
        } else {
            sb.append("失败工号列表：" + errorString);
        }
        return sb;
    }

    private List<String> batchAdd(List<SysPeople> peopleDtoList) {
        List<String> errorString = new LinkedList<String>();
        if (peopleDtoList.size() > 0 && peopleDtoList != null) {
            for (SysPeople faceStudent : peopleDtoList) {
                this.updateSysPeople(faceStudent);
            }
        }
        return errorString;
    }
}
