package com.ruoyi.system.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Comparator;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.TDeviceList;
import com.ruoyi.system.domain.TServiceManage;
import com.ruoyi.system.domain.dto.AddUserDto;
import com.ruoyi.system.domain.dto.TUserProfileDto;
import com.ruoyi.system.domain.dto.UserAgeDto;
import com.ruoyi.system.mapper.TDeviceListMapper;
import com.ruoyi.system.mapper.TEmergentPeopleMapper;
import com.ruoyi.system.service.ISysDictTypeService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.system.domain.TEmergentPeople;
import com.ruoyi.system.mapper.TUserProfileMapper;
import com.ruoyi.system.domain.TUserProfile;
import com.ruoyi.system.service.ITUserProfileService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 用户档案Service业务层处理
 *
 * @author zhengjie
 * @date 2023-08-25
 */
@Service
public class TUserProfileServiceImpl implements ITUserProfileService {
    @Autowired
    private TUserProfileMapper tUserProfileMapper;
    @Autowired
    private TEmergentPeopleMapper tEmergentPeopleMapper;
    @Autowired
    private TDeviceListMapper tDeviceListMapper;
    @Autowired
    private ISysDictTypeService dictTypeService;

    /**
     * 查询用户档案
     *
     * @param id 用户档案主键
     * @return 用户档案
     */
    @Override
    public TUserProfile selectTUserProfileById(Integer id) {
        return tUserProfileMapper.selectTUserProfileById(id);
    }

    /**
     * 查询用户档案列表
     *
     * @param tUserProfile 用户档案
     * @return 用户档案
     */
    @Override
    public List<TUserProfile> selectTUserProfileList(TUserProfile tUserProfile) {
        List<TUserProfile> tUserProfileList = tUserProfileMapper.selectTUserProfileList(tUserProfile);
        for (TUserProfile list : tUserProfileList) {
            list.setTEmergentPeopleList(tEmergentPeopleMapper.selectTEmergentPeopleByProfileId(list.getId()));
        }
        return tUserProfileList;
    }

    /**
     * 查询用户档案列表
     *
     * @param tUserProfileDto 用户档案
     * @return 用户档案集合
     */
    @Override
    public List<TUserProfileDto> selectTUserProfileListByDevice(TUserProfileDto tUserProfileDto) {
        return tUserProfileMapper.selectTUserProfileListByDevice(tUserProfileDto);
    }

    /**
     * 新增用户档案
     *
     * @param tUserProfile 用户档案
     * @return 结果
     */
    @Transactional
    @Override
    public int insertTUserProfile(TUserProfile tUserProfile) {
        if (tUserProfile == null) {
            throw new ServiceException("新增用户信息数据不能为空！");
        }
        //新增用户创建时间
        tUserProfile.setCreateTime(DateUtils.getNowDate());
        //判断提交数据格式是否正确
        if (tUserProfile.getSfzid() == null || tUserProfile.getSfzid().isEmpty()) {
            throw new ServiceException("新增用户信息数据身份证号格式异常！");
        }
        //根据身份证号查询数据库中的用户信息
        TUserProfile user = tUserProfileMapper.selectTUserProfileBySfzId(tUserProfile.getSfzid());
        if (user != null) {
            //如果表中有该用户则提示
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("新增用户信息已存在");
            //如果有用户名，则提示
            if (!StringUtils.isEmpty(tUserProfile.getName())) {
                stringBuilder.append(", 用户名：" + tUserProfile.getName());
            }
            //如果有身份证号，则提示
            if (!StringUtils.isEmpty(tUserProfile.getSfzid())) {
                stringBuilder.append(", 身份证号：" + tUserProfile.getSfzid());
            }
            stringBuilder.append("!");
            throw new ServiceException(stringBuilder.toString());
        }
        //TODO 关照之前逻辑
        //特长
        List<String> specialityList = new ArrayList<>();
        if (tUserProfile.getSpeciality() != null && !tUserProfile.getSpeciality().isEmpty()) {
            if (!tUserProfile.getSpeciality().startsWith("[") && !tUserProfile.getSpeciality().endsWith("]")) {
                List<SysDictData> sysSpeciality = dictTypeService.selectDictDataByType("sys_speciality");
                for (SysDictData data : sysSpeciality) {
                    if (data.getDictLabel().contains(tUserProfile.getSpeciality())) {
                        specialityList.add(data.getDictValue());
                    }
                }
                tUserProfile.setSpeciality(JSONObject.toJSONString(specialityList));
            }
        } else {
            tUserProfile.setSpeciality(JSONObject.toJSONString(specialityList));
        }
        //爱好
        List<String> hobbyList = new ArrayList<>();
        if (tUserProfile.getHobby() != null && !tUserProfile.getHobby().isEmpty()) {
            if (!tUserProfile.getHobby().startsWith("[") && !tUserProfile.getHobby().endsWith("]")) {
                List<SysDictData> sysHobby = dictTypeService.selectDictDataByType("sys_hobby");
                for (SysDictData data : sysHobby) {
                    if (data.getDictLabel().contains(tUserProfile.getHobby())) {
                        hobbyList.add(data.getDictValue());
                    }
                }
                tUserProfile.setHobby(JSONObject.toJSONString(hobbyList));
            }
        } else {
            tUserProfile.setHobby(JSONObject.toJSONString(hobbyList));
        }
        //慢性疾病
        List<String> slowIllnessList = new ArrayList<>();
        if (tUserProfile.getSlowIllness() != null && !tUserProfile.getSlowIllness().isEmpty()) {
            if (!tUserProfile.getSlowIllness().startsWith("[") && !tUserProfile.getSlowIllness().endsWith("]")) {
                List<SysDictData> sysSlowIllness = dictTypeService.selectDictDataByType("sys_slow_illness");
                for (SysDictData data : sysSlowIllness) {
                    if (data.getDictLabel().contains(tUserProfile.getSlowIllness())) {
                        slowIllnessList.add(data.getDictValue());
                    }
                }
                tUserProfile.setSlowIllness(JSONObject.toJSONString(slowIllnessList));
            }
        } else {
            tUserProfile.setSlowIllness(JSONObject.toJSONString(slowIllnessList));
        }
        int rows = tUserProfileMapper.insertTUserProfile(tUserProfile);
        insertTEmergentPeople(tUserProfile);
        return rows;
    }

    /**
     * 修改用户档案
     *
     * @param tUserProfile 用户档案
     * @return 结果
     */
    @Transactional
    @Override
    public int updateTUserProfile(TUserProfile tUserProfile) {
        if (tUserProfile == null) {
            throw new ServiceException("修改用户信息数据不能为空！");
        }
        //修改用户信息更新时间
        tUserProfile.setUpdateTime(DateUtils.getNowDate());
        //判断提交数据格式是否正确
        if (tUserProfile.getSfzid() == null || tUserProfile.getSfzid().isEmpty()) {
            throw new ServiceException("修改用户信息数据身份证号格式异常！");
        }
        //根据身份证号查询数据库中的用户信息
        List<TUserProfile> userList = tUserProfileMapper.selectTUserProfileBySfzIdV2(tUserProfile.getSfzid());
        if (userList != null && !userList.isEmpty()) {
            for (TUserProfile profile : userList) {
                if (profile.getId() != tUserProfile.getId()) {
                    //如果表中有该用户则提示
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append("修改用户信息异常");
                    //如果有用户名，则提示
                    if (!StringUtils.isEmpty(tUserProfile.getName())) {
                        stringBuilder.append(", 用户名：" + tUserProfile.getName());
                    }
                    //如果有身份证号，则提示
                    if (!StringUtils.isEmpty(tUserProfile.getSfzid())) {
                        stringBuilder.append(", 身份证号：" + tUserProfile.getSfzid());
                    }
                    stringBuilder.append("!");
                    throw new ServiceException(stringBuilder.toString());
                }
            }
        }
        tUserProfileMapper.deleteTEmergentPeopleByProfileId(tUserProfile.getId());
        insertTEmergentPeople(tUserProfile);
        int rows = tUserProfileMapper.updateTUserProfile(tUserProfile);
        return rows;
    }

    /**
     * 批量删除用户档案
     *
     * @param ids 需要删除的用户档案主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteTUserProfileByIds(Integer[] ids) {
        //判断是否为空
        if (ids == null || ids.length == 0) {
            throw new ServiceException("删除的用户主键禁止为空！");
        }
        //
        int count = 0;
        for (Integer userId : ids) {
            List<TDeviceList> tDeviceLists = tDeviceListMapper.selectTDeviceListByUserId(userId);
            //判断用户是否有设备
            if (tDeviceLists != null && !tDeviceLists.isEmpty()) {
                //如果有设备，则提示删除用户失败
                throw new ServiceException("该用户有绑定设备，禁止删除！");
            }
            tUserProfileMapper.deleteTEmergentPeopleByProfileId(userId);
            count = count + tUserProfileMapper.deleteTUserProfileByIds(ids);
        }
        return count;
    }

    /**
     * 删除用户档案信息
     *
     * @param id 用户档案主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteTUserProfileById(Integer id) {
        tUserProfileMapper.deleteTEmergentPeopleByProfileId(id);
        return tUserProfileMapper.deleteTUserProfileById(id);
    }

    @Override
    public String importTUserProfile(List<TUserProfile> tUserProfileList) {

        if (StringUtils.isNull(tUserProfileList) || tUserProfileList.size() == 0) {
            throw new ServiceException("导入用户档案信息数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (TUserProfile tUserProfile : tUserProfileList) {
            try {
                // 验证是否存在这个人
                TUserProfile u = tUserProfileMapper.selectTUserProfileBySfzId(tUserProfile.getSfzid());
                if (!StringUtils.isNull(u)) {
                    this.insertTUserProfile(tUserProfile);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "用户档案信息" + " 导入成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "用户档案信息" + " 信息不完整");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "用户档案信息" + " 导入失败：";
                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();
    }

    @Transactional
    @Override
    public String importTUserProfileV2(List<TUserProfile> tUserProfileList) {
        if (tUserProfileList == null || tUserProfileList.isEmpty()) {
            throw new ServiceException("导入用户档案信息数据不能为空！");
        }
        //批量导入用户数据
        for (TUserProfile userProfile : tUserProfileList) {
            //判断提交数据格式是否正确
            if (userProfile.getSfzid() == null || userProfile.getSfzid().isEmpty()) {
                throw new ServiceException("导入用户档案信息身份证号格式异常！");
            }
            //根据身份证号查询数据库中的用户信息
            TUserProfile user = tUserProfileMapper.selectTUserProfileBySfzId(userProfile.getSfzid());
            if (user != null) {
                //如果表中有该用户则提示
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("导入用户档案信息已存在");
                //如果有用户名，则提示
                if (!StringUtils.isEmpty(userProfile.getName())) {
                    stringBuilder.append(", 用户名：" + userProfile.getName());
                }
                //如果有身份证号，则提示
                if (!StringUtils.isEmpty(userProfile.getSfzid())) {
                    stringBuilder.append(", 身份证号：" + userProfile.getSfzid());
                }
                stringBuilder.append("!");
                throw new ServiceException(stringBuilder.toString());
            }
            insertTUserProfile(userProfile);
        }
        StringBuilder successMsg = new StringBuilder();
        successMsg.append("恭喜您，数据已全部导入成功！共 " + tUserProfileList.size() + " 条，数据如下：");
        return successMsg.toString();
    }


    @Override
    public List<UserAgeDto> selectuserAgeDto() {
        return tUserProfileMapper.selectuserAgeDto();
    }

    @Override
    public Integer selectuserAgeCount() {
        return tUserProfileMapper.selectuserAgeCount();
    }

    @Override
    public List<AddUserDto> selectAddUser() {
        return tUserProfileMapper.selectAddUser();
    }

    /**
     * 新增紧急联系人信息
     *
     * @param tUserProfile 用户档案对象
     */
    public void insertTEmergentPeople(TUserProfile tUserProfile) {
        List<TEmergentPeople> tEmergentPeopleList = tUserProfile.getTEmergentPeopleList();
        if (StringUtils.isNotNull(tEmergentPeopleList)) {
            List<TEmergentPeople> list = tEmergentPeopleList.stream()
                    .map(mapper -> {
                        mapper.setProfileId(tUserProfile.getId());
                        return mapper;
                    }).collect(Collectors.toList());
            if (list.size() > 0) {
                tUserProfileMapper.batchTEmergentPeople(list);
            }
        }
    }
}
