package com.ywt.controllers.mg;

import com.google.protobuf.ByteString;
import com.ywt.gapi.base.file.FileServiceGrpc;
import com.ywt.gapi.base.file.UploadImageRequest;
import com.ywt.gapi.base.file.UploadImageResponse;
import com.ywt.mg.core.MGRight;
import com.ywt.mg.core.MGRightTypeDef;
import com.ywt.mg.core.utils.DateUtil;
import com.ywt.mg.core.utils.StringHelper;
import com.ywt.mg.domain.models.ConstantDef;
import com.ywt.mg.web.BaseResponse;
import com.ywt.mg.web.DataResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 文件服务接口
 */
@RestController("/mg/file")
@RequestMapping({"/mg/file"})
@MGRight
public class FileController {
    private static Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    FileServiceGrpc.FileServiceBlockingStub fileServiceBlockingStub;

    /**
     * 上传图片（通用）
     *
     * @param req
     * @return
     */
    @MGRight(menuCode = {"/image/upload"}, type = MGRightTypeDef.Logined)
    @RequestMapping({"/image/upload"})
    public BaseResponse uploadImage(
            @RequestParam(name = "type", required = false) Integer type,
            HttpServletRequest req) {
        DataResponse response = new DataResponse();
        String vPath;

        if (type == null) {
            type = 0;
        }
        switch (type) {
            case 1:
                //医生头像
                vPath = ConstantDef.DOCTOR_AVATAR_PATH;
                break;
            case 2:
                //患者病历图片存放路径、患者信息图片存放路径、咨询订单图片存放路径
                vPath = ConstantDef.PATIENT_HIS_PATH;
                break;
            case 3:
                //聊天存放路径
                vPath = ConstantDef.IM_IMAGE_PATH;
                break;

            case 4:
                //商品存放路径
                vPath = ConstantDef.GOODS_IMAGE_PATH;
                break;
            default:
                vPath = String.format("com/%s", DateUtil.formatDate(new Date(), "yyyyMMdd"));
                break;
        }

        try {
            //System.out.println("-------------------------------");
            Map<String, MultipartFile> files = ((MultipartHttpServletRequest) req).getFileMap();
            Pattern pattern = Pattern.compile("\\/(?:jpeg|png|gif|jpg)");
            for (MultipartFile sourceFile : files.values()) {
                System.out.println(sourceFile.getContentType());
                if (!pattern.matcher(sourceFile.getContentType()).find()) {
                    //System.out.println("not match");
                    response.setCode(BaseResponse.APP_ERROR).setInfo("格式不正确");
                    break;
                }
                //System.out.println(sourceFile.getName());
                byte[] img1 = sourceFile.getBytes();
                String img1Ext = sourceFile.getContentType().split("\\/")[1];
                //System.out.println("---------" + img1.length);
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

                UploadImageRequest uploadImageRequest = UploadImageRequest.newBuilder()
                        .setFilename(String.format("%s.%s", StringHelper.getUUIDWithoutHyphen(), img1Ext))
                        .setDatas(ByteString.copyFrom(img1))
                        .setVpath(vPath)
//                        .setVpath("com/" + sdf.format(new Date()))
                        .build();
                UploadImageResponse uploadImageResponse = fileServiceBlockingStub.uploadImage(uploadImageRequest);
                if (uploadImageResponse.getCode() == 0) {
                    Map<String, String> dataMap = new HashMap<>();
                    dataMap.put("realityUrl", uploadImageResponse.getRealityUrl());
                    dataMap.put("largeUrl", uploadImageResponse.getLargeUrl());
                    dataMap.put("thumbnailUrl", uploadImageResponse.getThumbnailUrl());
                    response.setData(dataMap);
                }
                break;
            }
            return response;
        } catch (Exception e) {
            logger.error("uploadImage(): {}", e.getMessage(), e);
            return response.failed(BaseResponse.APP_EXCEPTION);
        }
    }
}
