package io.renren.modules.app.controller;

import io.renren.common.utils.R;
import io.renren.modules.app.annotation.Login;
import io.renren.modules.app.entity.FjEntity;
import io.renren.modules.app.entity.MyProps;
import io.renren.modules.app.entity.SqwxzqEntity;
import io.renren.modules.app.entity.WxjlbEntity;
import io.renren.modules.app.entity.WxxmxxEntity;
import io.renren.modules.app.entity.XlkEntity;
import io.renren.modules.app.service.SqwxzqService;
import io.renren.modules.app.service.ZhxxtempService;
import io.renren.modules.app.service.WxjlbService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


/**
 * 房屋维修单录入
 *
 * @author ly
 * @email 1271428398@qq.com
 * @date 2019-04-11 10:12:38
 */
@RestController
@RequestMapping("app/sqwxzq")
@Api(tags = "房屋维修单录入")
public class SqwxzqController {
	
	@Autowired
	private MyProps myprops;

	@Autowired
	private SqwxzqService sqwxzqService;
	@Autowired
	private WxjlbService WxjlbService;
	@Autowired
	private ZhxxtempService ZhxxtempService;

	@Login
	@GetMapping("/query")
	@ApiOperation(value = "列表", notes = "模糊查询，查询关键字：(请补充...)", response = SqwxzqEntity.class)
	public R query(SqwxzqEntity sqwxzqEntity) {

		return R.ok().put("data", sqwxzqService.query(sqwxzqEntity));
	}

	@Login
	@GetMapping("/querylr")
	@ApiOperation(value = "列表", notes = "房屋维修单录入申请单编号下拉选", response = SqwxzqEntity.class)
	public R querylr(SqwxzqEntity sqwxzqEntity) {

		return R.ok().put("data", sqwxzqService.querys(sqwxzqEntity));
	}

	@Login
	@GetMapping("/querysh")
	@ApiOperation(value = "列表", notes = "房屋维修单审核申请单编号下拉选", response = SqwxzqEntity.class)
	public R querysh(SqwxzqEntity sqwxzqEntity) {
		sqwxzqEntity.setSfsh("1");
		sqwxzqEntity.setSfjz("0");
		sqwxzqEntity.setSffp("0");
		return R.ok().put("data", sqwxzqService.querym(sqwxzqEntity));
	}

	@Login
	@GetMapping("/queryft")
	@ApiOperation(value = "列表", notes = "支取分摊申请单编号下拉选", response = SqwxzqEntity.class)
	public R queryft(SqwxzqEntity sqwxzqEntity) {
		sqwxzqEntity.setSfsh("1");
		sqwxzqEntity.setSfjz("0");
		return R.ok().put("data", sqwxzqService.querym(sqwxzqEntity));
	}

	@Login
	@GetMapping("/queryhb")
	@ApiOperation(value = "列表", notes = "支取划拨申请单编号下拉选", response = SqwxzqEntity.class)
	public R queryhb(SqwxzqEntity sqwxzqEntity) {
		sqwxzqEntity.setSfsh("1");
		sqwxzqEntity.setSfjz("0");
		sqwxzqEntity.setSffp("1");
		return R.ok().put("data", sqwxzqService.querym(sqwxzqEntity));
	}

	@Login
	@GetMapping("/queryyhb")
	@ApiOperation(value = "列表", notes = "已划拨申请单查询", response = SqwxzqEntity.class)
	public R queryyhb(SqwxzqEntity sqwxzqEntity) {
		sqwxzqEntity.setSfsh("1");
		sqwxzqEntity.setSfjz("1");
		sqwxzqEntity.setSffp("1");
		sqwxzqEntity.setSfjs("0");
		return R.ok().put("data", sqwxzqService.querym(sqwxzqEntity));
	}

	@Login
	@GetMapping("/queryftsc")
	@ApiOperation(value = "列表", notes = "支取分摊删除", response = SqwxzqEntity.class)
	public R queryftsc(SqwxzqEntity sqwxzqEntity) {
		if ("0".equals(sqwxzqEntity.getSffp())) {
			return R.ok().put("msg", "该单据未分配，操作失败！");
		} else {
			sqwxzqEntity.setSffp("0");
			sqwxzqService.updateById(sqwxzqEntity);
			sqwxzqService.queryftsc(sqwxzqEntity);
			return R.ok().put("msg", "删除成功");
		}

	}

	@Login
	@GetMapping("/queryftbc")
	@ApiOperation(value = "列表", notes = "支取分摊保存", response = SqwxzqEntity.class)
	public R queryftbc(SqwxzqEntity sqwxzqEntity) {
		if ("1".equals(sqwxzqEntity.getSffp())) {
			return R.ok().put("msg", "该单据已分配，操作失败！");
		} else {
			sqwxzqEntity.setSffp("1");
			sqwxzqService.updateById(sqwxzqEntity);
			sqwxzqService.queryftbc(sqwxzqEntity);
			return R.ok().put("msg", "保存成功");
		}

	}


	@Login
	@GetMapping("/queryshtg")
	@ApiOperation(value = "列表", notes = "房屋维修单审核通过", response = SqwxzqEntity.class)
	public R queryshtg(SqwxzqEntity sqwxzqEntity) {
		sqwxzqEntity.setSfsh("1");
		sqwxzqService.updateById(sqwxzqEntity);
		return R.ok();
	}

	@Login
	@GetMapping("/queryshbh")
	@ApiOperation(value = "列表", notes = "房屋维修单审核驳回", response = SqwxzqEntity.class)
	public R queryshbh(SqwxzqEntity sqwxzqEntity) {
		sqwxzqEntity.setSfsh("2");
		sqwxzqService.updateById(sqwxzqEntity);
		return R.ok();
	}

	@Login
	@GetMapping("/queryzq")
	@ApiOperation(value = "列表", notes = "支取分摊根据单号查询", response = SqwxzqEntity.class)
	public R queryzq(SqwxzqEntity sqwxzqEntity) {

		return R.ok().put("data", sqwxzqService.querft(sqwxzqEntity));
	}

	@Login
	@PostMapping("/insert")
	@ApiOperation(value = "新增一笔维修单录入保存", notes = "wxlb里放入一个list", response = SqwxzqEntity.class)
	public R insert(@RequestBody SqwxzqEntity sqwxzqEntity) {
		String temp_str="";   
	    Date dt = new Date();   
	    //最后的aa表示“上午”或“下午”    HH表示24小时制    如果换成hh表示12小时制   
	    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	    temp_str=sdf.format(dt);
	    String temp_str1 = "";
		Date dt1 = new Date();
		// 最后的aa表示“上午”或“下午” HH表示24小时制 如果换成hh表示12小时制
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
		temp_str1 = sdf1.format(dt1);
		String maxdjbh = sqwxzqService.queryByCount(temp_str);
		String newdjbh = "";
		if ("".equals(maxdjbh) || maxdjbh == null) {
			newdjbh = temp_str1 + "0001";
		} else if (!"".equals(maxdjbh) && maxdjbh != null) {
			String aa = Integer.parseInt(maxdjbh) + 1 + "";
			DecimalFormat df = new DecimalFormat("0000");
			String result = df.format(Integer.parseInt(aa));
			newdjbh =temp_str1 + result;
		}
		
		sqwxzqEntity.setSqdbh(newdjbh);
		List<WxjlbEntity> wxxmxxEntity = sqwxzqEntity.getWxlb();
		if (wxxmxxEntity != null) {//记录维修的内容
			for (WxjlbEntity wxxmxxEntity2 : wxxmxxEntity) {
//				wxxmxxEntity2.setDhbm(sqwxzqEntity.getDhbm());
				wxxmxxEntity2.setSqdbh(newdjbh);
				String uuid = UUID.randomUUID().toString().replaceAll("-", "");
				wxxmxxEntity2.setId(uuid);
				sqwxzqService.insertwxjlb(wxxmxxEntity2);
			}
		}
		String uuid2 = UUID.randomUUID().toString().replaceAll("-", "");
		
		if(isObjectNotEmpty(sqwxzqEntity.getWjdx())){//记录上传的文件信息
			sqwxzqEntity.getWjdx().setId(uuid2);
			sqwxzqService.insertFjb(sqwxzqEntity.getWjdx());
			sqwxzqEntity.setFjid(uuid2);
		}
		sqwxzqEntity.setLrrq(temp_str);
		sqwxzqService.insertsqwxz(sqwxzqEntity);
		return R.ok();
	}

	@Login
	@PostMapping("/update")
	@ApiOperation(value = "修改", notes = "在此补充接口详细注释...", response = SqwxzqEntity.class)
	public R update(@RequestBody SqwxzqEntity sqwxzqEntity) {
		sqwxzqService.updateById(sqwxzqEntity);
		Map map = new HashMap();
		map.put("sqdbh", sqwxzqEntity.getSqdbh());
		WxjlbService.deleteSqdbh(map);
		WxjlbService.insertBatch(sqwxzqEntity.getWxlb());
		return R.ok();
	}

	@Login
	@GetMapping("/delete")
	@ApiOperation(value = "(批量)删除", notes = "根据id删除，前端传参名：ids（数组）", response = SqwxzqEntity.class)
	public R delete(@RequestBody String[] ids) {
		sqwxzqService.deleteBatch(ids);
		return R.ok();
	}

	@Login
	@GetMapping("/selectdjld")
	@ApiOperation(value = "下拉框多级联动查询", notes = "在此补充接口详细注释...", response = XlkEntity.class)
	public R selectdjld(@RequestBody Map<String, String> map) {

		return R.ok().put("selectdjld", sqwxzqService.selectDjld(map));
	}

	@Login
	@GetMapping("/selectdjxx")
	@ApiOperation(value = "下拉框查询未审核和退回的单据信息", notes = "在此补充接口详细注释...", response = SqwxzqEntity.class)
	public R selectdjxx(@RequestBody Map<String, String> map) {

		return R.ok().put("selectdjxx", sqwxzqService.selectDjxx(map));
	}

	// @Login
	@PostMapping("/selectwxxmxx")
	@ApiOperation(value = "查询所有维修项目信息", notes = "在此补充接口详细注释...", response = WxxmxxEntity.class)
	public R selectwxxmxx(@RequestBody Map<String, String> map) {

		return R.ok().put("selectwxxmxx", sqwxzqService.selectWxxmxx(map));
	}

	// @Login
	@GetMapping("queryByPage")
	@ApiOperation(value = "房屋维修单录入分页查询", notes = "带分页、模糊查询，查询关键字：(请补充...)", response = SqwxzqEntity.class)
	public R queryByPage(Integer pageNum, Integer pageSize, SqwxzqEntity sqwxzqEntity) {

		return R.ok().put("data", sqwxzqService.queryByPage(pageNum, pageSize, sqwxzqEntity));
	}


	// @Login
	@PostMapping("/updatelr")
	@ApiOperation(value = "编辑单据保存修改", notes = "")
	public R updatelr(@RequestBody SqwxzqEntity sqwxzqEntity) {
		sqwxzqService.updatelr(sqwxzqEntity);
		return R.ok();
	}

	// @Login
	@PostMapping("/deletelr")
	@ApiOperation(value = "删除按钮", notes = "")
	public R deletelr(@RequestBody Map<String, String> map) {
		sqwxzqService.deletelr(map);
		return R.ok();
	}
	
	/**
	 * 文件上传公共接口
	 */
	@RequestMapping("fileUpload")
	@ResponseBody
	@ApiOperation(value = "实现文件上传测试", notes = "实现文件上传测试")
	public R fileUpload(@RequestParam("file") MultipartFile file) {
		String path = "";
		path = myprops.getSimpleprop();// 获取配置文件本地磁盘的绝对路径
		if (file.isEmpty()) {
			return R.error("文件为空");
		}
		
		String fileName = file.getOriginalFilename();
		String[] arr=fileName.split("\\.");
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		String wjmc = arr[0]+uuid;// 文件名称
		String type = arr[1];// 文件类型
		String size = file.getSize() + "";
		String wjqlj = path + "/" + wjmc+"."+type;// 文件全路径
		System.out.println(fileName + "-->" + size);
		File dest = new File(path + "/" + wjmc+"."+type);
		
		if (!dest.getParentFile().exists()) { // 判断文件夹路径本地磁盘是否存在，若不存在则自动创建
			dest.getParentFile().mkdirs();
		}
		
		try {
			file.transferTo(dest); // 保存文件
			FjEntity fj = new FjEntity();
			fj.setWjmc(wjmc);
			fj.setWjtype(type);
			fj.setWjqlj(wjqlj);
			fj.setWjsize(size);
			return R.ok().put("data", fj);
		} catch (IllegalStateException e) {
			e.printStackTrace();
			return R.error("printStackTrace");
		} catch (IOException e) {
			e.printStackTrace();
			return R.error("printStackTrace");
		}
	}
	
	/**
	 * 文件下载公共接口
	 * 
	 * @param path
	 * @param response
	 * @return
	 */
	@RequestMapping("/download")
	@ApiOperation(value = "实现文件下载测试", notes = "实现文件下载测试")
	public HttpServletResponse download(HttpServletRequest request, HttpServletResponse response) {
		try {
//			String path = "D:/wxzjwjk/wxdwj/66f8b8b52d79c93d76d34297e61d6908d7e7b6d0d75d4060a0fe86a35ec6de05.jpg";
			String name=request.getParameter("name");
//			String jdlj = myprops.getSimpleprop();// 获取配置文件本地磁盘的绝对路径
//			String path=jdlj+File.separator+name;
			String path=name;
			// path是指欲下载的文件的路径。
//			String path=qyXqFbEntity.getPath();
			File file = new File(path);
			// 取得文件名。
			String filename = file.getName();
			// 取得文件的后缀名。
			String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

			// 以流的形式下载文件。
			InputStream fis = new BufferedInputStream(new FileInputStream(path));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// 清空response
			response.reset();
			// 设置response的Header
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
			response.addHeader("Content-Length", "" + file.length());
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
			System.out.println(filename);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 返回图片给前端(以流的形式)
	 */
	@RequestMapping("/image")
	@ApiOperation(value = "图片", notes = "")
	public void assetCardImg(HttpServletRequest request,HttpServletResponse response) {
		String path = request.getParameter("name");
//		String path = "D:/wxzjwjk/wxdwj/bg201908200915e4912ef2e948c0a098c877e7d1d189.jpg";
		// 根据附件id, 查询附件全路径
//		String path = sqwxzqService.getWjqljById(fjid);
		try {
			if (path != null && !"".equals(path)) {
				File file = new File(path);
				if (file.exists()) {
					FileInputStream fis = new FileInputStream(file);
					byte[] b = new byte[1024];
					response.setContentType("application/jpeg");
					OutputStream os = response.getOutputStream();
					int len;
					while ((len = fis.read(b)) != -1) {
						os.write(b, 0, len);
					}
					fis.close();
					os.flush();
					os.close();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	public static Boolean isObjectNotEmpty(Object obj) {
		String str = ObjectUtils.toString(obj, "");
		return StringUtils.isNotBlank(str);
	}

}
