package com.ximai.mes.md.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ximai.common.annotation.Log;
import com.ximai.common.constant.UserConstants;
import com.ximai.common.core.controller.BaseController;
import com.ximai.common.core.domain.AjaxResult;
import com.ximai.common.core.domain.entity.MdItemType;
import com.ximai.common.enums.BusinessType;
import com.ximai.mes.md.service.IItemTypeService;
import com.ximai.mes.md.vo.MdItemTypeVo;
import com.ximai.system.strategy.AutoCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/mes/md/itemtype")
public class MdItemTypeController extends BaseController {

    @Autowired
    private IItemTypeService iItemTypeService;
    @Autowired
    private AutoCodeUtil autoCodeUtil;

    /**
     * 查询分类列表
     *
     * @param mdItemType
     * @return
     */
    @GetMapping("/list")
    public AjaxResult list(MdItemType mdItemType) {
        List<MdItemType> list = iItemTypeService.selectItemTypeList(mdItemType);
        return AjaxResult.success(list);
    }


    /**
     * 查询分类列表
     *
     * @param mdItemType
     * @return
     */
    @GetMapping("/listLevelClass")
    public AjaxResult listLevelClass(MdItemType mdItemType) {
        List<MdItemType> list = iItemTypeService.selectItemTypeList(mdItemType);
        List<MdItemType> resultList = null;
        if (mdItemType.getLevel() == 1) {
            resultList = list.stream().filter(x -> x.getAncestors().split(",").length == 1).collect(Collectors.toList());
        } else if (mdItemType.getLevel() == 2) {
            resultList = list.stream().filter(x -> x.getAncestors().split(",").length == 2).collect(Collectors.toList());
        } else if (mdItemType.getLevel() == 3) {
            resultList = list.stream().filter(x -> x.getAncestors().split(",").length == 3).collect(Collectors.toList());
        } else {
            resultList = list;
        }

        return AjaxResult.success(resultList);
    }

    /**
     * 查询部门列表（排除当前和父节点）
     *
     * @param itemTypeId
     * @return
     */
    @GetMapping("/list/exclude/{itemTypeId}")
    public AjaxResult excludeChild(@PathVariable(value = "itemTypeId", required = false) Long itemTypeId) {
        List<MdItemType> list = iItemTypeService.selectItemTypeList(new MdItemType());
        Iterator<MdItemType> it = list.iterator();
        Long parentTypeId = 0L;
        while (it.hasNext()) {
            MdItemType mdItemType = (MdItemType) it.next();
            if (mdItemType.getItemTypeId() == itemTypeId) {
                parentTypeId = mdItemType.getParentTypeId();
                it.remove();
            }

            if (mdItemType.getItemTypeId() == parentTypeId) {
                it.remove();
            }
        }
        return AjaxResult.success(list);
    }

    /**
     * 查询部门详情
     *
     * @param itemTypeId
     * @return
     */
    @PreAuthorize("@ss.hasPermi('mes:md:itemtype:query')")
    @GetMapping(value = "/{itemTypeId}")
    public AjaxResult getInfo(@PathVariable Long itemTypeId) {
        //权限校验?
        return AjaxResult.success(iItemTypeService.selectItemTypeById(itemTypeId));
    }

    /**
     * 获取树形结构数据
     *
     * @param mdItemType
     * @return
     */
    @GetMapping("/treeselect")
    public AjaxResult treeSelect(MdItemType mdItemType) {
        List<MdItemType> list = iItemTypeService.selectItemTypeList(mdItemType);
        return AjaxResult.success(iItemTypeService.buildTreeSelect(list));
    }


    @PreAuthorize("@ss.hasPermi('mes:md:itemtype:add')")
    @Log(title = "新增物料产品分类信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody MdItemType mdItemType) {

        if (UserConstants.NOT_UNIQUE.equals(iItemTypeService.checkItemTypeCodeUnique(mdItemType))) {
            return AjaxResult.error("分类" + mdItemType.getItemTypeCode() + "编码已存在");
        }
        if (UserConstants.NOT_UNIQUE.equals(iItemTypeService.checkItemTypeNameUnique(mdItemType))) {
            return AjaxResult.error("分类" + mdItemType.getItemTypeCode() + "名称已存在");
        }
        if (mdItemType.getParentTypeId() == null || mdItemType.getParentTypeId() == 0) {
            mdItemType.setParentTypeId(0L);
        }
        //自动生成一个唯一编码
        mdItemType.setItemTypeCode(autoCodeUtil.genSerialCode(UserConstants.ITEM_TYPE_CODE, null));
        mdItemType.setCreateBy(getUsername());
        return AjaxResult.success(iItemTypeService.insertItemType(mdItemType));
    }

    @PreAuthorize("@ss.hasPermi('mes:md:itemtype:update')")
    @Log(title = "更新物料产品分类", businessType = BusinessType.UPDATE)
    @PutMapping//@Validated
    public AjaxResult update( @RequestBody MdItemType mdItemType) {
        if (UserConstants.NOT_UNIQUE.equals(iItemTypeService.checkItemTypeCodeUnique(mdItemType))) {
            return AjaxResult.error("分类" + mdItemType.getItemTypeCode() + "编码已存在");
        }
        if (UserConstants.NOT_UNIQUE.equals(iItemTypeService.checkItemTypeNameUnique(mdItemType))) {
            return AjaxResult.error("分类" + mdItemType.getItemTypeCode() + "名称已存在");
        }
        mdItemType.setUpdateBy(getUsername());
        return AjaxResult.success(iItemTypeService.updateItemType(mdItemType));
    }

    @PreAuthorize("@ss.hasPermi('mes:md:itemtype:remove')")
    @Log(title = "删除物料产品分类", businessType = BusinessType.DELETE)
    @DeleteMapping("/{itemTypeId}")
    public AjaxResult del(@PathVariable Long itemTypeId) {

        if (iItemTypeService.checkHasChild(itemTypeId)) {
            return AjaxResult.error("分类下有子分类，请先删除子分类");
        }

        if (iItemTypeService.checkHasItem(itemTypeId)) {
            return AjaxResult.error("分类下有物料，请先删除物料");
        }

        //权限数据检查？
        return AjaxResult.success(iItemTypeService.removeItemType(itemTypeId));
    }


}
