package com.willalp.yiqing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.willalp.common.exception.base.BaseException;
import com.willalp.common.utils.StringUtils;
import com.willalp.yiqing.domain.HsPositiveContiguityUser;
import com.willalp.yiqing.domain.HsYiqingRegister;
import com.willalp.yiqing.domain.vo.RegisterVo;
import com.willalp.yiqing.domain.vo.RegisterVo2;
import com.willalp.yiqing.mapper.HsPositiveContiguityUserMapper;
import com.willalp.yiqing.mapper.HsYiqingRegisterMapper;
import com.willalp.yiqing.service.IHsYiqingRegisterService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 疫情登记信息Service业务层处理
 *
 * @author willalp
 * @date 2022-05-16
 */
@Service
public class HsYiqingRegisterServiceImpl extends ServiceImpl<HsYiqingRegisterMapper, HsYiqingRegister> implements IHsYiqingRegisterService {
    @Resource
    private HsYiqingRegisterMapper registerMapper;

    @Resource
    private HsPositiveContiguityUserMapper pcuMapper;

    /**
     * 查询疫情登记信息列表
     *
     * @param hsYiqingRegister 疫情登记信息
     * @return 疫情登记信息
     */
    @Override
    public List<RegisterVo2> selectHsYiqingRegisterList(HsYiqingRegister hsYiqingRegister) {
        return registerMapper.selectHsYiqingRegisterList(hsYiqingRegister);
    }

    @Override
    public String importData(List<RegisterVo2> list) {
        if (0 != list.size()) {
            List<HsPositiveContiguityUser> usersDb = pcuMapper.selectList(null);
            List<HsYiqingRegister> saveList = new ArrayList<>();
            for (RegisterVo2 vo : list) {
                int num = 0;
                HsYiqingRegister register = new HsYiqingRegister();
                for (HsPositiveContiguityUser user : usersDb) {
                    if (StringUtils.equals(vo.getUserName(), user.getUserName()) &&
                            StringUtils.equals(vo.getAttestNo(), user.getAttestNo())) {
                        register.setUserDataId(user.getDataId());
                        num++;
                    }
                }
                if (0 < num) {
                    BeanUtil.copyProperties(vo, register);
                    saveList.add(register);
                }
            }
            if (!this.saveOrUpdateBatch(saveList)) {
                throw new BaseException("批量导入失败");
            }
            if (0 != saveList.size()) {
                return "导入成功，共导入" + saveList.size() + "条记录";
            }
            return "无有效数据";
        }
        return "无有效数据";
    }
}
