package com.ruoyi.logistics.service.impl;

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

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.model.LoginUser;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.logistics.mapper.BizAddressBookMapper;
import com.ruoyi.logistics.domain.BizAddressBook;
import com.ruoyi.logistics.service.IBizAddressBookService;

/**
 * 地址簿管理Service业务层处理
 *
 * @author RuiJing
 * @date 2026-01-29
 */
@Service
public class BizAddressBookServiceImpl implements IBizAddressBookService {
    @Autowired
    private BizAddressBookMapper bizAddressBookMapper;

    /**
     * 查询地址簿管理
     *
     * @param addressId 地址簿管理主键
     * @return 地址簿管理
     */
    @Override
    public BizAddressBook selectBizAddressBookByAddressId(Long addressId) {
        return bizAddressBookMapper.selectBizAddressBookByAddressId(addressId);
    }

    /**
     * 查询地址簿管理列表
     *
     * @param bizAddressBook 地址簿管理
     * @return 地址簿管理
     */
    @Override
    public List<BizAddressBook> selectBizAddressBookList(BizAddressBook bizAddressBook) {
        bizAddressBook.setUserId(SecurityUtils.getLoginUser().getUserid());
        return bizAddressBookMapper.selectBizAddressBookList(bizAddressBook);
    }

    /**
     * 新增地址簿管理
     *
     * @param bizAddressBook 地址簿管理
     * @return 结果
     */
    @Override
    public Long insertBizAddressBook(BizAddressBook bizAddressBook) {
        LoginUser loginUser = SecurityUtils.getLoginUser();

        bizAddressBook.setUserId(loginUser.getUserid());
        bizAddressBook.setDeptId(loginUser.getSysUser().getDeptId());
        bizAddressBook.setCreateTime(DateUtils.getNowDate());
        bizAddressBook.setCreateBy(loginUser.getUsername());


        List<BizAddressBook> bizAddressBooks = bizAddressBookMapper.selectBizAddressBookList(bizAddressBook);
        if (CollectionUtils.isNotEmpty(bizAddressBooks)) {
            throw new ServiceException("地址已存在");
        }


        if ("1".equals(bizAddressBook.getDefaultFlag())) {
            bizAddressBookMapper.updateBizAddressBookDefault(loginUser.getUserid());
        }

        int i = bizAddressBookMapper.insertBizAddressBook(bizAddressBook);
        return bizAddressBook.getAddressId();
    }

    /**
     * 修改地址簿管理
     *
     * @param bizAddressBook 地址簿管理
     * @return 结果
     */
    @Override
    public int updateBizAddressBook(BizAddressBook bizAddressBook) {
        LoginUser loginUser = SecurityUtils.getLoginUser();

        bizAddressBook.setCreateTime(DateUtils.getNowDate());
        bizAddressBook.setUpdateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        bizAddressBook.setUpdateTime(DateUtils.getNowDate());

        bizAddressBook.setUserId(loginUser.getUserid());
        List<BizAddressBook> bizAddressBooks = bizAddressBookMapper.selectBizAddressBookList(bizAddressBook);
        if (CollectionUtils.isNotEmpty(bizAddressBooks)) {
            throw new ServiceException("地址已存在");
        }

        if ("1".equals(bizAddressBook.getDefaultFlag())) {
            bizAddressBookMapper.updateBizAddressBookDefault(loginUser.getUserid());
        }

        return bizAddressBookMapper.updateBizAddressBook(bizAddressBook);
    }

    /**
     * 批量删除地址簿管理
     *
     * @param addressIds 需要删除的地址簿管理主键
     * @return 结果
     */
    @Override
    public int deleteBizAddressBookByAddressIds(Long[] addressIds) {
        return bizAddressBookMapper.deleteBizAddressBookByAddressIds(addressIds);
    }

    /**
     * 删除地址簿管理信息
     *
     * @param addressId 地址簿管理主键
     * @return 结果
     */
    @Override
    public int deleteBizAddressBookByAddressId(Long addressId) {
        return bizAddressBookMapper.deleteBizAddressBookByAddressId(addressId);
    }

    @Override
    public BizAddressBook selectDefaultAddressBook() {

        BizAddressBook query = new BizAddressBook();
        query.setUserId(SecurityUtils.getLoginUser().getUserid());
        query.setDefaultFlag("1");
        BizAddressBook bizAddressBook = bizAddressBookMapper.selectDefaultAddressBook(query);
        return bizAddressBook;
    }


    /**
     * 导入地址簿数据
     *
     * @param bookList 地址簿列表
     */
    @Override
    public String importBook(List<BizAddressBook> bookList) {
        if (StringUtils.isNull(bookList) || bookList.isEmpty()) {
            throw new ServiceException("导入地址数据不能为空！");
        }

        // 获取当前登陆人信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userid = loginUser.getUserid();
        Long deptId = loginUser.getSysUser().getDeptId();
        Date nowDate = DateUtils.getNowDate();
        String username = loginUser.getUsername();

        // 对导入的地址进行判断,联系人,联系电话,省市区信息必须存在,是否默认字段允许为空(默认为否),如果不为空只能有一个默认
        bookList.forEach(book -> {
            // 先判断 联系人，联系电话，省市区信息是否为空
            if (StringUtils.isEmpty(book.getContactName())
                    || StringUtils.isEmpty(book.getContactPhone())
                    || StringUtils.isEmpty(book.getProvinceName())
                    || StringUtils.isEmpty(book.getCityName())
                    || StringUtils.isEmpty(book.getCountyName())
                    || StringUtils.isEmpty(book.getDetailedAddress())
            ) {
                throw new ServiceException("导入地址数据存在空值，请检查！");
            }
                        
            // 校验手机号格式
            if (!book.getContactPhone().matches("^1[3-9]\\d{9}$")) {
                throw new ServiceException("导入地址数据存在手机号格式不正确，请检查！");
            }

            // 判断 是否默认字段是否为空,如果不为空只能有一个默认,并根据传值进行发替换
            String defaultFlag = book.getDefaultFlag();
            if (defaultFlag == null || defaultFlag.isEmpty() || Objects.equals(defaultFlag, "否")) {
                book.setDefaultFlag("0");
            }
            if (Objects.equals(defaultFlag, "是")) {
                book.setDefaultFlag("1");
            }

            // 向地址簿中添加登陆人信息
            book.setUserId(userid);
            book.setDeptId(deptId);
            book.setCreateTime(nowDate);
            book.setCreateBy(username);
        });
        // 再次判断,是否存在多个默认
        if (bookList.stream().filter(book -> Objects.equals(book.getDefaultFlag(), "1")).count() > 1) {
            throw new ServiceException("导入地址数据存在多个默认地址,请检查！");
        }
        // 先对传入的数据进行去重
        List<BizAddressBook> distinctBizAddressBookList = bookList.stream().distinct().collect(Collectors.toList());
        // 判断如果存在重复的数据的处理方式(是否更新)
        // 如果更新的话会修改原来数据的创建时间和创建人信息,不会删除重新保存,避免原来绑定的数据丢失
        // 如果是不进行保存
        // 先获取传入的数据的 联系人集合,联系电话集合,省市区集合,详细地址集合,并和作为条件查询是否存在符合条件的数据
        Set<String> contactNameSet = distinctBizAddressBookList.stream().map(BizAddressBook::getContactName).collect(Collectors.toSet());
        Set<String> contactPhoneSet = distinctBizAddressBookList.stream().map(BizAddressBook::getContactPhone).collect(Collectors.toSet());
        Set<String> provinceNameSet = distinctBizAddressBookList.stream().map(BizAddressBook::getProvinceName).collect(Collectors.toSet());
        Set<String> cityNametoSet = distinctBizAddressBookList.stream().map(BizAddressBook::getCityName).collect(Collectors.toSet());
        Set<String> countyNameSet = distinctBizAddressBookList.stream().map(BizAddressBook::getCountyName).collect(Collectors.toSet());
        Set<String> addressSet = distinctBizAddressBookList.stream().map(BizAddressBook::getDetailedAddress).collect(Collectors.toSet());
        Set<String> defaultFlagetoSet = distinctBizAddressBookList.stream().map(BizAddressBook::getDefaultFlag).collect(Collectors.toSet());

        // 查询是否存在符合条件的数据
        List<BizAddressBook> bizAddressBookList = bizAddressBookMapper.getBizAddressBookList(contactNameSet, contactPhoneSet, provinceNameSet, cityNametoSet, countyNameSet, addressSet, defaultFlagetoSet);
        // 创建一个集合,用于存储最终需要保存的数据
        List<BizAddressBook> bizAddressBooks;
        // 如果查询结果为空的话就直接保存
        if (bizAddressBookList.isEmpty()) {
            bizAddressBooks = distinctBizAddressBookList;
        } else {
            bizAddressBooks = new ArrayList<>();

            // 将传入的数据根据查询到的数据进行过滤,过滤出查询到的数据中不存在的数据,然后进行保存
            bookList.forEach(book -> {
                // 从查询到的数据中过滤和当前遍历的数据完全一致的数据
                long count = bizAddressBookList.stream().filter(
                        b -> Objects.equals(b.getContactName(), book.getContactName())
                                && Objects.equals(b.getContactPhone(), book.getContactPhone())
                                && Objects.equals(b.getProvinceName(), book.getProvinceName())
                                && Objects.equals(b.getCityName(), book.getCityName())
                                && Objects.equals(b.getCountyName(), book.getCountyName())
                                && Objects.equals(b.getDetailedAddress(), book.getDetailedAddress())
                ).count();
                // 如果一致的数据条数为0,则添加到需要保存的集合中,后续进行保存
                if (count == 0) {
                    bizAddressBooks.add(book);
                }
            });
        }


        int bookSize = bookList.size();
        if (!bizAddressBooks.isEmpty()) {
            int addressSize = bizAddressBooks.size();
            bizAddressBookMapper.insertBatch(bizAddressBooks);
            if (addressSize == bookSize) {
                return "导入成功,本次一共导入"+ bookSize +"条数据,成功导入"+ addressSize +"条数据,导入失败0条数据";
            } else {
                return "导入成功,本次一共导入"+ bookSize +"条数据,成功导入"+ addressSize +"条数据,导入失败"+(bookSize - addressSize)+"条数据(失败原因可能为该联系人下面存在相同地址)";
            }
        }
        return "导入失败,本次一共导入"+ bookSize +"条数据,成功导入0条数据,导入失败"+ bookSize +"条数据(失败原因可能为该联系人下面存在相同地址)";
    }
}
