package com.sw.mes.yb.spc.app.controller;

import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.response.ResponsePage;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.core.utils.BeanUtil;
import com.sw.mes.core.utils.DynamicSpecifications;
import com.sw.mes.core.utils.PageUtil;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.yb.spc.app.dto.AppPermissionDto;
import com.sw.mes.yb.spc.app.entity.AppPermission;
import com.sw.mes.yb.spc.app.service.AppPermissionService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/spc/AppPermission")
@Slf4j
@Api(description = "安卓端spc权限接口")
public class AppPermissionController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private AppPermissionService appPermissionService;


    @ApiOperation(value = "分页查询安卓端spc权限列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),
    })
    @GetMapping("/listByPage")
    public Result<ResponsePage<AppPermissionDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<AppPermission> specification = DynamicSpecifications.bySearchFilter(request, AppPermission.class);
        Page<AppPermission> page = appPermissionService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<AppPermissionDto> dtos = page.getContent().stream()
                .map(entity -> toLazyDto(entity))
                .collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "获取所有安卓端spc权限")
    @GetMapping("/listAll")
    public Result<List<AppPermissionDto>> listAll(ServletRequest request) {
        Specification<AppPermission> specification = DynamicSpecifications.bySearchFilter(request, AppPermission.class);
        List<AppPermission> appPermissions = appPermissionService.findByExampleSort(specification, null);
        List<AppPermissionDto> appPermissionDtos = appPermissions.stream()
                .map(appPermission -> toLazyDto(appPermission))
                .collect(Collectors.toList());
        return ResultGenerator.success(appPermissionDtos);
    }

    @ApiOperation(value = "安卓端spc权限详细信息")
    @GetMapping("/{id}")
    public Result<AppPermissionDto> get(@PathVariable @ApiParam(value = "安卓端spc权限id") Integer id) {
        AppPermission appPermission = appPermissionService.get(id);
        if (null == appPermission) {
            return ResultGenerator.fail("该安卓端spc权限不存在");
        }
        return ResultGenerator.success(toEagerDto(appPermission));
    }

    @ApiOperation(value = "创建安卓端spc权限")
    @PostMapping("/create")
    public Result create(@RequestBody @Valid @ApiParam(value = "安卓端spc权限对象") AppPermissionDto appPermissionDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        AppPermission appPermission = fromDto(appPermissionDto);
        AppPermission appPermission1 = appPermissionService.findByRoleIdAndPermissionAndModuleNameAndType(appPermission.getRoleId(),
                appPermission.getPermission(), appPermission.getModuleName(), appPermission.getType());
        if (null != appPermission1) {
            appPermission.setId(appPermission1.getId());
        }
        appPermission.setUser(BaseContextHandler.getUsername());
        appPermission.setCreateTime(new Date());
        appPermissionService.saveOrUpdate(appPermission);
        return ResultGenerator.success();
    }

    @ApiOperation(value = "远程安卓端spc权限信息")
    @GetMapping("/getAppPermissionDto")
    public Result<Map<String, String>> getAppPermissionDto(HttpServletRequest request, String moduleName, Integer type) {
        if (StringUtils.isBlank(moduleName)) {
            return ResultGenerator.fail("模块名不能为空");
        }
        Map<String, String> map = appPermissionService.getAppPermissionDto(request, moduleName, type);
        return ResultGenerator.success(map);
    }

    @ApiOperation(value = "更新安卓端spc权限")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "安卓端spc权限") AppPermissionDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        AppPermission entity = appPermissionService.get(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            AppPermission entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            entityfromFto.setUser(BaseContextHandler.getUsername());
            entityfromFto.setCreateTime(new Date());
            appPermissionService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "删除安卓端spc权限")
    @PostMapping("/delete")
    public Result remove(@ApiParam(value = "id", type = "query") @RequestParam Integer id) {
        appPermissionService.delete(id);
        return ResultGenerator.success();
    }

    public AppPermissionDto toLazyDto(AppPermission entity) {
        return modelMapper.map(entity, AppPermissionDto.class);
    }

    public AppPermissionDto toEagerDto(AppPermission entity) {
        AppPermissionDto dto = modelMapper.map(entity, AppPermissionDto.class);
        return dto;
    }

    public AppPermission fromDto(AppPermissionDto dto) {
        return modelMapper.map(dto, AppPermission.class);
    }


}
