
package com.lideeyunji.core.framework.controller;

import cn.hutool.core.date.DateUtil;
import com.lideeyunji.tool.framework.common.constant.lideeYunJiBaseConstant;
import com.lideeyunji.core.framework.entity.DesformEntity;
import com.lideeyunji.core.framework.params.DesFormAddOrUpdateParam;
import com.lideeyunji.core.framework.params.PageDesFormParam;
import com.lideeyunji.core.framework.service.IDesFormService;
import com.lideeyunji.core.framework.utils.Func;
import com.lideeyunji.core.framework.utils.FuncWeb;
import com.lideeyunji.tool.framework.constants.FrameErrorCodeConstants;
import com.lideeyunji.tool.framework.yunji.adapter.IlideeYunjiAdapter;
import com.lideeyunji.tool.framework.yunji.annotation.ApiDecryptAes;
import com.lideeyunji.tool.framework.yunji.annotation.ApiEncryptAes;
import com.lideeyunji.tool.framework.yunji.constant.lideeYunjiCodeConstant;
import com.lideeyunji.tool.framework.yunji.constant.lideeRedisConstants;
import com.lideeyunji.tool.framework.yunji.component.redis.lideeYunjiRedisUtils;
import com.lideeyunji.tool.framework.yunji.enums.YNEnum;
import com.lideeyunji.tool.framework.yunji.utils.FuncBase;
import com.lideeyunji.tool.framework.yunji.model.global.BaseWebResult;
import com.lideeyunji.core.framework.params.vo.DesformEntityVo;
import com.lideeyunji.core.framework.params.vo.PageVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Tag(name = "低代码框架-表单设计器接口")
@RestController
@AllArgsConstructor
@RequestMapping( lideeYunJiBaseConstant.REQUEST_URL_START+"/desform")
public class DesFormController extends BaseController {

    private final IDesFormService desFormService;

    private final lideeYunjiRedisUtils lideeYunjiRedisUtils;

    private final IlideeYunjiAdapter adapter;


    @PostMapping("/unlock/{desFormId}")
    @ApiOperationSupport(order = 1)
    @Operation(tags = "自定义表单",summary = "表单设计增强-解锁")
    public BaseWebResult unlock(@PathVariable("desFormId") Long desFormId) {
        String redisKey = String.format(lideeRedisConstants.ENHANCE_DESFORM_LOCK,String.valueOf(desFormId));
        if (lideeYunjiRedisUtils.hasKey(redisKey)) {
            lideeYunjiRedisUtils.del(redisKey);
        }
        return BaseWebResult.success("成功");
    }

    @PreAuthorize("@ss.hasPermission('lideeyunji:desform:create')")
    @ApiDecryptAes//解密
    @PostMapping("/save")
    @ApiOperationSupport(order = 1)
    @Operation(tags = "自定义表单",summary = "表单设计器 - 保存")
    public BaseWebResult saveDesForm(@RequestBody DesFormAddOrUpdateParam param) {
        param.setIsHide(YNEnum.N.getCode());
        Long id = desFormService.saveDesForm(param);
        return BaseWebResult.success(id);
    }

    @PreAuthorize("@ss.hasPermission('lideeyunji:desform:update')")
    @ApiDecryptAes//解密
    @PutMapping("/update")
    @ApiOperationSupport(order = 2)
    @Operation(tags = "自定义表单",summary = "表单设计器 - 修改")
    public BaseWebResult updateDesForm(@RequestBody DesFormAddOrUpdateParam param) {
        desFormService.updateDesForm(param);
        return BaseWebResult.success("成功");
    }

    @PreAuthorize("@ss.hasPermission('lideeyunji:desform:delete')")
    @DeleteMapping("/delete")
    @ApiOperationSupport(order = 3)
    @Operation(tags = "自定义表单",summary = "表单设计器 - 删除")
    public BaseWebResult delDesForm(@RequestBody List<Long> ids) {
        desFormService.removeByIds(ids);
        return BaseWebResult.success("成功");
    }

    //返回数据加密
    @ApiEncryptAes
    @GetMapping("/detail")
    @ApiOperationSupport(order = 4)
    @Operation(tags = "自定义表单",summary = "表单设计器 - 获取详情")
    public BaseWebResult getDetailDesForm(Long desFormId,String lock) {
        if (FuncBase.isNotEmpty(lock) && FuncBase.equals(lock, "true")) {
            String redisKey = String.format(lideeRedisConstants.ENHANCE_DESFORM_LOCK,String.valueOf(desFormId));
            if (lideeYunjiRedisUtils.hasKey(redisKey)) {
                String lockMapStr = (String) lideeYunjiRedisUtils.get(redisKey);
                Map lockMap = Func.json2Bean(lockMapStr, Map.class);
                //返回锁定信息
                return BaseWebResult.error(FrameErrorCodeConstants.FRAME_ENHANCE_ERROR,lockMap);
            }

            String userName = adapter.getOnlineUserName();
            String timeStr = DateUtil.now();
            //存储锁定信息
            Map<String,Object> lockMap=new HashMap<>();
            lockMap.put("userName",userName);
            lockMap.put("timeStr",timeStr);
            lideeYunjiRedisUtils.set(redisKey, Func.json2Str(lockMap));//上锁
        }

        DesformEntity desformEntity = desFormService.getById(desFormId);
        return BaseWebResult.success(desformEntity);
    }

    @PostMapping("/page")
    @ApiOperationSupport(order = 6)
    @Operation(tags = "自定义表单",summary = "获取列表")
    public BaseWebResult page(PageDesFormParam param, PageVo pageVo) {

        LambdaQueryWrapper<DesformEntity> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(FuncBase.isNotEmpty(param.getId()),DesformEntity::getId,param.getId());
        wrapper.eq(FuncBase.isNotEmpty(param.getGroupDesformId()),DesformEntity::getGroupDesformId,param.getGroupDesformId());
        wrapper.eq(FuncBase.isNotEmpty(param.getIsOpen()), DesformEntity::getIsOpen, param.getIsOpen());
        wrapper.eq(FuncBase.isNotEmpty(param.getIsTemplate()), DesformEntity::getIsTemplate, param.getIsTemplate());
        wrapper.and(subWrapper->{
            subWrapper.ne(DesformEntity::getIsHide, YNEnum.Y.getCode()).or()
                    .isNull(DesformEntity::getIsHide);
        } );
        wrapper.like(FuncBase.isNotEmpty(param.getDesformName()),DesformEntity::getDesformName,param.getDesformName());
        wrapper.orderByDesc(DesformEntity::getId);

        IPage<DesformEntityVo> resultList=new Page<>();
        if(Func.isEmpty(pageVo) || Func.isEmpty(pageVo.getPageSize()) || Func.equals(lideeYunjiCodeConstant.NOT_PAGE,pageVo.getPageSize())){
            List<DesformEntity> dataList = desFormService.list(wrapper);
            resultList.setRecords(toVoBean(dataList, DesformEntityVo.class));
            resultList.setTotal(dataList.size());
            resultList.setCurrent(1L);
            resultList.setPages(1L);
            resultList.setSize(lideeYunjiCodeConstant.NOT_PAGE);
        }else{
            Page page = FuncWeb.getPage(pageVo.getPageNo(), pageVo.getPageSize());
            IPage<DesformEntity> pages = desFormService.page(page, wrapper);
            resultList = toVoBean(pages, DesformEntityVo.class);
        }

        return BaseWebResult.success(resultList);
    }



    @GetMapping("/get/template")
    @ApiOperationSupport(order = 6)
    @Operation(tags = "自定义表单",summary = "获取模板")
    public BaseWebResult getTemplate() {
        LambdaQueryWrapper<DesformEntity> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(DesformEntity::getIsTemplate, YNEnum.Y.getCode());
        List<DesformEntity> templateList = desFormService.list(wrapper);
        return BaseWebResult.success(templateList);
    }

}
