package com.cm.common.plugin.controller.apis.dynamic.config.form;

import com.cm.common.annotation.CheckRequestBodyAnnotation;
import com.cm.common.base.AbstractController;
import com.cm.common.constants.ISystemConstant;
import com.cm.common.exception.SearchException;
import com.cm.common.plugin.enums.dynamic.FieldRequireTypeEnum;
import com.cm.common.plugin.enums.dynamic.FieldTypeEnum;
import com.cm.common.plugin.pojo.dtos.dynamic.config.form.DynamicConfigFormDTO;
import com.cm.common.plugin.pojo.vos.dynamic.config.form.DynamicConfigFormVO;
import com.cm.common.plugin.pojo.vos.dynamic.config.form.FieldShowVO;
import com.cm.common.plugin.service.dynamic.config.form.IDynamicConfigFormService;
import com.cm.common.pojo.ListPage;
import com.cm.common.result.ErrorResult;
import com.cm.common.result.SuccessResult;
import com.cm.common.result.SuccessResultList;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: DynamicConfigFormController
 * @Description: 动态配置-表单
 * @Author: WangGeng
 * @Date: 2019/12/7 5:55 下午
 * @Version: 1.0
 **/
@RestController
@RequestMapping(ISystemConstant.API_PREFIX + "/dynamicconfigtable/dynamicconfigform")
public class DynamicConfigFormController extends AbstractController {

    @Autowired
    private IDynamicConfigFormService dynamicConfigFormService;

    @ApiOperation(value = "表单新增", notes = "表单新增接口")
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PostMapping("saveform")
    @CheckRequestBodyAnnotation
    public SuccessResult saveForm(@RequestBody DynamicConfigFormVO dynamicConfigFormVO) throws Exception {
        restVerifyConfig(dynamicConfigFormVO);
        restJoinTableConfig(dynamicConfigFormVO);
        return dynamicConfigFormService.saveForm(dynamicConfigFormVO);
    }

    @ApiOperation(value = "表单删除", notes = "通过id列表单批量删除表单接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "表单ID列表单，用下划线分隔", paramType = "path", example = "1_2_3")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @DeleteMapping("removeform/{ids}")
    public SuccessResult removeForm(@PathVariable("ids") String ids) {
        return dynamicConfigFormService.removeForm(ids);
    }

    @ApiOperation(value = "表单修改", notes = "表单修改接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "表单ID", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PutMapping("updateform/{id}")
    @CheckRequestBodyAnnotation
    public SuccessResult updateForm(@PathVariable("id") String id, @RequestBody DynamicConfigFormVO dynamicConfigFormVO) throws Exception {
        restVerifyConfig(dynamicConfigFormVO);
        restJoinTableConfig(dynamicConfigFormVO);
        return dynamicConfigFormService.updateForm(id, dynamicConfigFormVO);
    }

    /**
     * 初始化验证字段
     *
     * @param dynamicConfigFormVO
     */
    private void restVerifyConfig(DynamicConfigFormVO dynamicConfigFormVO) {
        if (!StringUtils.equals(FieldTypeEnum.STRING.getValue(), dynamicConfigFormVO.getFieldType())) {
            dynamicConfigFormVO.setVerifyType(null);
            dynamicConfigFormVO.setVerifyRegular(null);
            return;
        }
        if (!StringUtils.equals(FieldRequireTypeEnum.CUSTOM.getValue(), dynamicConfigFormVO.getVerifyType())) {
            dynamicConfigFormVO.setVerifyRegular(null);
        }
    }

    /**
     * 初始化联表字段
     *
     * @param dynamicConfigFormVO
     */
    private void restJoinTableConfig(DynamicConfigFormVO dynamicConfigFormVO) {
        boolean isJoin = StringUtils.equals(FieldTypeEnum.INNER_JOIN.getValue(), dynamicConfigFormVO.getFieldType())
                || StringUtils.equals(FieldTypeEnum.LEFT_JOIN.getValue(), dynamicConfigFormVO.getFieldType())
                || StringUtils.equals(FieldTypeEnum.RIGHT_JOIN.getValue(), dynamicConfigFormVO.getFieldType());
        if (!isJoin) {
            dynamicConfigFormVO.setJoinTable(null);
            dynamicConfigFormVO.setJoinTableField(null);
            dynamicConfigFormVO.setJoinTableListShow(null);
            dynamicConfigFormVO.setJoinTableFormShow(null);
            dynamicConfigFormVO.setJoinTableSort(1);
        }
    }

    @ApiOperation(value = "字段列表显示修改", notes = "字段列表显示修改接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "表单ID", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PutMapping("updatefieldlistshow/{id}")
    @CheckRequestBodyAnnotation
    public SuccessResult updateFieldListShow(@PathVariable("id") String id, @RequestBody FieldShowVO fieldShowVO) {
        return dynamicConfigFormService.updateFieldListShow(id, fieldShowVO);
    }

    @ApiOperation(value = "字段表单显示修改", notes = "字段表单显示修改接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "表单ID", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @PutMapping("updatefieldformshow/{id}")
    @CheckRequestBodyAnnotation
    public SuccessResult updateFieldFormShow(@PathVariable("id") String id, @RequestBody FieldShowVO fieldShowVO) {
        return dynamicConfigFormService.updateFieldFormShow(id, fieldShowVO);
    }

    @ApiOperation(value = "表单详情（ID查询）", notes = "表单详情（ID查询）接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dictionaryId", value = "表单ID", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("getformbyid/{id}")
    public DynamicConfigFormDTO getFormById(@PathVariable("id") String id) {
        return dynamicConfigFormService.getFormById(id);
    }

    @ApiOperation(value = "表单全部列表单", notes = "表单全部列表单接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dictionaryParentId", value = "表单上级ID", paramType = "path")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("listform/{tableName}")
    public List<DynamicConfigFormDTO> listForm(@PathVariable("tableName") String tableName) throws SearchException {
        Map<String, Object> params = requestParams();
        params.put("tableName", tableName);
        return dynamicConfigFormService.listForm(params);
    }

    @ApiOperation(value = "分页表单列表单", notes = "分页表单列表单接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "query", dataType = "int", defaultValue = "1"),
            @ApiImplicitParam(name = "rows", value = "显示数量", paramType = "query", dataType = "int", defaultValue = "20"),
            @ApiImplicitParam(name = "keywords", value = "关键字", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "query", dataType = "String")
    })
    @ApiResponses({@ApiResponse(code = 400, message = "请求失败", response = ErrorResult.class)})
    @GetMapping("listpageform/{tableName}")
    public SuccessResultList<List<DynamicConfigFormDTO>> listPageForm(@PathVariable("tableName") String tableName, ListPage page) {
        Map<String, Object> params = requestParams();
        params.put("tableName", tableName);
        page.setParams(params);
        return dynamicConfigFormService.listPageForm(page);
    }

}
