package com.junmp.jyzb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.junmp.jyzb.Repository.SupplierRepository;
import com.junmp.jyzb.api.bean.dto.FetchingDataDto.SupplierInfoDto;
import com.junmp.jyzb.api.bean.dto.MQDto;
import com.junmp.jyzb.api.bean.dto.SupplierDto;
import com.junmp.jyzb.api.bean.query.QuerySupplierReq;
import com.junmp.jyzb.api.bean.req.UpdateSupplierReq;
import com.junmp.jyzb.api.exception.enums.SupplierExceptionEnum;
import com.junmp.jyzb.entity.Supplier;
import com.junmp.jyzb.service.OrderMainService;
import com.junmp.jyzb.service.SupplierService;
import com.junmp.jyzb.utils.DateTimeUtil;
import com.junmp.jyzb.utils.RabbitMQSendMsg;
import com.junmp.v2.common.exception.base.ServiceException;
import com.junmp.v2.common.util.BeanPlusUtil;
import com.junmp.v2.db.api.factory.PageFactory;
import com.junmp.v2.db.api.factory.PageResultFactory;
import com.junmp.v2.db.api.page.PageResult;
import liquibase.pro.packaged.O;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import com.junmp.jyzb.mapper.SupplierMapper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SupplierServiceImpl extends ServiceImpl<SupplierMapper, Supplier> implements SupplierService {


    @Resource
    OrderMainService orderMainService;

    @Autowired
    private RabbitMQSendMsg MQ;

    @Resource
    private SupplierMapper supplierMapper;
    
    @Resource
    private SupplierRepository supplierRepository;

    @Override
    public Object addEs() {
        QuerySupplierReq req = new QuerySupplierReq();

        return null;
    }

    @Override
    public String AddSupplier(UpdateSupplierReq req) {
        List<Supplier> list = list(new LambdaQueryWrapper<Supplier>()
                .eq(Supplier::getName, req.getName()).or().eq(Supplier::getCode, req.getCode()));
        if (CollectionUtil.isNotEmpty(list)){
            for (Supplier supplier:list) {
                if (supplier.getName().equals(req.getName())){
                    throw new ServiceException(SupplierExceptionEnum.SUPPLIER_NAME_IS_EXIST);
                }
                if (supplier.getCode().equals(req.getCode())){
                    throw new ServiceException(SupplierExceptionEnum.SUPPLIER_CODE_IS_EXIST);
                }
            }
        }
        Supplier supplier = new Supplier();
        String ID=UUID.randomUUID().toString();
        req.setId(ID);
        BeanPlusUtil.copyProperties(req, supplier);
        supplier.setCreateTime(DateTimeUtil.getCurrentDateTime());
        supplier.setUpdateTime(DateTimeUtil.getCurrentDateTime());

        String exchangeName="topicExchange";
        MQDto mqDto = new MQDto();
        mqDto.setApi("InfoChange");
        //更改类别，1为类型
        mqDto.setType(3);
        mqDto.setMessage("Adding supplierInfo");
        MQ.sendToExchange(exchangeName,"org",mqDto);
        this.save(supplier);

        return ID;
    }



    @Override
    public boolean DeleteSupplier(UpdateSupplierReq req) {
        this.removeById(req.getId());
        return true;
    }

    @Override
    public boolean UpdateSupplier(UpdateSupplierReq req) {
        Supplier supplier = this.getById(req.getId());
        if (ObjectUtil.isNull(supplier)) {
            throw new ServiceException(SupplierExceptionEnum.SUPPLIER_NOT_EXIST);
        }
        req.setCode(supplier.getCode());//为了控制code不一致的情况
        BeanPlusUtil.copyProperties(req, supplier);
        supplier.setUpdateTime(DateTimeUtil.getCurrentDateTime());
        String exchangeName="topicExchange";
        MQDto mqDto = new MQDto();
        mqDto.setApi("InfoChange");
        //更改类别，1为类型
        mqDto.setType(3);
        mqDto.setMessage("Updating supplierInfo");
        MQ.sendToExchange(exchangeName,"org",mqDto);
        return this.updateById(supplier);
    }



    public List<String>  CheckSupplierList(List<String> req){
        List<String> nonexistentSuppliers = new ArrayList<>();
        //如果供应商为空，直接返回一个空的数组
        if (ObjectUtil.isNull(req)){
            return nonexistentSuppliers;
        }
        LambdaQueryWrapper<Supplier> wp = new LambdaQueryWrapper<>();
        wp.in(ObjectUtil.isNotEmpty(req), Supplier::getId, req);
        List<Supplier> st = list(wp);

        for (String supplierId : req) {
            boolean found = false;
            for (Supplier supplier : st) {
                if (supplier.getId().equals(supplierId)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                nonexistentSuppliers.add(supplierId);
            }
        }

        return nonexistentSuppliers;

    }



    @Override
    public List<SupplierDto> ShowSupplier(QuerySupplierReq req) {

        LambdaQueryWrapper<Supplier> wrapper = createWrapper(req);
        List<SupplierDto> dto=new ArrayList<>();

        //判断是否需要全部的厂商商信息还是只需要名字去重的厂商名称，如果是去重的，这里给true,但是返回的id默认是第一个名称的id
        if (ObjectUtil.isNotNull(req.getFlag()) && req.getFlag()){
            dto=supplierMapper.selectDistinctList();
        }else {
            List<Supplier> list = this.list(wrapper);
            for (Supplier supplier:list) {
                SupplierDto sd=new SupplierDto();
                BeanPlusUtil.copyProperties(supplier, sd);
                dto.add(sd);
            }

        }

        return dto;
    }

    //分页
    @Override
    public PageResult<Supplier> ShowSupplierPage(QuerySupplierReq req) {
        LambdaQueryWrapper<Supplier> wrapper = createWrapper(req);
        Page<Supplier> page = page(PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize()), wrapper);

        return PageResultFactory.createPageResult(page);
    }

    @Override
    public List<SupplierInfoDto> alignSupplierInfo(UpdateSupplierReq req) {
        String date = DateTimeUtil.TimeLongToString(req.getUpdateTime());
        return supplierMapper.alignSupplierInfo(date);
    }

    @Override
    public Boolean ChangeSupplierState(UpdateSupplierReq req) {
        Supplier supplier = this.getById(req.getId());
        if (ObjectUtil.isNull(supplier)) {
            throw new ServiceException(SupplierExceptionEnum.SUPPLIER_NOT_EXIST);
        }
        BeanPlusUtil.copyProperties(req, supplier);
        supplier.setUpdateTime(DateTimeUtil.getCurrentDateTime());
        return this.updateById(supplier);
    }



    private LambdaQueryWrapper<Supplier> createWrapper(QuerySupplierReq req) {
        LambdaQueryWrapper<Supplier> wrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isEmpty(req)) {
            return wrapper;
        }
        //根据供应商短码查询查询
        wrapper.like(ObjectUtil.isNotEmpty(req.getCode()), Supplier::getCode, req.getCode());
        //类型
        wrapper.eq(ObjectUtil.isNotEmpty(req.getAgencyType()), Supplier::getAgencyType, req.getAgencyType());
        //供应商ID
        wrapper.like(ObjectUtil.isNotEmpty(req.getId()), Supplier::getId, req.getId());
        //供应商名称模糊查询
        wrapper.like(ObjectUtil.isNotEmpty(req.getName()), Supplier::getName, req.getName());
        //供应商名称模糊查询
        wrapper.like(ObjectUtil.isNotEmpty(req.getShortName()), Supplier::getShortName, req.getShortName());
        wrapper.eq(ObjectUtil.isNotNull(req.getState()),Supplier::getState,req.getState());
        //contacts联系人
        wrapper.like(ObjectUtil.isNotEmpty(req.getContacts()), Supplier::getContacts, req.getContacts());
        //根据创建时间降序
        if (ObjectUtil.isNotNull(req.getColumn())){

            wrapper.orderBy(ObjectUtil.isNotNull(req.getColumn()),(ObjectUtil.isNotNull(req.getOrder()) && req.getOrder().equals("asc")),Supplier::getName);

        }else {

            wrapper.orderByDesc(Supplier::getCreateTime);
        }
        return wrapper;
    }
}
