package com.nantian.cloud.jly.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nantian.cloud.jly.entity.CompanyCalculater;
import com.nantian.cloud.jly.service.CompanyCalculaterService;
import com.nantian.cloud.jly.vo.util.FileUtil;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.log.annotation.SysLog;
import com.nantian.sc.cloud.common.minio.service.MinioTemplate;
import com.nantian.sc.cloud.common.security.annotation.Inner;
import com.nantian.sc.cloud.common.security.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.builder.ToStringExclude;
import org.apache.xmlbeans.impl.piccolo.io.FileFormatException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * 能源计量人员配置信息
 *
 * @author
 * @date 2018-09-27 15:20:44
 */
@Slf4j
@RestController
@AllArgsConstructor
@Api(value = "companyCalculater",tags = "能源计量人员配置信息")
@RequestMapping("/companyCalculater")
public class CompanyCalculaterController {
	private final CompanyCalculaterService companyCalculaterService;
	private final MinioTemplate minioTemplate;


	/**
	 * 分页查询
	 *
	 * @param page      分页对象
	 * @param companyCalculater 请假审批单
	 * @return
	 */
	@SysLog("能源计量人员配置信息-分页查询")
	@ApiOperation(value = "查询计量人员配置信息",notes = "条件查询计量人员配置信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name ="CompanyCalculater",value = "计量人员配置信息",required = false,dataType = "json",paramType = "path"),
			@ApiImplicitParam(name ="Page",value = "分页对象",required = false,dataType = "json",paramType = "path")
	})
	@GetMapping("/page")
	public R pageCmp(Page page, CompanyCalculater companyCalculater) {
		companyCalculater.setDelFlag("1"); //查询未删除数据
		return R.ok(companyCalculaterService.pageCmp(page, companyCalculater));
	}

	/**
	 * 分页查询
	 *
	 * @param page      分页对象
	 * @param companyCalculater 请假审批单
	 * @return
	 */
	@SysLog("能源计量人员配置信息-分页查询")
	@ApiOperation(value = "查询计量人员配置信息",notes = "条件查询计量人员配置信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name ="CompanyCalculater",value = "计量人员配置信息",required = false,dataType = "json",paramType = "path"),
			@ApiImplicitParam(name ="Page",value = "分页对象",required = false,dataType = "json",paramType = "path")
	})
	@GetMapping("/selectByCmp")
	public R selectByCmp(Page page, CompanyCalculater companyCalculater) {
		companyCalculater.setDelFlag("1"); //查询未删除数据
		//return R.ok(companyCalculaterService.page(page, Wrappers.query(companyCalculater)));
		return R.ok(companyCalculaterService.selectByCmp(page, companyCalculater));
	}


	/**
	 * 信息
	 *
	 * @param companyCalculaterId
	 * @return R
	 */
	@SysLog("能源计量人员配置信息-通过ID查询计量人员配置信息")
	@ApiOperation(value = "通过ID查询计量人员配置信息",notes = "通过ID查询计量人员配置信息")
	@ApiImplicitParam(name ="companyCalculaterId",value = "计量人员配置信息ID",required = true,paramType = "path",dataType = "int")
	@GetMapping("/{companyCalculaterId}")
	public R getById(@PathVariable("companyCalculaterId") Integer companyCalculaterId) {
		return R.ok(companyCalculaterService.getById(companyCalculaterId));
	}

	/**
	 * 新增/修改
	 */
	@SysLog("能源计量人员配置信息-新增/修改")
	@ApiOperation(value = "新增/修改计量人员配置信息",notes = "新增/修改计量人员配置信息")
	@PostMapping
	@ApiImplicitParams({
			@ApiImplicitParam(name ="CompanyCalculater",value = "计量人员配置信息",required = true,dataType = "json",paramType = "path"),
			@ApiImplicitParam(name = "certificateFile", value = "文件流（专业技术证书文件）", required = false, dataType = "File", paramType = "path"),
	})
	public R save(CompanyCalculater companyCalculater, MultipartFile certificateFile) throws Exception {
		log.error("新增/修改计量人员配置信息：{}，##文件：{}",companyCalculater,
				certificateFile == null ? 0 : certificateFile.getSize());

		CompanyCalculater co=new CompanyCalculater();
		ScUser u= SecurityUtils.getUser();
		companyCalculater.setUserid(u.getId());
		companyCalculater.setDeptId(u.getDeptId());
		companyCalculater.setEnterpriseCode(u.getEnterpriseCode());
		companyCalculater.setDelFlag("1");
		companyCalculater.setUpdateTime(new Date());
		if (certificateFile != null) {
			if(certificateFile.getSize()>0){
				//被替换计量器二位码
				companyCalculater.setCertificate(getFileUrl(certificateFile));
			}
		}
		return R.ok(companyCalculaterService.saveOrUpdate(companyCalculater));
	}

	public String getFileUrl(MultipartFile file) throws Exception {
		String uuid = UUID.randomUUID().toString();
		InputStream inputStream = file.getInputStream(); //得到文件流
		String fileName = file.getOriginalFilename();    //文件名（含后缀）
		//minioTemplate.putObject("jly", uuid, inputStream);
		minioTemplate.putObject("jly", uuid, inputStream,inputStream.available(),"application/octet-stream");
		return fileName + "<" + uuid;
	}

	/**
	 * 修改
	 *
	 * @param companyCalculater
	 * @return R
	 */
	@SysLog("能源计量人员配置信息-修改")
	@ApiOperation(value = "修改计量人员配置信息",notes = "修改计量人员配置信息")
	@ApiImplicitParam(name ="CompanyCalculater",value = "计量人员配置信息",required = true,dataType = "json",paramType = "path")
	@PutMapping
	public R updateById(@RequestBody CompanyCalculater companyCalculater) {
		ScUser u= SecurityUtils.getUser();
		companyCalculater.setUserid(u.getId());
		companyCalculater.setUpdateTime(new Date());
		return R.ok(companyCalculaterService.updateById(companyCalculater));
	}

	/**
	 * 删除
	 *
	 * @param companyCalculaterId
	 * @return R
	 */
	@SysLog("能源计量人员配置信息-删除")
	@ApiOperation(value = "删除计量人员配置信息",notes = "删除计量人员配置信息")
	@ApiImplicitParam(name ="companyCalculaterId",value = "计量人员配置信息ID",required = true,dataType = "int",paramType = "path")
	@DeleteMapping("/{companyCalculaterId}")
	public R removeById(@PathVariable("companyCalculaterId") Long companyCalculaterId) {
		CompanyCalculater companyCalculater = companyCalculaterService.getById(companyCalculaterId);
		ScUser u= SecurityUtils.getUser();
		if(u.getId()!=null){
			companyCalculater.setUserid(u.getId());
		}
		companyCalculater.setDelFlag("4");
		companyCalculater.setUpdateTime(new Date());
		return R.ok(companyCalculaterService.updateById(companyCalculater));
	}

	/**
	 * 查询计量人员按地区统计数据
	 *
	 * @return R
	 */
	@SysLog("能源计量人员配置信息-查询计量人员按地区统计数据")
	@ApiOperation(value = "查询计量人员按地区统计数据",notes = "查找计量人员按地区统计数据")
	@GetMapping("/getCaculaterStatistics")
	public R getCaculaterStatistics() {
		return R.ok(companyCalculaterService.getCaculaterStatistics());
	}

	/**
	 * 分页查询计量人员数据
	 *
	 * @return R
	 */
	@SysLog("能源计量人员配置信息-分页查询计量人员数据")
	@ApiOperation(value = "分页查询计量人员数据",notes = "分页查询计量人员数据")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "Page", value = "分页对象", required = false, dataType = "json", paramType = "path"),
			@ApiImplicitParam(name = "areaCodes", value = "地区编码", required = false, dataType = "string", paramType = "path"),
			@ApiImplicitParam(name = "industryCode", value = "行业编码", required = false, dataType = "string", paramType = "path"),
			@ApiImplicitParam(name = "cmpName", value = "企业名称", required = false, dataType = "string", paramType = "path")
	})
	@GetMapping("/getPageData")
	public R getPageData(Page page, String areaCodes, String industryCode, String cmpName,String calculaterName) {
		return R.ok(companyCalculaterService.getPageData(page,areaCodes,industryCode,cmpName,calculaterName));
	}

	/**
	 * 下载模板文件
	 */
	@SysLog("能源计量人员配置信息-下载模板文件")
	@GetMapping(value = "/download")
	@ApiOperation(value = "下载模板文件", notes = "下载模板文件")
	public R download(HttpServletRequest request, HttpServletResponse response) {
		try {
			//URL url = getClass().getClassLoader().getResource("mouldFile/RecordPersonManagerMouldFile.xls");
			URL url = new ClassPathResource("mouldFile/RecordPersonManagerMouldFile.xls").getURL();
			log.info("获取文件url:" + url);
			// 通过url获取File的绝对路径
			File f = new File(url.getFile());
			if (!f.exists()) {
				return R.failed("路径有误，文件不存在！");
			}
			log.info("获取文件的绝对路径:" + f + "，文件长度：" + f.length());
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/x-download;charset=utf-8");
			response.setHeader("Content-disposition", URLEncoder.encode(f.getName(), "UTF-8"));
			//mime类型
			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(f.getName(), "UTF-8"));
			response.setHeader("Pragma", "No-cache");
			//从内存中写出来
			OutputStream outputStream = response.getOutputStream();
			outputStream.write(FileUtil.file2byte(f));
			outputStream.flush();
			outputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return R.ok("下载模板文件成功");
	}

	/**
	 * 导入excel
	 */
	@SysLog("能源计量人员配置信息-导入excel")
	@PostMapping("excelImport")
	@ApiOperation(value = "导入excel", notes = "导入excel")
	@ApiImplicitParam(name = "file", value = "文件", required = true, dataType = "file", paramType = "path")
	public R excelImport(@RequestParam MultipartFile file,String epc) throws FileFormatException {
		return companyCalculaterService.excelImport(file,epc);
	}

}
