package com.keyware.shandan.bianmu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.keyware.shandan.bianmu.entity.DataLabelsVo;
import com.keyware.shandan.bianmu.entity.DirectoryResource;
import com.keyware.shandan.bianmu.entity.FormLabelVo;
import com.keyware.shandan.bianmu.service.DataLabelsService;
import com.keyware.shandan.bianmu.utils.DataLabelsTreeUtil;
import com.keyware.shandan.common.controller.BaseController;
import com.keyware.shandan.common.entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * @author GuoXin
 * @date 2022-12-30
 */
@RestController
@RequestMapping("/data-label/manager")
public class DataLabelsController extends BaseController<DataLabelsService, DataLabelsVo, Integer> {

    @Autowired
    private DataLabelsService service;

    @GetMapping("/view/index")
    public ModelAndView index(ModelAndView mav) {
        mav.setViewName("business/datalabels/managerIndex");
        return mav;
    }

    @GetMapping("/api/tree/children")
    public Result<Object> treeChildren(@RequestParam(defaultValue = "0") Integer id) {
        DataLabelsVo param = DataLabelsVo.builder().parentId(id).isLabel(false).build();
        List<DataLabelsVo> children = commonService.list(new QueryWrapper<>(param));
        return Result.of(DataLabelsTreeUtil.parseTreeNode(children, "false"));
    }

    /**
     * 表单页选择标签弹窗全量查询标签树
     *
     * @param typeId 配置到表单的标签分类ID
     * @param id     父级标签节点ID
     * @return List
     */
    @GetMapping("/api/tree/choose")
    public Result<Object> treeAllChildren(@RequestParam(defaultValue = "0") Integer typeId,
                                          @RequestParam(required = false) Integer id) {
        QueryWrapper<DataLabelsVo> wrapper = new QueryWrapper<>();
        DataLabelsVo parent = new DataLabelsVo();
        if (id != null) {
            parent = service.getById(id);
        } else if (typeId != 0) {
            parent = service.getById(typeId);
            // 查询所有父级分类
            List<String> parentIds = new ArrayList<>(Arrays.asList(parent.getIdPath().split("/")));
            parentIds.add(String.valueOf(typeId));
            parentIds.remove("");
            wrapper.in("ID", parentIds);
        }
        if (parent.getIsLabel() != null && parent.getIsLabel()) {
            return Result.of(new ArrayList<>());
        }

        // 查询所有下级分类及标签
        wrapper.or().like("ID_PATH", parent.getIdPathWithSelf());

        List<DataLabelsVo> children = commonService.list(wrapper);
        return Result.of(DataLabelsTreeUtil.buildTree(children, 0));

    }

    /**
     * 批量删除置标标签数据
     *
     * @param ids id集合字符串，以“,”分隔
     * @return Object
     */
    @PostMapping("/api/delete")
    public Result<Object> deleteByIds(@RequestBody String ids) {
        return Result.of(commonService.removeByIds(Arrays.asList(ids.split(","))));
    }

    /**
     * 查询表单置标标签配置
     *
     * @return List
     */
    @GetMapping("/api/form-config/list")
    public Result<Object> formList() {
        return Result.of(service.formConfigList());
    }

    /**
     * 保存表单置标标签配置
     *
     * @param formLabel 配置实体
     * @return Object
     */
    @PostMapping("/api/form-config/save")
    public Result<Object> addToForm(FormLabelVo formLabel) {
        if (formLabel.getId() != null) {
            FormLabelVo oldData = service.getFormLabelById(formLabel.getId());
            oldData.setFieldTitle(formLabel.getFieldTitle());
            oldData.setFieldSort(formLabel.getFieldSort());
            return Result.of(service.updateFormLabel(oldData));
        } else {
            DataLabelsVo label = commonService.getById(formLabel.getLabelId());
            if (service.checkConfig(label, formLabel.getFieldTitle())) {
                service.addConfig(label, formLabel.getFieldTitle());
            }
            return Result.of(null);
        }
    }

    /**
     * 删除表单的置标标签配置
     *
     * @param id 配置ID
     * @return Object
     */
    @DeleteMapping("/api/form-config/delete/{id}")
    public Result<Object> formLabelDelete(@PathVariable String id) {
        return Result.of(service.deleteFormLabelById(Integer.valueOf(id)));
    }

    /**
     * 查询指定标签分类下的子级分类
     *
     * @param id 标签ID
     * @return 置标分类树
     */
    @GetMapping("/api/view/tree/children")
    public Result<Object> viewTreeChildren(@RequestParam(defaultValue = "0") Integer id, @RequestParam(defaultValue = "false") String checked) {
        DataLabelsVo param = DataLabelsVo.builder().parentId(id).build();
        List<DataLabelsVo> children = commonService.list(new QueryWrapper<>(param))
                .stream()
                // 将没有关联数据的标签分类过滤出去
                .filter(data -> service.countByLabelEntity(data) > 0)
                .collect(Collectors.toList());

        // 暂时取消根据父级状态选中自己节点
        checked = "false";
        return Result.of(DataLabelsTreeUtil.parseTreeNode(children, checked));
    }

    /**
     * 分页查询指定标签分类下已关联的目录资源数据
     *
     * @param page 分页对象
     * @param id   标签ID
     * @return 目录资源数据
     */
    @GetMapping("/api/view/data/page")
    public Result<Object> viewDataPage(Page<DirectoryResource> page,
                                       @RequestParam(defaultValue = "0") Integer id,
                                       @RequestParam(required = false) String resourceName,
                                       @RequestParam(required = false) String ids) {
        List<Integer> idList = new ArrayList<>();
        idList.add(id);
        if (StringUtils.hasText(ids)) {
            idList = Arrays.stream(ids.split(",")).map(Integer::valueOf).collect(Collectors.toList());
        }
        return Result.of(service.directoryResourcePageByDataLabel(page, resourceName, idList.toArray(new Integer[0])));
    }

}
