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

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.dynamic.IDynamicFormService;
import com.cm.common.pojo.bos.DepartmentBO;
import com.cm.common.token.app.AppTokenManager;
import com.cm.common.token.app.entity.*;
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.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: DynamicFormAppRouteController
 * @Description: 动态表单APP
 * @Author: WangGeng
 * @Date: 2020/2/8 10:25 下午
 * @Version: 1.0
 **/
@Api(tags = ISystemConstant.API_TAGS_APP_ROUTE_PREFIX + "动态表单页面接口")
@Controller
@RequestMapping(ISystemConstant.APP_ROUTE_PREFIX + "/dynamicform")
public class DynamicFormAppRouteController {

    @Autowired
    private IDynamicFormService dynamicFormService;

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

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

        setCurrentUserIdAndNameValues(mv, token, dynamicFormFormShowFieldDTOs);
        return mv;
    }

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

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

    /**
     * 设置ID和名称值：当前用户、部门、角色、组、职位等
     *
     * @param mv
     */
    private void setCurrentUserIdAndNameValues(ModelAndView mv, String token, List<DynamicFormFormShowFieldDTO> dynamicFormFormShowFieldDTOs) {
        AppTokenUser appTokenUser = AppTokenManager.getInstance().getToken(token).getAppTokenUser();
        dynamicFormFormShowFieldDTOs.forEach(dynamicFormFormShowFieldDTO -> {
            if (StringUtils.equals(FieldTypeEnum.CURRENT_USER.getValue(), dynamicFormFormShowFieldDTO.getFieldType())) {
                mv.addObject("userIdAndValue", String.format("%s|%s", appTokenUser.getId(), appTokenUser.getName()));
                mv.addObject("userNameValue", appTokenUser.getName());
            } else if (StringUtils.equals(FieldTypeEnum.CURRENT_DEPARTMENT.getValue(), dynamicFormFormShowFieldDTO.getFieldType())) {
                List<AppTokenUserDepartment> appTokenUserDepartments = appTokenUser.getDepartments();
                StringBuilder idStringBuilder = new StringBuilder();
                StringBuilder nameStringBuilder = new StringBuilder();
                appTokenUserDepartments.forEach(appTokenUserPosition -> {
                    if (idStringBuilder.length() > 0) {
                        idStringBuilder.append(",");
                        nameStringBuilder.append(",");
                    }
                    idStringBuilder.append(appTokenUserPosition.getDepartmentId());
                    nameStringBuilder.append(appTokenUserPosition.getDepartmentName());
                });
                mv.addObject("departmentIdAndNamesValue", idStringBuilder.length() > 0 ? idStringBuilder.append("|").append(nameStringBuilder).toString() : "");
                mv.addObject("departmentNamesValue", nameStringBuilder.length() > 0 ? nameStringBuilder.toString() : "");
            } else if (StringUtils.equals(FieldTypeEnum.CURRENT_ROLE.getValue(), dynamicFormFormShowFieldDTO.getFieldType())) {
                List<AppTokenUserRole> appTokenUserRoles = appTokenUser.getRoles();
                StringBuilder idStringBuilder = new StringBuilder();
                StringBuilder nameStringBuilder = new StringBuilder();
                appTokenUserRoles.forEach(appTokenUserPosition -> {
                    if (idStringBuilder.length() > 0) {
                        idStringBuilder.append(",");
                        nameStringBuilder.append(",");
                    }
                    idStringBuilder.append(appTokenUserPosition.getRoleId());
                    nameStringBuilder.append(appTokenUserPosition.getRoleName());
                });
                mv.addObject("roleIdAndNamesValue", idStringBuilder.length() > 0 ? idStringBuilder.append("|").append(nameStringBuilder).toString() : "");
                mv.addObject("roleNamesValue", nameStringBuilder.length() > 0 ? nameStringBuilder.toString() : "");
            } else if (StringUtils.equals(FieldTypeEnum.CURRENT_GROUP.getValue(), dynamicFormFormShowFieldDTO.getFieldType())) {
                List<AppTokenUserGroup> appTokenUserGroups = appTokenUser.getGroups();
                StringBuilder idStringBuilder = new StringBuilder();
                StringBuilder nameStringBuilder = new StringBuilder();
                appTokenUserGroups.forEach(appTokenUserPosition -> {
                    if (idStringBuilder.length() > 0) {
                        idStringBuilder.append(",");
                        nameStringBuilder.append(",");
                    }
                    idStringBuilder.append(appTokenUserPosition.getGroupId());
                    nameStringBuilder.append(appTokenUserPosition.getGroupName());
                });
                mv.addObject("groupIdAndNamesValue", idStringBuilder.length() > 0 ? idStringBuilder.append("|").append(nameStringBuilder).toString() : "");
                mv.addObject("groupNamesValue", nameStringBuilder.length() > 0 ? nameStringBuilder.toString() : "");
            } else if (StringUtils.equals(FieldTypeEnum.CURRENT_POSITION.getValue(), dynamicFormFormShowFieldDTO.getFieldType())) {
                List<AppTokenUserPosition> appTokenUserPositions = appTokenUser.getPositions();
                StringBuilder idStringBuilder = new StringBuilder();
                StringBuilder nameStringBuilder = new StringBuilder();
                appTokenUserPositions.forEach(appTokenUserPosition -> {
                    if (idStringBuilder.length() > 0) {
                        idStringBuilder.append(",");
                        nameStringBuilder.append(",");
                    }
                    idStringBuilder.append(appTokenUserPosition.getPositionId());
                    nameStringBuilder.append(appTokenUserPosition.getPositionName());
                });
                mv.addObject("positionIdAndNamesValue", idStringBuilder.length() > 0 ? idStringBuilder.append("|").append(nameStringBuilder).toString() : "");
                mv.addObject("positionNamesValue", nameStringBuilder.length() > 0 ? nameStringBuilder.toString() : "");
            }
        });
    }

}
