package com.mvc.service.produce;

import com.mvc.dao.DicProductionPartMapper;
import com.mvc.entity.DicProductionPart;
import com.mvc.entity.DicProductionPartExample;
import com.mvc.model.produce.DicProductionPartModel;
import com.mvc.model.produce.FilterDataModel;
import com.mvc.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Transactional
public class DicProductionPartService {

    @Resource
    private DicProductionPartMapper dicProductionPartMapper;

    /**
     * 查询筛选器数据
     *
     * @param type (0:全部,1:只查1级系统保留属性)
     * @return
     */
    public List<FilterDataModel> findFilterDataModelList(int type) {
        List<FilterDataModel> filterDataModelList = new ArrayList<>();
        List<DicProductionPartModel> dicProductionParts = selectByExample(null);
        if (dicProductionParts == null) {
            return filterDataModelList;
        }
        Map<Integer, List<DicProductionPartModel>> lvMap = dicProductionParts.stream().collect(Collectors.groupingBy(DicProductionPartModel::getParentId));
        if (lvMap.isEmpty() || !lvMap.containsKey(0)) {
            return filterDataModelList;
        }

        List<DicProductionPartModel> lv1List = lvMap.get(0);
        for (DicProductionPartModel lv1 : lv1List) {
            if (type == 1 && lv1.getSystemFlag() != 1) {
                continue;
            }
            FilterDataModel dataModel = new FilterDataModel(lv1);

            if (lvMap.containsKey(lv1.getId())) {
                List<FilterDataModel.Option> options = new ArrayList<>();
                for (int i = 0; i < lvMap.get(lv1.getId()).size(); i++) {
                    FilterDataModel.Option option = new FilterDataModel.Option();
                    option.setLabel(lvMap.get(lv1.getId()).get(i).getPartName());
                    option.setValue(lvMap.get(lv1.getId()).get(i).getId().toString());
                    option.setImage(lvMap.get(lv1.getId()).get(i).getPartImage());
                    option.setOrder(lvMap.get(lv1.getId()).get(i).getViewOrder());
                    //测试图片
                    //option.setImage("https://www.xzeai.com:6090/image/rawdata/2024-11/0000020264/11211100116_20241112000345_B.jpg");
                    options.add(option);
                }
                Collections.sort(options, Comparator.comparing(FilterDataModel.Option::getOrder));
                dataModel.setOptions(options);
            }
            if (dataModel.getOptions()!=null && dataModel.getOptions().size() > 0) {
                filterDataModelList.add(dataModel);
            }
        }
        Collections.sort(filterDataModelList, Comparator.comparing(FilterDataModel::getOrder));
        return filterDataModelList;
    }

    public List<DicProductionPartModel> findAllDicProductionPart(DicProductionPartModel queryModel) {
        DicProductionPartExample example = new DicProductionPartExample();
        DicProductionPartExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(queryModel.getCreateMan())) {
            criteria.andCreateManLike(StringUtil.getLikeFormat(queryModel.getCreateMan()));
        }

        if (queryModel.getLevel() != null) {
            criteria.andLevelEqualTo(queryModel.getLevel());
        }

        if (queryModel.getParentId() != null) {
            criteria.andParentIdEqualTo(queryModel.getParentId());
        }

        if (queryModel.getSystemFlag() != null) {
            criteria.andSystemFlagEqualTo(queryModel.getSystemFlag());
        }

        example.setOrderByClause("PARENT_ID,VIEW_ORDER");

        return selectByExample(example);
    }

    /**
     * 根据id获取记录
     *
     * @param id
     * @return
     */
    public DicProductionPartModel getDicProductionPartById(int id) {
        DicProductionPart dicProductionPart = dicProductionPartMapper.selectByPrimaryKey(id);
        DicProductionPartModel model = new DicProductionPartModel();
        BeanUtils.copyProperties(dicProductionPart, model);
        return model;
    }

    /**
     * 获取系统保留类型的根节点
     *
     * @return
     */
    public DicProductionPartModel getSystemPartModel() {
        DicProductionPartExample example = new DicProductionPartExample();
        example.createCriteria().andLevelEqualTo(1).andSystemFlagEqualTo(1);
        List<DicProductionPartModel> list = selectByExample(example);
        if (!list.isEmpty()) {
            DicProductionPartModel model = list.get(0);

        }
        return list.size() > 0 ? list.get(0) : null;
    }

    /**
     * 根据条件查询列表
     *
     * @param example
     * @return
     */
    private List<DicProductionPartModel> selectByExample(DicProductionPartExample example) {
        List<DicProductionPart> deviceSnManagements = dicProductionPartMapper.selectByExample(example);
        List<DicProductionPartModel> resList = new ArrayList<>();
        for (DicProductionPart deviceSnManagement : deviceSnManagements) {
            DicProductionPartModel model = new DicProductionPartModel();
            BeanUtils.copyProperties(deviceSnManagement, model);
            resList.add(model);
        }
        return resList;
    }

    public DicProductionPartModel saveDicProductionPart(DicProductionPartModel model) {
        model.setCreateTime(new Date());
        if (model.getParentId() == null) {
            model.setParentId(0);
        }
        if (model.getViewOrder() == null) {
            model.setViewOrder(getNextViewOrderNumber(model.getParentId()));
        }
        DicProductionPart dicProductionPart = new DicProductionPart();
        BeanUtils.copyProperties(model, dicProductionPart);
        int insert = dicProductionPartMapper.insert(dicProductionPart);
        model.setId(dicProductionPart.getId());
        return model;
    }

    //批量添加
    public DicProductionPartModel batchAddDicProductionPart(DicProductionPartModel model) {
        for (DicProductionPartModel detail : model.getDetails()) {
            if (StringUtils.isEmpty(detail.getPartName())) {
                continue;
            }
            detail.setParentId(model.getId());
            detail.setLevel(2);
            detail.setCreateMan(model.getCreateMan());
            detail.setPartNum(1);
            detail.setSystemFlag(0);
            saveDicProductionPart(detail);
        }
        return model;
    }

    /**
     * 获取下一个排序号
     *
     * @param parentId
     * @return
     */
    private int getNextViewOrderNumber(int parentId) {
        DicProductionPartExample example = new DicProductionPartExample();
        DicProductionPartExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(parentId);

        List<DicProductionPart> list = dicProductionPartMapper.selectByExample(example);
        if (list.size() == 0) {
            return 1;
        } else {
            OptionalInt maxViewOrder = list.stream()
                    .mapToInt(DicProductionPart::getViewOrder)
                    .max();
            if (maxViewOrder.isPresent()) {
                return maxViewOrder.getAsInt() + 1;
            }
        }
        return list.size() + 1;
    }

    private List<DicProductionPart> findDicProductionPartsByParentId(int parentId) {
        DicProductionPartExample example = new DicProductionPartExample();
        DicProductionPartExample.Criteria criteria = example.createCriteria();
        criteria.andParentIdEqualTo(parentId);
        return dicProductionPartMapper.selectByExample(example);
    }

    public DicProductionPartModel updateDicProductionPart(DicProductionPartModel model) {
        DicProductionPart DicProductionPart = dicProductionPartMapper.selectByPrimaryKey(model.getId());
        BeanUtils.copyProperties(model, DicProductionPart);
        int i = dicProductionPartMapper.updateByPrimaryKey(DicProductionPart);
        return model;
    }

    public int deleteDicProductionPart(int id) {
        //int i = dicProductionPartMapper.deleteByPrimaryKey(id);
        DicProductionPartExample example = new DicProductionPartExample();
        DicProductionPartExample.Criteria criteria1 = example.createCriteria();
        criteria1.andIdEqualTo(id);

        DicProductionPartExample.Criteria criteria2 = example.createCriteria();
        criteria2.andParentIdEqualTo(id);

        example.or(criteria2);

        return dicProductionPartMapper.deleteByExample(example);
    }

    /**
     * 获取字典的Map集合
     *
     * @return
     */
    public Map<Integer, DicProductionPartModel> getAllDicProductionPartMap() {
        List<DicProductionPartModel> list = selectByExample(null);
        return list.stream().collect(Collectors.toMap(DicProductionPartModel::getId, Function.identity()));
    }

    /**
     * 检查数据是否合法(批量)
     *
     * @param model
     * @return
     */
    public String checkMultipleDataLegitimacy(DicProductionPartModel model) {
        List<DicProductionPartModel> list = model.getDetails();
        List<Integer> orders = new ArrayList<>();
        List<String> names = new ArrayList<>();
        String error = "";
        if (list != null && list.size() > 0) {
            for (DicProductionPartModel partModel : list) {
                if (StringUtils.isEmpty(partModel.getPartName())) {
                    continue;
                }
                if (orders.contains(partModel.getViewOrder())) {
                    error = "本次提交数据序号存在重复";
                    break;
                }
                if (names.contains(partModel.getPartName())) {
                    error = "本次提交数据名称存在重复";
                    break;
                }
                partModel.setParentId(model.getId());
                error = checkDataLegitimacy(partModel);
                if (StringUtils.isNotEmpty(error)) {
                    break;
                }
                orders.add(partModel.getViewOrder());
                names.add(partModel.getPartName());
            }
        } else {
            error = checkDataLegitimacy(model);
        }
        return error;
    }

    /**
     * 校验数据是否合法
     *
     * @param model
     * @return
     */
    public String checkDataLegitimacy(DicProductionPartModel model) {
        List<DicProductionPart> list = findDicProductionPartsByParentId(model.getParentId());

        Optional<DicProductionPart> optionalOrder = null;

        //校验序号
        if (model.getId() == null) {//新增
            optionalOrder = list.stream().filter(s -> s.getViewOrder().equals(model.getViewOrder())).findFirst();
        } else {
            optionalOrder = list.stream().filter(s -> s.getViewOrder().equals(model.getViewOrder()) && !s.getId().equals(model.getId())).findFirst();
        }
        if (optionalOrder.isPresent()) {
            return String.format("[%s]序号重复,请重新输入", model.getViewOrder());
        }

        //校验名称
        Optional<DicProductionPart> optionalName = null;
        if (model.getId() == null) {//新增
            optionalName = list.stream().filter(s -> s.getPartName().equals(model.getPartName())).findFirst();
        } else {
            optionalName = list.stream().filter(s -> s.getPartName().equals(model.getPartName()) && !s.getId().equals(model.getId())).findFirst();
        }
        if (optionalName.isPresent()) {
            return String.format("[%s]名称重复,请重新输入", model.getPartName());
        }

        return null;
    }
}
