package com.bweb.controller;

import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.utils.DateUtil;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.config.CommonSysConst;
import com.hfkj.entity.BsMer;
import com.hfkj.entity.BsMerPlatformNo;
import com.hfkj.model.ResponseData;
import com.hfkj.obs.HuaWeiYunObs;
import com.hfkj.service.BsMerPlatformNoService;
import com.hfkj.service.BsMerService;
import com.hfkj.sysenum.PlatformTypeEnum;
import com.obs.services.model.PutObjectResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Controller
@RequestMapping(value = "/merPlatformNo")
@Api(value = "商户平台号")
public class BsMerPlatformNoController {

    private static Logger log = LoggerFactory.getLogger(BsMerPlatformNoController.class);

    @Resource
    private BsMerService merService;

    @Resource
    private BsMerPlatformNoService merPlatformNoService;

    @RequestMapping(value = "/configMerPlatformNo", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "配置商户平台号")
    public ResponseData configMerPlatformNo(@RequestBody BsMerPlatformNo merPlatformNo, HttpServletRequest request) {
        try {

            if (merPlatformNo.getMerId() == null ||
                    merPlatformNo.getPlatformType() == null ||
                    StringUtils.isBlank(merPlatformNo.getPlatformNo())
            ) {
                log.error("BsMerPlatformNoController --> configMerPlatformNo() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            if (merPlatformNo.getPlatformType().equals(PlatformTypeEnum.type3.getNumber())) {
                if (StringUtils.isBlank(merPlatformNo.getPosId())
                    || StringUtils.isBlank(merPlatformNo.getBranchId())
                    || StringUtils.isBlank(merPlatformNo.getMerPublicKey())
                    || StringUtils.isBlank(merPlatformNo.getPlatformOperatorId())
                    || StringUtils.isBlank(merPlatformNo.getPlatformOperatorPwd())
                    || StringUtils.isBlank(merPlatformNo.getRefundCertUrl())
                    || StringUtils.isBlank(merPlatformNo.getRefundCertPwd())
                ) {
                    log.error("BsMerPlatformNoController --> configMerPlatformNo() error!", "参数错误");
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }
            }

            // 校验商户号
            BsMer mer = merService.getMer(merPlatformNo.getMerId());
            if (mer == null) {
                log.error("BsMerPlatformNoController --> configMerPlatformNo() error!", "未知的商户号");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的商户号");
            }

            BsMerPlatformNo platformNo = merPlatformNoService.getPlatformNo(mer.getId(), PlatformTypeEnum.getDataByNumber(merPlatformNo.getPlatformType()));
            if (platformNo == null) {
                platformNo = new BsMerPlatformNo();
                platformNo.setMerId(mer.getId());
                platformNo.setMerNo(mer.getMerNo());
                platformNo.setPlatformType(merPlatformNo.getPlatformType());
            }
            platformNo.setPlatformNo(merPlatformNo.getPlatformNo());
            platformNo.setCupNo(merPlatformNo.getCupNo());
            platformNo.setPosId(merPlatformNo.getPosId());
            platformNo.setBranchId(merPlatformNo.getBranchId());
            platformNo.setMerPublicKey(merPlatformNo.getMerPublicKey());
            platformNo.setPlatformOperatorId(merPlatformNo.getPlatformOperatorId());
            platformNo.setPlatformOperatorPwd(merPlatformNo.getPlatformOperatorPwd());
            platformNo.setRefundCertUrl(merPlatformNo.getRefundCertUrl());
            platformNo.setRefundCertPwd(merPlatformNo.getRefundCertPwd());
            merPlatformNoService.editMerPlatformNo(platformNo);

            return ResponseMsgUtil.success("操作成功");

        } catch (Exception e) {
            log.error("BsMerPlatformNoController --> configMerPlatformNo() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value = "/getMerPlatformNo", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询商户平台号")
    public ResponseData getMerPlatformNo(@RequestParam(value = "merId" , required = true) Long merId,
                                         @RequestParam(value = "platformType" , required = true) Integer platformType) {
        try {

            return ResponseMsgUtil.success(merPlatformNoService.getPlatformNo(merId, PlatformTypeEnum.getDataByNumber(platformType)));

        } catch (Exception e) {
            log.error("BsMerPlatformNoController --> getMerPlatformNo() error!", e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/uploadfile",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "文件上传")
    public ResponseData uploadFile(@RequestParam(value = "files" , required = false) MultipartFile files,
                                   @RequestParam(value = "platformType" , required = true) Integer platformType,
                                   HttpServletRequest request,
                                   HttpServletResponse response) throws Exception {
        try {
            response.setHeader("Access-Control-Allow-Origin", "*");
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                    request.getSession().getServletContext());
            // 判断 request 是否有文件上传,即多部分请求
            List<String> fileNames = new ArrayList<String>();
            if (multipartResolver.isMultipart(request)) {
                // 转换成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                Iterator<String> iterator = multiRequest.getFileNames();

                while (iterator.hasNext()) {
                    MultipartFile file = multiRequest.getFile(iterator.next());
                    if (file != null) {
                        FileOutputStream out = null;
                        try {
                            String fileType = file.getOriginalFilename()
                                    .substring(file.getOriginalFilename().lastIndexOf(".") + 1);
                            String fileName = System.currentTimeMillis() + "." + fileType;

                            String childPath = "";
                            if (platformType.equals(3)) {
                                childPath = "/ccb/cert/";
                            }

                            String destDirName = CommonSysConst.getSysConfig().getFile_url() + childPath;
                            File dir = new File(destDirName);
                            if (!dir.exists()) {
                                dir.mkdirs();
                            }
                            out = new FileOutputStream(destDirName + fileName);
                            out.write(file.getBytes());
                            out.flush();
                            fileNames.add(childPath + fileName);

                            File filePath = new File(destDirName  + fileName);
                            HuaWeiYunObs.putObject(CommonSysConst.getSysConfig().getObs_bucket_name(),
                                    "config" + childPath + fileName, filePath);

                        } catch (Exception e) {
                            log.error(e.getMessage(), e);
                        } finally {
                            if (out != null) {
                                out.close();
                            }
                        }
                    }
                }
            }
            return ResponseMsgUtil.success(fileNames);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

}
