package com.unis.base.server.controller;


import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.github.pagehelper.PageInfo;
import com.unis.base.common.util.ExcelUtils;
import com.unis.base.common.vo.CompanyVO;
import com.unis.base.common.vo.ImportConfigVO;
import com.unis.base.server.entity.TyHly;
import com.unis.base.server.entity.TyHlyDr;
import com.unis.base.server.entity.TyHlyz;
import com.unis.base.server.service.CompanyService;
import com.unis.base.server.service.TyHlyService;
import com.unis.common.utils.DateUtil;
import com.unis.common.utils.JsonUtils;
import com.unis.common.utils.ResponseWrapper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 好粮油
 * @author My Sunshine
 *
 */
@RestController
@RequestMapping(value="/haoliangyou")
@Api(tags = "好粮油")
public class TyHlyController {

    @Resource
    private TyHlyService hlyService;
    
    @Autowired
	private CompanyService companyService;

    
    /**
     * 列表
     * @param pageNum  页码
     * @param pageSize 每页显示条数
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/selectPageByEntity",produces = MediaType.APPLICATION_JSON_VALUE, method=RequestMethod.POST)
    @ApiOperation(value="好粮油企业列表", notes = "查询数据列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query")
    })
    public PageInfo<TyHly> selectPageByEntity(Integer pageNum, Integer pageSize,HttpServletRequest request, 
    		@RequestBody TyHly hly) throws Exception {
        List<TyHly> list = hlyService.queryList(pageNum, pageSize,hly);
        PageInfo<TyHly> pageInfo = new PageInfo<TyHly>(list);
        return pageInfo;
    }


    
    /** 保存
     * @param hlyzList list
     * @param  TyHly 实体对象
     * @return
     * @throws JsonParseException
     * @throws JsonMappingException
     * @throws IOException
     */
    @RequestMapping(value="/save",produces = MediaType.APPLICATION_JSON_VALUE, method=RequestMethod.POST)
    @ApiOperation(value="保存数据", notes = "保存")
    @SuppressWarnings("unchecked")
    @ApiImplicitParams({
            @ApiImplicitParam(name="TyHly", value="好粮油数据对象", paramType="form")
    })
    public Map<String, Object> save(@RequestBody TyHly hly,HttpServletRequest request) 
    		throws JsonParseException, JsonMappingException, IOException {
                                    
        Map<String, Object> returnMap = new HashMap<String, Object>();
        int a = 0;
        try {

        	List<TyHlyz> hlyzList = hly.getzList();
        	if(hly.getId() == null || hly.getId() == ""){
        		//新增
        		CompanyVO companyVO = new CompanyVO();
            	companyVO.setTyshxydm(hly.getQyxydm());//统一社会信用代码
            	companyVO.setQymc(hly.getQymc());//企业名称
                a = companyService.insert(companyVO);
                if(a>0){
                	String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            		hly.setId(uuid);
            		hly.setCjsj(new Date());
                    a = hlyService.save(hly,hlyzList);
                }
        	}else{
        		
        		CompanyVO companyVO = companyService.getCompanyBytyshxydm(hly.getQyxydm());
        		if(companyVO != null){
        			companyVO.setQymc(hly.getQymc());
        			a = companyService.updateByEntitySelective(companyVO);
        		}
    			
        			a = hlyService.update(hly,hlyzList);
        	}
        	
            if (a>0) {
            	returnMap.put("status", "success");
            	
            }else{
            	returnMap.put("status", "error");
            	returnMap.put("msg", "保存失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            returnMap.put("status", "error");
            returnMap.put("msg", "保存失败！");
            return returnMap;
        }
        return returnMap;
    }


    /**
	 * 删除
	 * @param id 主键
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	@RequestMapping(value="/remove", produces = MediaType.APPLICATION_JSON_VALUE, method=RequestMethod.POST)
	@ApiOperation(value="删除", notes = "根据id删除")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id", value = "id", paramType = "query"),
		@ApiImplicitParam(name = "qyxydm", value = "qyxydm", paramType = "query")
	})
	public Map<String, Object> remove(String id,String qyxydm) throws JsonParseException, JsonMappingException, IOException {
		Map<String, Object> modelMap = new HashMap<String, Object>();
		if (id != null && id != "" && qyxydm != null && qyxydm != "") {
			int a = hlyService.remove(id,qyxydm);
			if(a>0){
				modelMap.put("status", "success");
			}else{
				modelMap.put("status", "error");
			}
		}else{
			modelMap.put("msg", "请输入有效id");
		}
		
		return modelMap;
	}

	
	/**
	 * 根据id查找
	 * @param id 主键
	 * @return
	 */
	@RequestMapping(value="/getById", produces = MediaType.APPLICATION_JSON_VALUE, method=RequestMethod.GET)
	@ApiOperation(value="根据id查找", notes = "根据id查找")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id", value = "id", paramType = "query")
	})
	public Map<String, Object> getById(String id) {
        return hlyService.getById(id);
    }
	
	
	@ApiOperation(value = "好粮油企业导入数据", notes = "好粮油企业导入数据---")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "file", value = "文件对象集合")
			,@ApiImplicitParam(name = "zzbm", value = "组织编码")
	})
	@PostMapping(value= "/importByEntity", headers= "content-type= multipart/form-data", consumes= "multipart/*")
	public ResponseWrapper importByEntity(HttpServletRequest request, HttpServletResponse response
			,@RequestParam(value= "file", required = true) MultipartFile file
			,@RequestPart(value = "zzbm", required = true) String zzbm) throws IOException {
			
		if(file== null){
			return ResponseWrapper.fail("无文件数据");
		}
		//获得文件名
        String fileName = file.getOriginalFilename();
        //判断文件是否是excel文件
        if (!fileName.endsWith("xls") && !fileName.endsWith("xlsx")) {
        	return ResponseWrapper.invalid();
        }
		
	    return hlyService.importByEntityResult(file,zzbm);
		
	}
	
	
	@ApiOperation(value = "好粮油---根据条件导出数据", notes = "好粮油---")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "qymc", value = "企业名称", paramType = "query")
    })
    @RequestMapping(value="/exportByEntity",produces = MediaType.APPLICATION_JSON_VALUE, method=RequestMethod.POST)
    public void exportByEntity(HttpServletRequest request, HttpServletResponse response
            , String qymc) throws Exception {
            
		
        List<TyHlyDr> data= hlyService.exportByEntityResult(qymc);
        LinkedHashMap<String, String> columnName = new LinkedHashMap<>();
        
        columnName.put("qymc","企业名称");
        columnName.put("qylx","企业类型");
        columnName.put("qyxydm","企业信用代码");
        columnName.put("cp","产品");
        columnName.put("pp","品牌");
        columnName.put("lxr","联系人");
        columnName.put("lxfs","联系方式");
        
        // 输出Excel文件
   		
   		response.reset();
   		String fileName = "放心(好)粮油企业";
   		response.setHeader("content-disposition", "attachment;filename="
   				+ new String(DateUtil.getDate()) + ".xls");
   	
   		response.setContentType("application/vnd.ms-excel;charset=gb2312");
   		ServletOutputStream output = response.getOutputStream();
   		ExcelUtils.pojo3Excel(data, output, columnName,fileName);
   		
   		output.close();
    
    }

	 
}