package com.cm.common.plugin.controller.routes.dynamic;

import com.cm.common.base.AbstractController;
import com.cm.common.component.SecurityComponent;
import com.cm.common.constants.ISystemConstant;
import com.cm.common.plugin.enums.dynamic.FieldTypeEnum;
import com.cm.common.plugin.pojo.dtos.dynamic.DynamicFormFormShowFieldDTO;
import com.cm.common.plugin.service.datadictionary.IDataDictionaryService;
import com.cm.common.plugin.service.dynamic.IDynamicFormService;
import com.cm.common.pojo.bos.RoleBO;
import com.cm.common.pojo.bos.UserInfoBO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: DynamicFormRouteController
 * @Description: 动态表单
 * @Author: WangGeng
 * @Date: 2019/12/5 17:19
 * @Version: 1.0
 **/
@Api(tags = ISystemConstant.API_TAGS_SYSTEM_PREFIX + "动态表单页面接口")
@Controller
@RequestMapping(ISystemConstant.ROUTE_PREFIX + "/dynamicform")
public class DynamicFormRouteController extends AbstractController {

    @Autowired
    private IDynamicFormService dynamicFormService;
    @Autowired
    private SecurityComponent securityComponent;

    @ApiOperation(value = "动态表单新增页面", notes = "动态表单新增页面接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tableName", value = "表名", paramType = "path")
    })
    @GetMapping("savedynamicform/{tableName}")
    public ModelAndView saveDynamicForm(@PathVariable("tableName") String tableName) {
        ModelAndView mv = new ModelAndView("dynamic/form/save-dynamic-form");
        mv.addObject("tableName", tableName);

        List<DynamicFormFormShowFieldDTO> dynamicFormFormShowFieldDTOs = dynamicFormService.listFormShowFieldOfPage(tableName);
        mv.addObject("dynamicFormFormShowFieldDTOList", dynamicFormFormShowFieldDTOs);
        dynamicFormService.setDynamicFieldData(mv, dynamicFormFormShowFieldDTOs);
        setCurrentUserIdAndNameValues(mv, dynamicFormFormShowFieldDTOs);
        return mv;
    }

    @ApiOperation(value = "动态表单更新页面", notes = "动态表单列表更新接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tableName", value = "表名", paramType = "path"),
            @ApiImplicitParam(name = "uuidValue", value = "id值", paramType = "path")
    })
    @GetMapping("updatedynamicform/{tableName}/{uuidValue}")
    public ModelAndView updateDynamicForm(@PathVariable("tableName") String tableName, @PathVariable("uuidValue") String uuidValue) {
        ModelAndView mv = new ModelAndView("dynamic/form/update-dynamic-form");
        mv.addObject("tableName", tableName);
        mv.addObject("uuidValue", uuidValue);

        List<DynamicFormFormShowFieldDTO> dynamicFormFormShowFieldDTOs = dynamicFormService.listFormShowFieldOfPage(tableName);
        mv.addObject("dynamicFormFormShowFieldDTOList", dynamicFormFormShowFieldDTOs);
        dynamicFormService.setDynamicFieldData(mv, dynamicFormFormShowFieldDTOs);
        setCurrentUserIdAndNameValues(mv, dynamicFormFormShowFieldDTOs);
        return mv;
    }

    @ApiOperation(value = "动态表单更新（链接）页面", notes = "动态表单更新（链接）页面接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tableName", value = "表名", paramType = "path"),
            @ApiImplicitParam(name = "joinId", value = "链接id值", paramType = "path")
    })
    @GetMapping("updatedynamicjoinform/{tableName}/{joinKey}/{joinId}")
    public ModelAndView updateDynamicJoinForm(@PathVariable("tableName") String tableName, @PathVariable("joinKey") String joinKey, @PathVariable("joinId") String joinId) {
        ModelAndView mv = new ModelAndView("dynamic/form/update-dynamic-join-form");
        mv.addObject("tableName", tableName);
        mv.addObject("joinKey", joinKey);
        mv.addObject("joinId", joinId);

        List<DynamicFormFormShowFieldDTO> dynamicFormFormShowFieldDTOs = dynamicFormService.listFormShowFieldOfPage(tableName);
        mv.addObject("dynamicFormFormShowFieldDTOList", dynamicFormFormShowFieldDTOs);
        dynamicFormService.setDynamicFieldData(mv, dynamicFormFormShowFieldDTOs);
        return mv;
    }

    @ApiOperation(value = "动态表单列表页面", notes = "动态表单列表页面接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tableName", value = "表名", paramType = "path")
    })
    @GetMapping("listdynamicform/{tableName}")
    public ModelAndView listDynamicForm(@PathVariable("tableName") String tableName) {
        ModelAndView mv = new ModelAndView("dynamic/form/list-dynamic-form");
        mv.addObject("tableName", tableName);
        mv.addObject("uuidField", String.format("%sId", tableName));
        mv.addObject("dynamicListFormShowFieldDTOList", dynamicFormService.listListShowFieldOfPage(tableName));
        return mv;
    }

    /**
     * 设置ID和名称值：当前用户、部门、角色、组、职位等
     *
     * @param mv
     */
    private void setCurrentUserIdAndNameValues(ModelAndView mv, List<DynamicFormFormShowFieldDTO> dynamicFormFormShowFieldDTOs) {
        dynamicFormFormShowFieldDTOs.forEach(dynamicFormFormShowFieldDTO -> {
            if (StringUtils.equals(FieldTypeEnum.CURRENT_USER.getValue(), dynamicFormFormShowFieldDTO.getFieldType())) {
                mv.addObject("userIdAndValue", String.format("%s|%s", securityComponent.getCurrentUser().getUserId(), securityComponent.getCurrentUser().getUserName()));
                mv.addObject("userNameValue", securityComponent.getCurrentUser().getUserName());
            } else if (StringUtils.equals(FieldTypeEnum.CURRENT_DEPARTMENT.getValue(), dynamicFormFormShowFieldDTO.getFieldType())) {
                String departmentIdAndNamesValue = securityComponent.getCurrentUser().getDepartmentIdAndNamesValue();
                mv.addObject("departmentIdAndNamesValue", departmentIdAndNamesValue);
                mv.addObject("departmentNamesValue", departmentIdAndNamesValue.isEmpty() ? departmentIdAndNamesValue : departmentIdAndNamesValue.split("\\|")[1]);
            } else if (StringUtils.equals(FieldTypeEnum.CURRENT_ROLE.getValue(), dynamicFormFormShowFieldDTO.getFieldType())) {
                String roleIdAndNamesValue = securityComponent.getCurrentUser().getRoleIdAndNamesValue();
                mv.addObject("roleIdAndNamesValue", roleIdAndNamesValue);
                mv.addObject("roleNamesValue", roleIdAndNamesValue.isEmpty() ? roleIdAndNamesValue : roleIdAndNamesValue.split("\\|")[1]);
            } else if (StringUtils.equals(FieldTypeEnum.CURRENT_GROUP.getValue(), dynamicFormFormShowFieldDTO.getFieldType())) {
                String groupIdAndNamesValue = securityComponent.getCurrentUser().getGroupIdAndNamesValue();
                mv.addObject("groupIdAndNamesValue", groupIdAndNamesValue);
                mv.addObject("groupNamesValue", groupIdAndNamesValue.isEmpty() ? groupIdAndNamesValue : groupIdAndNamesValue.split("\\|")[1]);
            } else if (StringUtils.equals(FieldTypeEnum.CURRENT_POSITION.getValue(), dynamicFormFormShowFieldDTO.getFieldType())) {
                String positionIdAndNamesValue = securityComponent.getCurrentUser().getPositionIdAndNamesValue();
                mv.addObject("positionIdAndNamesValue", positionIdAndNamesValue);
                mv.addObject("positionNamesValue", positionIdAndNamesValue.isEmpty() ? positionIdAndNamesValue : positionIdAndNamesValue.split("\\|")[1]);
            }
        });
    }

}
