package com.softwarebr.nunu.web.api;

import com.aliyun.oss.model.PutObjectResult;
import com.brframework.commonoss.core.AliYunOSSClient;
import com.brframework.commonweb.json.JSONResult;
import com.google.common.collect.Lists;
import com.softwarebr.nunu.config.domain.ConfigService;
import com.softwarebr.nunu.domain.AgreementConfig;
import com.softwarebr.nunu.domain.ServiceTerms;
import com.softwarebr.nunu.entity.oper.Advertisement;
import com.softwarebr.nunu.entity.oper.Area;
import com.softwarebr.nunu.json.api.FileUriResult;
import com.softwarebr.nunu.service.oper.AdvertisementService;
import com.softwarebr.nunu.service.oper.AreaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @date 2020-02-18 10:58:32
 * @author lilin
 */

@RestController
@Api(tags = "运营")
@RequestMapping("/api")
@Slf4j
public class ApiOperController {

	@Autowired
	private AdvertisementService advertisementService;

	@Autowired
	private ConfigService<ServiceTerms> serviceTermsConfigService;

	@Autowired
	private ConfigService<AgreementConfig> agreementConfigService;

    @Autowired
    AliYunOSSClient ossClient;

    @Autowired
	private AreaService areaService;

	@ApiOperation(value = "获取广告")
	@GetMapping("/v1/advertisement/list/{position}")
	public JSONResult<List<Advertisement>> advertisementList(@ApiParam("广告位置1.首页 2.创新项目路演厅") @PathVariable Integer position) {
		List<Advertisement> advertisementList = advertisementService.getAdvertisementList(position);
		return JSONResult.ok(advertisementList);
	}

	@ApiOperation(value = "获取省级信息")
	@GetMapping("access/v1/area/province")
	public JSONResult<List<Area>> getAreaParent() {
		List<Area> province = areaService.findProvince();
		return JSONResult.ok(province);
	}

	@ApiOperation(value = "获取市级/区县信息")
	@GetMapping("access/v1/area/city/{parentId}")
	public JSONResult<List<Area>> getAreaChild (@PathVariable Long parentId) {
		List<Area> province = areaService.findCity(parentId);
		return JSONResult.ok(province);
	}

	@ApiOperation(value = "获取服务条款")
	@GetMapping("/v1/service/terms/config")
	public JSONResult<ServiceTerms> getServiceTerms() {
		return JSONResult.ok(serviceTermsConfigService.get());
	}


	@ApiOperation(value = "获取用户协议")
	@GetMapping("/v1/agreement/config")
	public JSONResult<AgreementConfig> getAgreementConfig() {
		return JSONResult.ok(agreementConfigService.get());
	}


    @PostMapping("/v1/app/imgUpload")
    @ApiOperation(value = "上传图片", notes = "上传图片")
    public JSONResult<FileUriResult> imgUpload(HttpServletRequest request) {
        InputStream stream = null;
        String uri = "";
        List<String> uriList = Lists.newArrayList();
        String bucket = ossClient.getDefaultBucketName();
        try {
            DiskFileItemFactory fac = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(fac);
            upload.setHeaderEncoding("utf-8");

            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> fileList1 = new ArrayList<>(multipartRequest.getFileMap().values());

            for (MultipartFile file : fileList1) {
                String fileName = UUID.randomUUID().toString();
                String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
                if (null == file) {
                    continue;
                }
                stream = file.getInputStream();
                PutObjectResult result = ossClient.putObject(bucket, "nunu/" + fileName + fileType, stream);
                uriList.add(ossClient.genUrl("nunu/" + fileName + fileType));
            }
        } catch (Exception e) {
            log.error("文件上传错误:", e);
        } finally {
            try {
                if (stream != null) {
                    stream.close();
                }
            } catch (IOException e) {
                log.error("文件上传错误:", e);
            }
        }
        if (0 != uriList.size()) {
            uri = StringUtils.join(uriList, ",");
        }
        return JSONResult.ok(FileUriResult.builder().fileUri(uri).build());
    }

}