package com.ximai.mes.md.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ximai.common.exception.ServiceException;
import com.ximai.common.utils.data.DateUtils;
import com.ximai.common.utils.bean.BeanValidators;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ximai.mes.md.mapper.MdClientItemMapper;
import com.ximai.mes.md.domain.MdClientItem;
import com.ximai.mes.md.service.IMdClientItemService;

import javax.validation.Validator;


/**
 * 客户产品对照Service业务层处理
 *
 * @author generator
 * @date 2024-01-25
 */
@Service
@AllArgsConstructor
public class MdClientItemServiceImpl extends ServiceImpl<MdClientItemMapper, MdClientItem> implements IMdClientItemService {

    @Autowired
    private Validator validator;
    @Autowired
    private MdClientItemMapper mdClientItemMapper;


    @Override
    public IPage<MdClientItem> page(Map<String, Object> params) {
        final Integer pageNum = MapUtil.getInt(params, "pageNum");
        final Integer pageSize = MapUtil.getInt(params, "pageSize");
        return baseMapper.pageBy(new Page<>(pageNum, pageSize), params);
    }

    /**
     * 查询客户产品对照
     *
     * @param id 客户产品对照主键
     * @return 客户产品对照
     */
    @Override
    public MdClientItem selectById(String id) {
        return baseMapper.getById(id);
    }

    @Override
    public List<MdClientItem> selectList(MdClientItem mdClientItem) {
        QueryWrapper<MdClientItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("client_code", mdClientItem.getClientCode());
        return list(queryWrapper);
    }

    /**
     * 新增客户产品对照
     *
     * @param mdClientItem 客户产品对照
     * @return 结果
     */
    @Override
    public Boolean insert(MdClientItem mdClientItem) {
        mdClientItem.setCreateTime(DateUtils.getNowDate());
        return save(mdClientItem);
    }

    /**
     * 修改客户产品对照
     *
     * @param mdClientItem 客户产品对照
     * @return 结果
     */
    @Override
    public Boolean update(MdClientItem mdClientItem) {
        mdClientItem.setUpdateTime(DateUtils.getNowDate());
        return updateById(mdClientItem);
    }

    /**
     * 批量删除客户产品对照
     *
     * @param ids 需要删除的客户产品对照主键
     * @return 结果
     */
    @Override
    public Boolean deleteByIds(List<String> ids) {
        return removeByIds(ids);
    }

    /**
     * 删除客户产品对照信息
     *
     * @param id 客户产品对照主键
     * @return 结果
     */
    @Override
    public Boolean deleteById(String id) {
        return removeById(id);
    }

    /**
     * 导入产品对照组
     *
     * @param mdClientItemsList
     * @param updateSupport
     * @param operaName
     * @return Msg
     */
    @Override
    public String importMdClientItem(List<MdClientItem> mdClientItemsList, String clientCode, boolean updateSupport, String operaName) {
        if (CollectionUtil.isEmpty(mdClientItemsList)) {
            throw new ServiceException("导入客户对照组数据不能为空！");
        }
        int successNum = 0;
        int failNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failMsg = new StringBuilder();
        List<String> clientItemCodeList = mdClientItemMapper.getClientCodeListByClientCode(clientCode);
        // 筛选出没有的数据
        List<MdClientItem> addMdClientItemList = mdClientItemsList.stream().filter(mdClientItem -> !clientItemCodeList.contains(mdClientItem.getItemCode())).collect(Collectors.toList());
        // 筛选出可能更新的数据
        List<MdClientItem> updateMdClientItemList = mdClientItemsList.stream().filter(mdClientItem -> clientItemCodeList.contains(mdClientItem.getItemCode())).collect(Collectors.toList());


        for (MdClientItem mdClientItem : addMdClientItemList) {
            try {
                BeanValidators.validateWithException(validator, mdClientItem);
                mdClientItem.setClientCode(clientCode);
                mdClientItem.setCreateBy(operaName);
                this.insert(mdClientItem);
                successNum++;
                successMsg.append("<br/>" + successNum + "、产品对照组 " + mdClientItem.getItemCode() + " 导入成功");
            } catch (Exception e) {
                failNum++;
                String msg = "<br/>" + failNum + "、产品对照组 " + mdClientItem.getItemCode() + " 导入失败：";
                failMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        for (MdClientItem mdClientItem : updateMdClientItemList) {
            try {
                if (updateSupport) {
                    BeanValidators.validateWithException(validator, mdClientItem);
                    mdClientItem.setUpdateBy(operaName);
                    mdClientItem.setClientCode(clientCode);
                    this.update(mdClientItem);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、产品对照组 " + mdClientItem.getItemCode() + " 更新成功");
                } else {

                    failNum++;
                    failMsg.append("<br/>" + failNum + "、产品对照组 " + mdClientItem.getItemCode() + " 已存在");

                }
            } catch (Exception e) {
                failNum++;
                String msg = "<br/>" + failNum + "、产品对照组 " + mdClientItem.getItemCode() + " 导入失败：";
                failMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }


        if (failNum > 0) {
            failMsg.insert(0, "导入失败！共 " + failNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failMsg.toString());
        } else {
            successMsg.insert(0, "数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

}
