package com.bcxin.ars.rest.gx;

import com.bcxin.ars.dto.AjaxResult;
import com.bcxin.ars.dto.certificate.SecurityCerDto;
import com.bcxin.ars.dto.gx.RequestDto;
import com.bcxin.ars.service.certificate.SecurityCertificateService;
import com.bcxin.ars.service.gx.IntegratedService;
import com.bcxin.ars.service.gx.InternetPlusBusinessService;
import com.bcxin.ars.util.DateUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 广西公安互联网+平台推送流水号到业务办理系统
 *
 * @author subh
 * @see IntegratedService
 * @see LoggerFactory
 * @since jdk1.8
 */
@Controller
@RequestMapping("internetPlus")
public class InternetPlusController {
    /**
     * 日志
     */
    private final static Logger logger = LoggerFactory.getLogger(InternetPlusController.class);
    public static SimpleDateFormat systemDate = new SimpleDateFormat("yyyy-MM-dd");

    @Value("${upload-folder}")
    private String uploadFolder;
    /***
     * 一体化服务层
     */
    @Autowired
    private SecurityCertificateService securityCertificateService;

    @Autowired
    private InternetPlusBusinessService internetPlusBusinessService;

    @RequestMapping("sponsorlicense")
    public @ResponseBody
    AjaxResult sponsorlicense(@RequestBody RequestDto requestDto) throws Exception {
        try {
            return internetPlusBusinessService.saveSponsorlicense(requestDto);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return AjaxResult.error(e.getMessage());
        }
    }

    @RequestMapping("legalchange")
    public @ResponseBody
    AjaxResult legalchange(@RequestBody RequestDto requestDto) throws Exception {
        try {
            //若有加密 则需要先解密
            // AESUtil.decrypt(requestDto.getData(),"");
//            LegalchangeDto legalchange = JSON.parseObject(requestDto.getSdata(),LegalchangeDto.class);
//            legalchangeService.updateAndSaveWorkExperience(legalchange);
            return internetPlusBusinessService.saveLegalchange(requestDto);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return AjaxResult.error(e.getMessage());
        }
    }

    @RequestMapping("cer/search")
    public @ResponseBody
    AjaxResult cerSearch(@RequestBody RequestDto requestDto) throws Exception {
        try {
            //若有加密 则需要先解密
            // AESUtil.decrypt(requestDto.getSdata(),"");
            ObjectMapper objectMapper = new ObjectMapper();
            SecurityCerDto securityCerDto = objectMapper.convertValue(requestDto.getSdata(), SecurityCerDto.class);
            SecurityCerDto cer = securityCertificateService.findByIdNum(securityCerDto.getIdNum());

            return AjaxResult.success(cer);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return AjaxResult.error(e.getMessage());
        }
    }
    @RequestMapping("certificateVerification")
    public @ResponseBody
    AjaxResult certificateVerification(@RequestBody RequestDto requestDto) throws Exception {
        try {
            return internetPlusBusinessService.saveCertificateVerification(requestDto);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return AjaxResult.error(e.getMessage());
        }
    }
    /**
     * 上传文件
     * @param file
     * @return
     */
    @RequestMapping("uploadFile")
    public @ResponseBody AjaxResult uploadFile(MultipartFile file) throws Exception {
        AjaxResult result = new AjaxResult();
        try {
            Date now = new Date();
            String[] fileTypes = file.getOriginalFilename().split("\\.");
            String materialFileType = fileTypes[fileTypes.length-1]; //文件类型
            /***  上传的文件类型可能小写、可能大写、可能大小混合 by llc 2018-08-21 ***/
            String fileType = "ZIP,RAR,PDF,TXT,XML,DOC,GIF,PNG,BMP,JPEG,JPG,DOCX,XLS,XLSX,PPT,PPTX";
//			判断是否为允许上传的文件类型
            if ( !Arrays.<String> asList(fileType.split(",")).contains(materialFileType.toUpperCase()))
            {
                result.setSuccessful(false);
                result.setMsg("文件格式不对，重新上传！！");
                return result;
            }
            String fileName = now.getTime() +"."+ materialFileType;
            String dirDate = DateUtil.systemDate.format(now);
            File dir = new File(uploadFolder + dirDate);
            if(!dir.exists()) {
                dir.mkdirs();
            }
            String key = "upload/" + dirDate + "/" + fileName;
            String url = "getResource.do?path=" + key;
            String targetPath = uploadFolder + dirDate + "/" + fileName;
            File targetFile = new File(targetPath);
            logger.info("执行本地文件上传..." + targetFile);
            file.transferTo(targetFile);
            Map<String,String> map = new HashMap<String, String>();
            map.put("key", key);
            map.put("url", url);
            logger.info("本地文件上传成功!");
            result.setSuccessful(true);
            result.setData(map);
        } catch(Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        }
        return result;
    }
}
