package com.repair.controller;


import com.repair.api.RepairArticleTypeControllerAPI;
import com.repair.common.utils.paramUtils;
import com.repair.model.pojo.RepairArticleType;
import com.repair.model.pojo.RepairShiftSettings;
import com.repair.model.request.updateArticleDetailRequest;
import com.repair.model.request.updateArticleNumRequest;
import com.repair.model.request.updateRepairArticleTypeRequest;
import com.repair.model.result.CommonResult;
import com.repair.model.result.PageUtils;
import com.repair.model.vo.RepairArticleChildVo;
import com.repair.model.vo.RepairArticleConsumeVo;
import com.repair.model.vo.RepairArticleTypeTreeVo;
import com.repair.model.vo.RepairWorkTypeVo;
import com.repair.services.RepairArticleTypeService;
import com.repair.services.RepairConsumeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ceshi
 * @since 2023-07-18
 */
@RestController
public class RepairArticleTypeController implements RepairArticleTypeControllerAPI {

    @Autowired
    private RepairConsumeService repairConsumeService;
    @Autowired
    private RepairArticleTypeService repairArticleTypeService;

    /**
     * 新增报修物品
     *
     * @param rat           报修物品数据
     * @param bindingResult 是否为空判断
     * @return
     */
    @Override
    public CommonResult InsertRepairArticleType(RepairArticleType rat, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        RepairArticleType data = repairArticleTypeService.getRepairArticleTypeByName(rat.getName(), rat.getSchoolId());
        if (data != null) {
            return CommonResult.fail("该物品已存在！");
        }

        int result = repairArticleTypeService.insertRepairArticleType(rat);

        return result > 0 ? CommonResult.ok("添加成功") : CommonResult.fail("添加失败");
    }

    /**
     * 根据数据ID更新报修物品数据
     *
     * @param uratr         更新的报修物品数据
     * @param bindingResult 是否为空判断
     * @return
     */
    @Override
    public CommonResult updateRepairArticleTypeById(updateRepairArticleTypeRequest uratr, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        RepairArticleType data = repairArticleTypeService.getRepairArticleTypeByName(uratr.getName(), uratr.getSchoolId());
        if (data != null && !data.getId().equals(uratr.getId())) {
            return CommonResult.fail("该物品已存在！");
        }

        RepairArticleType rat = new RepairArticleType();
        rat.setId(uratr.getId());
        rat.setName(uratr.getName());

        int result = repairArticleTypeService.updateRepairArticleType(rat);

        return result > 0 ? CommonResult.ok("修改成功") : CommonResult.fail("修改失败");
    }

    /**
     * 报修物品分页数据查询
     *
     * @param currentPage 当前页数
     * @param pageCount   一页数据条数
     * @param name        报修物品名称
     * @return
     */
    @Override
    public CommonResult queryPageRepairArticleTypes(int currentPage, int pageCount, String name) {
        PageUtils<RepairArticleType> result = repairArticleTypeService.queryPageRepairArticleTypes(currentPage, pageCount, name);
        return CommonResult.ok(result);
    }

    /**
     * 根据数据ID删除报修物品
     *
     * @param id 数据ID
     * @return
     */
    @Override
    public CommonResult deleteRepairArticleTypeById(int id) {
        RepairArticleType data = repairArticleTypeService.getRepairById(id);
        if (data == null) {
            return CommonResult.fail("当前数据不存在，删除失败！");
        }

        int result = repairArticleTypeService.deleteRepairArticleTypeById(id);

        return result > 0 ? CommonResult.ok("删除成功") : CommonResult.fail("删除失败");
    }

    /**
     * 根据校区ID查询报修物品树形图结构数据
     *
     * @param schoolId 校区ID
     * @return
     */
    @Override
    public CommonResult queryRepairArticleTypeTree(int schoolId) {
        List<RepairArticleType> result = repairArticleTypeService.getRepairArticleTypesBySchoolId(schoolId);
        List<RepairArticleTypeTreeVo> datas = QueryArticleTypeTreeRecords(0, result);

        return CommonResult.ok(datas);
    }

    /**
     * 根据校区查询报修物品数据
     *
     * @param schoolId
     * @return
     */
    @Override
    public CommonResult queryRepairArticleType(int schoolId) {
        List<RepairWorkTypeVo> result = repairArticleTypeService.getRepairArticleTypes(schoolId);
        return CommonResult.ok(result);
    }

    /**
     * 获取关联耗材数据
     *
     * @param schoolId 校区ID
     * @param keyWord  搜索内容
     * @return
     */
    @Override
    public CommonResult queryConsumeMaterial(int schoolId, String keyWord) {
        List<RepairArticleChildVo> result = repairArticleTypeService.getRepairParentArticleTypes(schoolId);
        List<String> articleIds = Arrays.stream(StringUtils.join(result.stream().map(RepairArticleChildVo::getChildId).collect(Collectors.toList()), ',').split(",")).distinct().collect(Collectors.toList());
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < articleIds.size(); i++) {
            sb.append("FIND_IN_SET(" + articleIds.get(i) + ",article_id)");
            if (i + 1 != articleIds.size()) {
                sb.append(" or ");
            }
        }

        String sss = sb.toString();
        //耗材数据
        List<RepairArticleConsumeVo> consumeResult = repairConsumeService.queryArticleConsumes(schoolId, keyWord, sb.toString());
        for (RepairArticleChildVo article : result) {
            List<String> ids = new ArrayList<>(Arrays.asList(article.getChildId().split(",")));
            for (String id : ids) {
                List<RepairArticleConsumeVo> datas = consumeResult.stream().filter(e -> ("," + e.getArticleId() + ",").contains(("," + id + ","))).collect(Collectors.toList());
                if (datas.size() > 0) {
                    article.setConsumes(datas);
                }
            }
        }

        //判断获取子类的 按查询内容模糊查询获取
        return CommonResult.ok(result);
    }

    /**
     * 根据父级ID获取树形菜单数据
     *
     * @param parentID 父级ID
     * @param lists    数据集合
     * @return
     */
    private List<RepairArticleTypeTreeVo> QueryArticleTypeTreeRecords(Integer parentID, List<RepairArticleType> lists) {
        List<RepairArticleTypeTreeVo> newTrees = new ArrayList<>();

        List<RepairArticleType> datas = lists.stream().filter(e -> e.getParentId().equals(parentID)).sorted(Comparator.comparing(RepairArticleType::getOrderNum)).collect(Collectors.toList());

        for (RepairArticleType data : datas) {
            RepairArticleTypeTreeVo item = RepairArticleTypeTreeVo.builder()
                    .id(data.getId())
                    .schoolId(data.getSchoolId())
                    .parentId(data.getParentId())
                    .name(data.getName())
                    .orderNum(data.getOrderNum())
                    .build();
            List<RepairArticleTypeTreeVo> news = QueryArticleTypeTreeRecords(item.getId(), lists);
            if (news == null || news.size() == 0) {
                newTrees.add(item);
                continue;
            } else {
                news.sort(Comparator.comparing(RepairArticleTypeTreeVo::getOrderNum));
                item.setChildren(news);
                newTrees.add(item);
            }
        }

        return newTrees;
    }


    /**
     * 拖拽报修物品
     *
     * @return
     */
    @Override
    public CommonResult dragArticle(@RequestBody updateArticleNumRequest datas) {
        if(datas == null){
            return CommonResult.fail("参数不能为空");
        }

        if(datas.getArticles() == null){
            return CommonResult.fail("参数不能为空");
        }

        List<RepairArticleType> rats = new ArrayList<>();
        for (updateArticleDetailRequest data : datas.getArticles()) {
            RepairArticleType rat = new RepairArticleType();
            rat.setId(data.getId());
            rat.setOrderNum(data.getOrderNum());
            rats.add(rat);
        }

        boolean updateBatch = repairArticleTypeService.updateBatchArticle(rats);

        if(!updateBatch){
            return CommonResult.fail("拖拽失败");
        }

        return CommonResult.ok("拖拽成功");
    }
}

