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.DistributorDTO;
import com.om.entity.dto.DistributorQueryPageDTO;
import com.om.entity.dto.GuidDTO;
import com.om.entity.po.Distributor;
import com.om.entity.po.User;
import com.om.entity.vo.APpDistributorVO;
import com.om.entity.vo.DistributorQueryPageVO;
import com.om.entity.vo.DistributorVO;
import com.om.exception.BadReqException;
import com.om.mapper.DistributorMapper;
import com.om.service.IDistributorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.om.service.IUserService;
import com.om.utils.AesUtil;
import com.om.utils.JwtUtils;
import com.om.utils.Result;
import com.om.utils.ResultCode;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 修理厂信息表 服务实现类
 * </p>
 *
 * @author bmmx
 * @since 2024-02-08
 */
@Service
public class DistributorServiceImpl extends ServiceImpl<DistributorMapper, Distributor> implements IDistributorService {

    @Resource
    private IUserService userService;

    @Resource
    private JwtUtils jwtUtils;

    @Override
    public Result createDistributor(DistributorDTO dto) {
        //判断是否为空
        if (BeanUtil.isEmpty(dto)){
            throw new BadReqException("参数为空");
        }

        Distributor distributor = BeanUtil.copyProperties(dto, Distributor.class);
        LocalDateTime now = LocalDateTime.now();
        distributor.setCreateTime(now);
        distributor.setUpdateTime(now);

        //保存
        this.save(distributor);
        return Result.ok();
    }

    @Override
    public Result<DistributorVO> queryDistributorById(Integer id) {
        //根据id查询
        Distributor distributor = this.getById(id);
        //判断是否为空
        if (BeanUtil.isEmpty(distributor)){
            throw new BadReqException("该维修厂不存在");
        }

        //封装vo
        DistributorVO distributorVO = BeanUtil.copyProperties(distributor, DistributorVO.class);
        return Result.ok(distributorVO);
    }

    @Override
    public Result<List<DistributorVO>> queryList() {
        //查询集合
        List<Distributor> list = this.list();
        if (CollectionUtil.isEmpty(list)){
            return Result.ok(Collections.emptyList());
        }

        List<DistributorVO> distributorVOS = BeanUtil.copyToList(list, DistributorVO.class);

        return Result.ok(distributorVOS);
    }

    @Override
    public Result upStatus(Integer id, Integer status) {
        //根据id查询
        Distributor distributor = this.getById(id);
        if (BeanUtil.isEmpty(distributor)){
            throw new BadReqException("该维修厂不存在");
        }

        //修改状态
        distributor.setEnableStatus(status);
        this.updateById(distributor);
        return Result.ok();
    }

    @Override
    public Result updateDistributor(DistributorDTO dto) {
        //根据id查询
        Distributor distributor = this.getById(dto.getId());
        if (BeanUtil.isEmpty(distributor)){
            throw new BadReqException("该维修厂不存在");
        }

        BeanUtil.copyProperties(dto,distributor);
        distributor.setUpdateTime(LocalDateTime.now());

        //修改
        this.updateById(distributor);
        return Result.ok();
    }

    @Override
    public Result<DistributorQueryPageVO> queryPageList(DistributorQueryPageDTO dto) {
        Integer pageSize = dto.getPageSize();
        Integer pageIndex = dto.getPageIndex();
        String searchName = dto.getSearchName();
        String searchTelephone = dto.getSearchTelephone();
        //分页查询
        Page<Distributor> page = this.lambdaQuery()
                .like(searchName != null, Distributor::getCompany, searchName)
                .like(searchTelephone != null, Distributor::getTelephone, searchTelephone)
                .orderByDesc(Distributor::getCreateTime)
                .page(new Page<>(pageIndex, pageSize));

        //封装vo
        DistributorQueryPageVO vo = new DistributorQueryPageVO();
        vo.setCurrent((int) page.getCurrent());
        vo.setSize((int) page.getSize());
        vo.setPages((int) page.getPages());
        vo.setTotal((int) page.getTotal());
        if (searchName !=null || searchTelephone !=null){
            vo.setSearchCount(true);
        }
        List<Distributor> records = page.getRecords();

        List<DistributorVO> distributorVOS = BeanUtil.copyToList(records, DistributorVO.class);

        vo.setRecords(distributorVOS);

        return Result.ok(vo);
    }

    @Override
    public Result AppGetById(AppBaseDTO dto) {
        String guid = dto.getGuid();
        GuidDTO guidDTO = AesUtil.getGuidDTOFromGuid(guid);
        Integer userId = guidDTO.getUserId();

        //查询用户所在的维修厂id
        User user = userService.getById(userId);
        if (BeanUtil.isEmpty(user)){
            return Result.fail("用户不存在").result(ResultCode.USER_NO_EXIST);
        }

        Integer distributorId = user.getDistributorId();
        //根据id查询维修厂
        Distributor distributor = this.getById(distributorId);

        APpDistributorVO aPpDistributorVO = BeanUtil.copyProperties(distributor, APpDistributorVO.class);
        return Result.ok(aPpDistributorVO);

    }

    @Override
    public Result Appupdate(APpDistributorVO distributorVO) {
        String guid = distributorVO.getGuid();
        GuidDTO guidDTO = AesUtil.getGuidDTOFromGuid(guid);
        Integer userId = guidDTO.getUserId();

        //查询用户所在的维修厂id
        User user = userService.getById(userId);
        if (BeanUtil.isEmpty(user)){
            return Result.fail("用户不存在").result(ResultCode.USER_NO_EXIST);
        }
        Integer distributorId = user.getDistributorId();

        //根据id查询
        Distributor distributor = this.getById(distributorId);
        if (BeanUtil.isEmpty(distributor)){
            throw new BadReqException("用户查询失败维修厂不存在");
        }
        BeanUtil.copyProperties(distributorVO,distributor);
        distributor.setUpdateTime(LocalDateTime.now());
        //修改操作
        this.updateById(distributor);
        return Result.ok();
    }

    @Override
    public Result deleteDistributorById(Integer id) {
        //根据id查询
        Distributor distributor = this.lambdaQuery()
                .eq(Distributor::getId, id)
                .one();
        if (BeanUtil.isEmpty(distributor)){
            throw new BadReqException("该维修厂信息不存在");
        }
        //查询 user
        List<User> userList = userService.lambdaQuery()
                .eq(User::getDistributorId, distributor.getId())
                .list();
        if (!userList.isEmpty()){
            throw new BadReqException("该维修厂已被客户端账号绑定，不能删除");
        }
        this.removeById(id);
        return Result.ok();
    }
}
