package com.willalp.yiqing.service.impl;

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.HsYiqingAddr;
import com.willalp.yiqing.mapper.HsYiqingAddrMapper;
import com.willalp.yiqing.service.IHsYiqingAddrService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 疫情地理地址Service业务层处理
 *
 * @author willalp
 * @date 2022-05-15
 */
@Service
public class HsYiqingAddrServiceImpl extends ServiceImpl<HsYiqingAddrMapper, HsYiqingAddr> implements IHsYiqingAddrService {
    @Resource
    private HsYiqingAddrMapper hsYiqingAddrMapper;

    /**
     * 查询疫情地理地址列表
     *
     * @param hsYiqingAddr 疫情地理地址
     * @return 疫情地理地址
     */
    @Override
    public List<HsYiqingAddr> selectHsYiqingAddrList(HsYiqingAddr hsYiqingAddr) {
        return hsYiqingAddrMapper.selectHsYiqingAddrList(hsYiqingAddr);
    }

    @Override
    public String importData(List<HsYiqingAddr> list) {
        if (0 != list.size()) {
            List<HsYiqingAddr> addrsDb = hsYiqingAddrMapper.selectList(null);
            List<HsYiqingAddr> saveAddrs = new ArrayList<>();
            int errorNum = 0;
            try {
                for (HsYiqingAddr addr : list) {
                    int num = 0;
                    for (HsYiqingAddr addrDb : addrsDb) {
                        if (StringUtils.equals(addrDb.getAddrName(), addr.getAddrName()) &&
                                StringUtils.equals(addrDb.getAddrNo(), addr.getAddrNo()) &&
                                StringUtils.equals(addrDb.getHouseNo(), addr.getHouseNo()) &&
                                StringUtils.equals(addrDb.getAddrDetail(), addr.getAddrDetail()) &&
                                StringUtils.equals(addrDb.getBelongName(), addr.getBelongName())) {
                            num++;
                            break;
                        }
                    }
                    if (0 == num) {
                        String addrNo = addr.getAddrNo();
                        if (StringUtils.isBlank(addrNo)) {
                            errorNum++;
                            break;
                        }
                        addr.setAddrTreeId(addrNo);
                        saveAddrs.add(addr);
                    }
                }
            } catch (Exception e) {
                errorNum++;
            }
            if (0 != saveAddrs.size()) {
                if (!this.saveOrUpdateBatch(saveAddrs)) {
                    throw new BaseException("批量导入失败");
                } else {
                    return "共导入 " + saveAddrs.size() + " 条数据，无效数据 " + errorNum + " 条";
                }
            } else {
                return "共导入 " + saveAddrs.size() + " 条数据，无效数据 " + errorNum + " 条";
            }
        }
        return "没有效数据";
    }
}
