package org.springblade.flow.visual.base.controller;


import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.tool.api.R;
import org.springblade.flow.visual.base.entity.VisualdevDataPermission;
import org.springblade.flow.visual.base.service.impl.VisualdevDataPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Base64;
import java.util.Date;
import java.util.List;

@Api(tags = "表单操作权限接口", value = "dataPerm")
@RestController
@RequestMapping("/paas/visualdev/dataPerm")
public class VisualdevDataPermController extends BladeController {

    @Autowired
    private VisualdevDataPermissionService dataPermissionService;

    /**
     * @return
     */
    @GetMapping("/list")
    @ApiOperation(value = "根据表单ID查询列表")
    public R<List<VisualdevDataPermission>> list(@RequestParam String visualdevId){
        return R.data(dataPermissionService.list(Wrappers.<VisualdevDataPermission>lambdaQuery().eq(VisualdevDataPermission::getVisualdevId, visualdevId)));
    }

    /**
     *
     * @return
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除数据")
    public R<String> delete(@RequestParam Integer visualdevPermId){
        return R.status(dataPermissionService.removeById(visualdevPermId));
    }

    /**
     *
     * @return
     */
    @PostMapping("/submit")
    @ApiOperation(value = "添加或修改一个表单操作权限", notes = "添加或修改一个表单操作权限")
    public R<String> doSubmit(@RequestBody String value) throws Exception{
        String decoderStr = new String(Base64.getDecoder().decode(value), "utf-8");
        VisualdevDataPermission dataPermission = JSON.parseObject(decoderStr, VisualdevDataPermission.class);
        if(dataPermission.getId() == null) {
            //查重
            VisualdevDataPermission visualdevDataPermission=dataPermissionService.getOne(Wrappers.<VisualdevDataPermission>lambdaQuery().eq(VisualdevDataPermission::getVisualdevId, dataPermission.getVisualdevId()).eq(VisualdevDataPermission::getDataPermId,dataPermission.getDataPermId()));
            if (visualdevDataPermission== null){
                dataPermission.setCreateUserId(getUser().getUserId());
                dataPermission.setCreateTime(new Date());
            }else {
                return R.fail("该权限组已设置，请勿重复设置!");
            }

        }
        return R.status(dataPermissionService.saveOrUpdate(dataPermission));
    }




}
