package com.dgtly.api.controller;

import com.dgtly.common.annotation.ApiNoCheckSign;
import com.dgtly.common.annotation.ApiPassToken;
import com.dgtly.common.config.Global;
import com.dgtly.common.config.ServerConfig;
import com.dgtly.common.core.controller.ApiBaseController;
import com.dgtly.common.core.domain.AjaxResult;
import com.dgtly.common.core.domain.ParameterObject;
import com.dgtly.common.core.domain.ResultType;
import com.dgtly.common.utils.file.FileUploadUtils;
import com.dgtly.system.service.ISysDictDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;


/**
 * 通用请求处理
 * 
 * @author dgtly
 */
@Api(tags = "常用API")
@ApiNoCheckSign
@ApiPassToken
@RestController()
@RequestMapping("/common")
public class CommonController extends ApiBaseController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private ISysDictDataService sysDictDataService;


    @ApiOperation(value = "获取字典")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body"),
    })
    @PostMapping("/dict")
    public Object getDict(){
        ParameterObject obj = getParameterObject();
        obj.checkParameterNotNull("dictType");
        String dictType = obj.getString("dictType");
        return AjaxResult.success().putKV("list", sysDictDataService.selectSimpleDictDataByType(dictType));
    }


    /**
     * 通用上传请求
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception{
        try
        {
            // 上传文件路径
            String filePath = Global.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.putKV("fileName", fileName);
            ajax.putKV("url", url);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    @ApiOperation(value = "获取全局异常")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "params" , paramType = "body"),
    })
    @PostMapping("/globalException")
    public Object globalException(){
        List<String> res = new ArrayList<>();
        for(ResultType r :ResultType.values()){
            String s = "错误代码："+r.value()+"---错误信息："+r.msg();
            res.add(s);
        }
        return AjaxResult.success().putKV("list", res);
    }



}
