package com.om.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.om.entity.dto.AppBaseDTO;
import com.om.entity.dto.BrandDTO;
import com.om.entity.dto.BrandQueryPageDTO;
import com.om.entity.dto.GuidDTO;
import com.om.entity.po.Brand;
import com.om.entity.po.BrandClient;
import com.om.entity.po.Client;
import com.om.entity.vo.APPBrandVO;
import com.om.entity.vo.BrandQueryPageVO;
import com.om.entity.vo.BrandVO;
import com.om.exception.BadReqException;
import com.om.mapper.BrandMapper;
import com.om.service.IBrandClientService;
import com.om.service.IBrandService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.om.service.IClientService;
import com.om.utils.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author bmmx
 * @since 2024-02-07
 */
@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements IBrandService {

    @Resource
    private IBrandClientService brandClientService;

    @Resource
    private JwtUtils jwtUtils;

    @Resource
    private IClientService clientService;

    @Override
    @Transactional
    public Result createBrand(BrandDTO dto) {
        if (BeanUtil.isEmpty(dto)) {
            throw new BadReqException("数据为空");
        }

        //保存品牌
        Brand brand = BeanUtil.copyProperties(dto, Brand.class);
        LocalDateTime now = LocalDateTime.now();
        brand.setCreateTime(now);
        brand.setUpdateTime(now);

        this.save(brand);

        //保存客户端和品牌的关联
        List<Integer> clientIds = dto.getClientIds();
        if (!CollectionUtil.isEmpty(clientIds)) {
            //重新查询一遍
            Brand one = this.getById(brand);
            List<BrandClient> brandClients = new ArrayList<>();
            for (Integer clientId : clientIds) {
                BrandClient brandClient = new BrandClient();
                brandClient.setBrandId(one.getId());
                brandClient.setClientId(clientId);
                brandClients.add(brandClient);
            }
            // 批量保存
            brandClientService.saveBatch(brandClients);
        }

        return Result.ok();
    }

    @Override
    @Transactional
    public Result deleteBrand(Integer id) {
        // 根据id查询数据库
        Brand brand = this.getById(id);
        // 判断是否存在
        if (BeanUtil.isEmpty(brand)) {
            throw new BadReqException("该品牌不存在");
        }

        //先 删除 品牌和客户端的关联表
        List<BrandClient> list = brandClientService.lambdaQuery()
                .eq(BrandClient::getBrandId, brand.getId())
                .list();

        if (!CollectionUtil.isEmpty(list)) {
            List<Integer> collect = list.stream().map(c -> c.getId()).collect(Collectors.toList());

            brandClientService.removeByIds(collect);
        }

        //删除品牌表
        this.removeById(brand);

        return Result.ok();
    }

    @Override
    public Result<BrandVO> queryById(Integer id) {
        //根据id查询
        Brand brand = this.getById(id);
        //判断是否存在
        if (BeanUtil.isEmpty(brand)) {
            throw new BadReqException("该品牌不存在");
        }

        //封装vo
        BrandVO brandVO = BeanUtil.copyProperties(brand, BrandVO.class);
        //查询 品牌和客户端的关联表
        List<BrandClient> list = brandClientService.lambdaQuery()
                .eq(BrandClient::getBrandId, id)
                .list();

        if (!CollectionUtil.isEmpty(list)) {
            List<Integer> clientIds = list.stream().map(c -> c.getClientId()).collect(Collectors.toList());
            brandVO.setClientIds(clientIds);
        }


        return Result.ok(brandVO);
    }

    @Override
    @Transactional
    public Result updateBrand(BrandDTO dto) {
        if (BeanUtil.isEmpty(dto)) {
            throw new BadReqException("数据为空");
        }

        //修改品牌
        //根据dto查询数据库
        Brand brand = this.getById(dto.getId());
        if (BeanUtil.isEmpty(brand)) {
            throw new BadReqException("该品牌不存在");
        }
        BeanUtil.copyProperties(dto, brand);
        LocalDateTime now = LocalDateTime.now();
        brand.setUpdateTime(now);

        this.updateById(brand);

        //修改 客户端和品牌的关联

        //先删除   后新增
        //批量查询
        List<BrandClient> brandClients = brandClientService.lambdaQuery()
                .eq(BrandClient::getBrandId, brand.getId())
                .list();

        if (!CollectionUtil.isEmpty(brandClients)) {
            //删除
            List<Integer> ids = brandClients.stream().map(c -> c.getId()).collect(Collectors.toList());
            brandClientService.removeByIds(ids);
        }
        //新增
        List<Integer> clientIds = dto.getClientIds();
        if (!CollectionUtil.isEmpty(clientIds)) {

            List<BrandClient> brandClientList = new ArrayList<>();
            for (Integer clientId : clientIds) {
                BrandClient brandClient = new BrandClient();
                brandClient.setClientId(clientId);
                brandClient.setBrandId(brand.getId());
                brandClientList.add(brandClient);
            }
            // 批量保存
            brandClientService.saveBatch(brandClientList);
        }

        return Result.ok();
    }

    @Override
    public Result<List<BrandVO>> queryList() {
        List<Brand> list = this.list();

        List<BrandVO> brandVOS = BeanUtil.copyToList(list, BrandVO.class);
        if (CollectionUtil.isEmpty(brandVOS)) {
            return Result.ok(Collections.emptyList());
        }
        //根据品牌ids 批量查询
        for (BrandVO brandVO : brandVOS) {

            List<BrandClient> brandClients = brandClientService.lambdaQuery()
                    .eq(BrandClient::getBrandId, brandVO.getId())
                    .list();
            List<Integer> collect = brandClients.stream().map(c -> c.getClientId()).collect(Collectors.toList());

            brandVO.setClientIds(collect);
        }



        return Result.ok(brandVOS);
    }

    @Override
    public Result<BrandQueryPageVO> queryPageList(BrandQueryPageDTO dto) {
        //从dto中取数据
        Integer pageIndex = dto.getPageIndex();
        Integer pageSize = dto.getPageSize();
        String searchCn = dto.getSearchCn();
        String searchEn = dto.getSearchEn();

        //分页查询
        Page<Brand> page = this.lambdaQuery()
                .like(searchCn != null, Brand::getBrandCn, searchCn)
                .like(searchEn != null, Brand::getBrandEn, searchEn)
                .orderByDesc(Brand::getCreateTime)
                .page(new Page<>(pageIndex, pageSize));

        //封装vo
        BrandQueryPageVO brandQueryPageVO = new BrandQueryPageVO();
        brandQueryPageVO.setCurrent((int) page.getCurrent());
        brandQueryPageVO.setSize((int) page.getSize());
        brandQueryPageVO.setPages((int) page.getPages());
        brandQueryPageVO.setTotal((int) page.getTotal());
        if (searchCn !=null || searchEn !=null){
            brandQueryPageVO.setSearchCount(true);
        }
        List<Brand> records = page.getRecords();
        List<BrandVO> list = new ArrayList<>();
        for (Brand record : records) {
            BrandVO brandVO = BeanUtil.copyProperties(record, BrandVO.class);
            //根据id查询 关联表
            List<BrandClient> clients = brandClientService.lambdaQuery()
                    .eq(BrandClient::getBrandId, record.getId())
                    .list();
            if (!CollectionUtil.isEmpty(clients)){
                List<Integer> collect = clients.stream().map(c -> c.getClientId()).collect(Collectors.toList());
                brandVO.setClientIds(collect);

            }
            list.add(brandVO);

        }
        brandQueryPageVO.setRecords(list);
        return Result.ok(brandQueryPageVO);
    }

    @Override
    public Result getAPPList(AppBaseDTO dto) {
        if (BeanUtil.isEmpty(dto)){
            return Result.fail("未获取到数据").result(ResultCode.NO_DATA);
        }

        String guid = dto.getGuid();
        GuidDTO guidDTO = AesUtil.getGuidDTOFromGuid(guid);
        String clientNum = guidDTO.getClientNum();
        //根据客户端编号查询客户端id
        Client client = clientService.lambdaQuery()
                .eq(Client::getNumber, clientNum)
                .one();
        if (BeanUtil.isEmpty(client)){
            throw new BadReqException("该客户端不存在！！");
        }
        //根据客户端id查询品牌客户端关联表
        List<BrandClient> brandClients = brandClientService.lambdaQuery()
                .eq(BrandClient::getClientId, client.getId())
                .list();
        List<Integer> brandids = brandClients.stream().map(c -> c.getBrandId()).collect(Collectors.toList());
        if (brandids.isEmpty()){
           return Result.ok();
        }
        List<Brand> brands = this.listByIds(brandids);
        List<APPBrandVO> brandVOS = new ArrayList<>();
        for (Brand brand : brands) {
            APPBrandVO brandVO = BeanUtil.copyProperties(brand, APPBrandVO.class);

            //查询brand_client
            List<Integer> clientIds = brandClientService.lambdaQuery()
                    .eq(BrandClient::getBrandId, brand.getId())
                    .list().stream().map(c -> c.getClientId()).collect(Collectors.toList());
            if (clientIds.isEmpty()){
                throw new BadReqException("该品牌下没有查询到客户端");
            }
            brandVO.setClientIds(clientIds);
            brandVO.setCreateTime(brand.getCreateTime().toInstant(ZoneOffset.of("+8")).toEpochMilli());
            brandVOS.add(brandVO);
        }


        return Result.ok(brandVOS);
    }
}
