package com.keyware.shandan.control.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.keyware.shandan.dynacmicform.core.DynamicFormEventListener;
import com.keyware.shandan.dynacmicform.core.basic.entity.FormInfoPo;
import com.keyware.shandan.system.entity.SysMenu;
import com.keyware.shandan.system.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Component
@Transactional(rollbackFor = Exception.class, propagation = Propagation.SUPPORTS)
public class DynamicFormListener implements DynamicFormEventListener {

    @Autowired
    private SysMenuService menuService;

    @Override
    public void onSave(FormInfoPo form) throws Exception {
        SysMenu parentMenu = getDynamicDataManagerMenu();
        SysMenu menu = new SysMenu();
        menu.setMenuId(form.getId().toString());
        menu.setParentMenu(parentMenu);
        menu.setMenuParentId(parentMenu.getMenuId());
        menu.setMenuName(form.getFormName());
        menu.setMenuPath("/dynamic-data/view/data/list/" + form.getId());
        menu.setSystem(parentMenu.getSystem());
        menu.setMenuParentName(parentMenu.getMenuName());
        menu.setDeleted(false);
        menu.setSortWeight(0);
        menuService.updateOrSave(menu);
    }

    @Override
    public void onAlter(FormInfoPo form) {
        SysMenu menu = menuService.getById(form.getId().toString());
        menu.setMenuName(form.getFormName());
        menuService.saveOrUpdate(menu);
    }

    @Override
    public void onDrop(FormInfoPo form) {
        menuService.deleteById(form.getId().toString());
    }

    private SysMenu getDynamicDataManagerMenu(){
        QueryWrapper<SysMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("MENU_PATH", "/dynamic-data/view/data/list/");
        return menuService.getOne(wrapper);
    }
}
