package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpClientUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.domain.OdsQssHsjcxx;
import com.ruoyi.system.domain.UserInfo;
import com.ruoyi.system.domain.UserNucleicTime;
import com.ruoyi.system.mapper.SysDictTypeMapper;
import com.ruoyi.system.mapper.UserInfoMapper;
import com.ruoyi.system.mapper.UserNucleicTimeMapper;
import com.ruoyi.system.service.IUserInfoService;
import com.ruoyi.system.service.OdsQssHsjcxxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 导入人员信息Service业务层处理
 *
 * @author ruoyi
 * @date 2022-08-11
 */
@Service
public class UserInfoServiceImpl implements IUserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private OdsQssHsjcxxService qdsQssHsjcxxService;
    @Autowired
    private UserNucleicTimeMapper userNucleicTimeMapper;

    /**
     * 查询导入人员信息
     *
     * @param id 导入人员信息主键
     * @return 导入人员信息
     */
    @Override
    public UserInfo selectUserInfoById(Long id) {
        return userInfoMapper.selectUserInfoById(id);
    }

    /**
     * 查询导入人员信息列表
     *
     * @param userInfo 导入人员信息
     * @return 导入人员信息
     */
    @Override
    public List<UserInfo> selectUserInfoList(UserInfo userInfo) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        userInfo.setDeptId(String.valueOf(user.getDeptId()));
        return userInfoMapper.selectUserInfoList(userInfo);
    }


    /**
     * 新增导入人员信息
     *
     * @param userInfo 导入人员信息
     * @return 结果
     */
    @Override
    public int insertUserInfo(UserInfo userInfo) {
        userInfo.setCreateTime(DateUtils.getNowDate());
        return userInfoMapper.insertUserInfo(userInfo);
    }

    /**
     * 修改导入人员信息
     *
     * @param userInfo 导入人员信息
     * @return 结果
     */
    @Override
    public int updateUserInfo(UserInfo userInfo) {
        userInfo.setUpdateTime(DateUtils.getNowDate());
        return userInfoMapper.updateUserInfo(userInfo);
    }

    /**
     * 批量删除导入人员信息
     *
     * @param ids 需要删除的导入人员信息主键
     * @return 结果
     */
    @Override
    public int deleteUserInfoByIds(Long[] ids) {
        return userInfoMapper.deleteUserInfoByIds(ids);
    }

    /**
     * 删除导入人员信息信息
     *
     * @param id 导入人员信息主键
     * @return 结果
     */
    @Override
    public int deleteUserInfoById(Long id) {
        return userInfoMapper.deleteUserInfoById(id);
    }

    /**
     * 核酸比对人员导入
     *
     * @param jobStyle        职业类别
     * @param focusCrowdStyle 重点人群分类
     * @param detectionNumber 检测频次（次数）
     * @param detectionScope  检测频次（时间范围）
     * @param startTime       比对开始时间
     * @param endTime         比对结束时间
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importUser(List<UserInfo> userList, String jobStyle, String focusCrowdStyle, String detectionNumber,
                             String detectionScope, String startTime, String endTime) throws Exception {

        System.out.println("接口开始========");
        long start1 = System.currentTimeMillis();

        StringBuilder sb = new StringBuilder();
        for (UserInfo userInfo : userList) {
            if(userInfo.getIdCard().length()!=18){
                sb.append(userInfo.getName()).append(",");
            }
        }

        if(StringUtils.isNotEmpty(sb.toString())){
            return "操作失败,以下人员身份证格式错我【"+sb.toString()+"】";
        }

        //todo 获取当前上传人员部门id
        SysUser user = SecurityUtils.getLoginUser().getUser();
        String deptId = String.valueOf(user.getDeptId());

        //获取上传名单的所有身份证号
        List<String> idCardList = userList.stream().map(UserInfo::getIdCard).collect(Collectors.toList());

        //从第三方数据库查询人员核酸计录
        List<OdsQssHsjcxx> OdsQssHsjcxxList = qdsQssHsjcxxService.thirdNucleicAcid(startTime, endTime, idCardList);


        List<UserNucleicTime> UserNucleicTimeList = new ArrayList<>();

        int index = 0;
        int res1 = 0;
        int res2 = 0;
        String date = null;
        for (UserInfo userInfo : userList) {

            userInfo.setDeptId(deptId);
            //采集地点
            StringBuilder collectPlace = new StringBuilder();
            //核酸采集时间
            StringBuilder nucleicCollectTime = new StringBuilder();
            //核酸结果时间
            StringBuilder nucleicResultsTime = new StringBuilder();

            userInfo.setJobStyle(jobStyle);
            userInfo.setFocusCrowdStyle(focusCrowdStyle);
            userInfo.setDetectionFrequency(detectionNumber + "/" + detectionScope);
            userInfo.setDetectionNumber(detectionNumber);
            userInfo.setDetectionScope(detectionScope);
            userInfo.setStartTime(startTime);
            userInfo.setEndTime(endTime);
            userInfo.setCreateBy(user.getUserName());
            userInfo.setUpdateBy(user.getUserName());
            //判断结果是否合格,默认合格
            Boolean bl = true;
            //创建一个死循环
            for (int i = 2; i > 1; i++) {
                //计算开始时间加上检测频次（时间范围）后的时间
                date = DateUtils.getAddDate(startTime, Integer.parseInt(detectionScope));
                int res = endTime.compareTo(date);//res>0(endTime>date),res=0(endTime=date),res<0(endTime<date)
                if (res > 0) {
                    index = 0;
                    for (OdsQssHsjcxx odsQssHsjcxx : OdsQssHsjcxxList) {
                        //判断 核酸采集时间是不是在 startTime和date之间
                        res1 = odsQssHsjcxx.getCjsj().compareTo(startTime);
                        res2 = date.compareTo(odsQssHsjcxx.getCjsj());
                        if (userInfo.getIdCard().equals(odsQssHsjcxx.getSfzhm()) && res1 >= 0 && res2 >= 0) {

                            if (StringUtils.isNotEmpty(collectPlace.toString())) {
                                collectPlace.append("/");
                            }
                            collectPlace.append(odsQssHsjcxx.getJcdd());

                            if (StringUtils.isNotEmpty(nucleicCollectTime.toString())) {
                                nucleicCollectTime.append("/");
                            }
                            nucleicCollectTime.append(odsQssHsjcxx.getCjsj());

                            if (StringUtils.isNotEmpty(nucleicResultsTime.toString())) {
                                nucleicResultsTime.append("/");
                            }
                            nucleicResultsTime.append(odsQssHsjcxx.getJgcjss());

                            index++;
                            //当index与detectionNumber相等时，满足条件，跳出当前循环
                            if (index == Integer.parseInt(detectionNumber)) {
                                startTime = date;
                                break;
                            }
                        }
                    }
                    if (index < Integer.parseInt(detectionNumber)) {
                        bl = false;
                    }
                } else {
                    index = 0;
                    for (OdsQssHsjcxx odsQssHsjcxx : OdsQssHsjcxxList) {
                        //判断 核酸采集时间是不是在 startTime和date之间
                        res1 = odsQssHsjcxx.getCjsj().compareTo(startTime);
                        res2 = date.compareTo(odsQssHsjcxx.getCjsj());
                        if (userInfo.getIdCard().equals(odsQssHsjcxx.getSfzhm()) && res1 >= 0 && res2 >= 0) {

                            if (StringUtils.isNotEmpty(collectPlace.toString())) {
                                collectPlace.append("/");
                            }
                            collectPlace.append(odsQssHsjcxx.getJcdd());

                            if (StringUtils.isNotEmpty(nucleicCollectTime.toString())) {
                                nucleicCollectTime.append("/");
                            }
                            nucleicCollectTime.append(odsQssHsjcxx.getCjsj());

                            if (StringUtils.isNotEmpty(nucleicResultsTime.toString())) {
                                nucleicResultsTime.append("/");
                            }
                            nucleicResultsTime.append(odsQssHsjcxx.getJgcjss());

                            index++;
                            //当index与detectionNumber相等时，满足条件，跳出当前循环
                            if (index == Integer.parseInt(detectionNumber)) {
                                //跳出死循环
                                i = -1;
                                break;
                            }
                        }
                    }
                    if (index < Integer.parseInt(detectionNumber)) {
                        bl = false;
                        //跳出死循环
                        i = -1;
                    }
                }
            }
            userInfo.setCollectPlace(collectPlace.toString());
            userInfo.setNucleicCollectTime(nucleicCollectTime.toString());
            userInfo.setNucleicResultsTime(nucleicResultsTime.toString());
            if (bl) {
                userInfo.setDetectionResult("正常");
            } else {
                userInfo.setDetectionResult("异常");
            }

        }


        for (OdsQssHsjcxx odsQssHsjcxx : OdsQssHsjcxxList) {
            for (UserInfo userInfo : userList) {
                if (userInfo.getIdCard().equals(odsQssHsjcxx.getSfzhm())) {
                    UserNucleicTime userNucleicTime = new UserNucleicTime();
                    userNucleicTime.setInfoId(userInfo.getId());
                    userNucleicTime.setIdCard(odsQssHsjcxx.getSfzhm());
                    userNucleicTime.setCollectPlace(odsQssHsjcxx.getJcdd());
                    userNucleicTime.setNucleicCollectTime(odsQssHsjcxx.getCjsj());
                    userNucleicTime.setNucleicResultsTime(odsQssHsjcxx.getJgcjss());
                    userNucleicTime.setJobStyle(jobStyle);
                    userNucleicTime.setFocusCrowdStyle(focusCrowdStyle);
                    userNucleicTime.setName(userInfo.getName());
                    userNucleicTime.setPhoneNum(userInfo.getPhoneNum());
                    userNucleicTime.setDeptId(deptId);
                    UserNucleicTimeList.add(userNucleicTime);
                }
            }
        }

        //批量保存
        userInfoMapper.insertUserInfoList(userList);
        userNucleicTimeMapper.insertUserNucleicTimeList(UserNucleicTimeList);

        long end1 = System.currentTimeMillis();
        System.out.println("---------------接口耗时" + (end1 - start1) + "---------------");

        return "操作成功";
    }


}
