package com.bcxin.platform.web.controller.common;

import cn.hutool.json.JSONUtil;
import com.bcxin.platform.common.config.BMSConfig;
import com.bcxin.platform.common.config.ServerConfig;
import com.bcxin.platform.common.constant.Constants;
import com.bcxin.platform.common.core.domain.AjaxResult;
import com.bcxin.platform.common.exception.V5BusinessException;
import com.bcxin.platform.common.utils.Result;
import com.bcxin.platform.common.utils.StringUtils;
import com.bcxin.platform.common.utils.file.FileUploadUtils;
import com.bcxin.platform.common.utils.file.FileUtils;
import com.bcxin.platform.domain.company.ConfigIndustryDict;
import com.bcxin.platform.service.common.CommonService;
import com.bcxin.platform.util.CreateSecretKey;
import com.bcxin.platform.util.log.Log;
import com.bcxin.platform.web.controller.base.BaseController;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 通用请求处理
 * 
 * @author task
 */
@RestController
public class CommonController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private CommonService commonService;

    /**
     * 通用下载请求
     * 
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = BMSConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

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

    /**
     * 本地资源通用下载
     */
    @GetMapping("/common/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        try
        {
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = BMSConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }
    /**
     * 获取随机公钥
     *
     * @param req
     * @param resp
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/public/common/get/public_key")
    public Result getPublicKey(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        return Result.success("", CreateSecretKey.generateString(16));
    }


    /**
     * 获取银行配置
     *
     * @auth llc
     * @date 2019-04-16
     * @return
     * @throws Exception
     */
    @GetMapping("/public/common/get-config-bank-list")
    public Result getConfigBankList() throws Exception {
        return commonService.getConfigBankList().setBack(getRequest());
    }

    @PostMapping("/public/common/get-dict-by-code-types")
    @ResponseBody
    @ApiOperation(value="传入字典类型字符串数组", notes="economicType经济类型,comType公司类型,institutionType机构类型,industryType行业类型,fieldType字段类型")
    public Result getConfigDictById(String codeTypes) {
        return commonService.getConfigDictById(codeTypes).setBack(getRequest());
    }

    @GetMapping("/public/common/delete-redis-by-key")
    @ApiOperation(value="通过接口删除redisKey方便下次加载", notes="由于redisKey对应的value存在变动手动删除不方便")
    public Result deleteRedisByKey(String key) throws Exception {
        return commonService.deleteRedisByKey(key).setBack(getRequest());
    }

    @PostMapping("/public/common/get-institution-type-by-industry-type")
    @ApiOperation(value="从机构类型字典表获取", notes="根据行业类型获取机构")
    public Result getInstitutionTypeByIndustryType(String industryType) {
        logger.info(">>>>>>>>获得参数"+ JSONUtil.toJsonStr(industryType));
        return commonService.getInstitutionTypeByIndustryType(industryType).setBack(getRequest());
    }

    @PostMapping("/public/common/get-ins-projects")
    @ApiOperation(value="获得保障项目列表", notes="获得保障项目列表")
    public Result getInsProjects() {
        return commonService.getInsProjects().setBack(getRequest());
    }

    @PostMapping("/public/common/get-industry-dict-by-code-types")
    @ApiOperation(value="从业字典获取", notes="通过参数codeType获取从业相关类型")
    public Result getConfigIndustryDictByComId(ConfigIndustryDict cid) {
        return commonService.getConfigIndustryDictByComId(cid).setBack(getRequest());
    }
    /**
     * @Author: wangcy
     * @Description:发型验证码
     * @Date: 2017/12/20 0020 16:08
     */

    @Log(operation = Log.OPERA_TYPE_SAVE, modle = "平台信息管理", title = "发送验证码", systemType = Log.SYSTEMTYPE_BACKMANAGE)
    @PostMapping(value = "/public/common/send-verification-code")
    public Result sendVerificationCode(String mobile) {
        return commonService.sendVerificationCode(mobile).setBack(getRequest());
    }

    /**
     * @Author: wangcy
     * @Description:验证验证码
     * @Date: 2017/12/20 0020 19:18
     */
    @Log(operation = Log.OPERA_TYPE_SAVE, modle = "平台信息管理", title = "验证验证码", systemType = Log.SYSTEMTYPE_BACKMANAGE)
    @PostMapping(value = "/public/common/verification-code")
    public Result verificationCode(String mobile, String code)throws V5BusinessException {
        return commonService.verificationCode(mobile, code).setBack(getRequest());
    }
}
