package com.unis.base.server.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.unis.base.common.vo.*;
import com.unis.common.utils.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.github.pagehelper.PageInfo;
import com.unis.base.server.entity.TzSlqyDO;
import com.unis.base.server.service.CompanyService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author huangxing
 * @version 1.0
 * @Title TzSlqyController
 * @ProjectName 企业信息Controller
 * @date 2019/07/22 17点26分
 */
@RestController
@Api(value = "企业信息", tags = "企业信息维护")
@Slf4j
public class CompanyController {

	@Autowired
	private CompanyService companyService;

	/**
	 * @author huangxing
	 * @Description 获取企业信息列表
	 * @param 社会统一行政编码，企业名称，企业类型，企业性质，法定代表人
	 * @return 企业信息列表
	 */
	@ApiOperation(value = "获取企业信息列表", notes = "参数：社会统一行政编码，企业名称，企业类型，企业性质，法定代表人，企业状态")
	@PostMapping(value = "/companyList")
    public ResponseWrapper getCompanyList(@RequestBody CompanyQueryVO companyQueryVO) {
		try{
        	List<CompanyVO> tzSlqyTOs = companyService.getCompanyList(companyQueryVO);
            return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), tzSlqyTOs);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
    }

	@ApiOperation(value = "获取企业信息列表", notes = "参数：社会统一行政编码，企业名称，企业类型，企业性质，法定代表人，企业状态")
	@PostMapping(value = "/qyxxList/{pageNum}/{pageSize}")
	public ResponseWrapper qyxxList(@RequestBody QyxxVO qyxxVO,@PathVariable("pageNum")Integer pageNum,@PathVariable("pageSize") Integer pageSize) {
		try{
			PageInfo<QyxxVO> pageInfos = new PageInfo<QyxxVO>(companyService.getQyxxListPage(qyxxVO,pageNum,pageSize));

			List<QyxxVO> companyList = companyService.qyxxList(qyxxVO);

			pageInfos.setTotal(companyList.size());
			return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), pageInfos);
			//List<QyxxVO> tzSlqyTOs = companyService.qyxxList(qyxxVO);
			//return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), tzSlqyTOs);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
		return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
	}


	/**
	 * @author
	 * @Description
	 * @param
	 * @return
	 */
	@ApiOperation(value = "获取承储库数据(固定用)", notes = "")
	@PostMapping(value = "/companyKdList")
	public ResponseWrapper companyKdList() {
		try{
			List<CompanyKdVO> tzSlqyTOs = companyService.getCompanyKdList();
			return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), tzSlqyTOs);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
		return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
	}


	/**
	 * @author huangxing
	 * @Description 获取企业信息列表
	 * @param 社会统一行政编码，企业名称，企业类型，企业性质，法定代表人
	 * @return 企业信息列表
	 */
	@ApiOperation(value = "分页获取企业信息列表", notes = "参数：社会统一行政编码，企业名称，企业类型，企业性质，法定代表人")
	@PostMapping(value = "/companyPage/{pageNum}/{pageSize}")
    public ResponseWrapper getCompanyPage(@RequestBody CompanyQueryVO companyVO,@PathVariable("pageNum")Integer pageNum,@PathVariable("pageSize") Integer pageSize) {
		try{
		    PageInfo<CompanyVO> pageInfos = new PageInfo<>(companyService.getCompanyPage(companyVO,pageNum,pageSize));
			List<CompanyVO> companyList = companyService.getCompanyList(companyVO);
			pageInfos.setTotal(companyList.size());
            return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), pageInfos);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
    }

	/**
	 * @author huangxing
	 * @Description 新增企业信息
	 * @param 参数：企业信息实体 models
	 * @return 新增状态
	 */
	@PostMapping(value = "/company")
	@ApiOperation(value = "新增企业信息", notes = "参数：统一社会信用代码，企业名称")
    public ResponseWrapper insert(@RequestBody CompanyVO companyVO) {
		try{
			if(StringUtils.isEmpty(companyVO.getTyshxydm())||StringUtils.isEmpty(companyVO.getQymc())) {
				return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "有必传参数为空", null);
			}
			int x = companyService.insert(companyVO);
			if(x>0) {
	            return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(),null);
			} else if (x==0) {
	            return ResponseWrapper.error(HttpStatus.BAD_REQUEST.value(), "添加失败", null);
			} else {
				 return ResponseWrapper.error(HttpStatus.BAD_REQUEST.value(), "添加失败,该统一社会信用代码已存在", null);
			}
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
    }

	/**
	 * @author huangxing
	 * @Description 修改企业信息
	 * @param 参数：企业信息实体 models
	 * @return 新增状态
	 */
	@PutMapping(value = "/company")
	@ApiOperation(value = "更新企业信息", notes = "参数：企业统一社会信用代码")
    public ResponseWrapper update(@RequestBody @Validated CompanyVO companyVO, BindingResult bindingResult) {
		try{
			if (bindingResult.hasFieldErrors()){
				//获取与字段相关的所有错误
				List<FieldError> fieldErrors = bindingResult.getFieldErrors();
				List<String> msgList = new ArrayList<>();
				for (FieldError fieldError : fieldErrors){
					msgList.add(fieldError.getField() + " : " + fieldError.getDefaultMessage());
				}
				return ResponseWrapper.error(msgList.toString());
			}
			if(new Date().before(companyVO.getZcrq())) {
				return ResponseWrapper.success(HttpStatus.NON_AUTHORITATIVE_INFORMATION.value(), "注册日期不能大于当前日期", null);
			}
			if(Double.parseDouble(companyVO.getQyjd())<73.55 || Double.parseDouble(companyVO.getQyjd())>135.1) {
				return ResponseWrapper.success(HttpStatus.NON_AUTHORITATIVE_INFORMATION.value(), "经度不在中国范围以内", null);
			}
			if(Double.parseDouble(companyVO.getQywd())<3.51 || Double.parseDouble(companyVO.getQywd())>53.33) {
				return ResponseWrapper.success(HttpStatus.NON_AUTHORITATIVE_INFORMATION.value(), "纬度不在中国范围以内", null);
			}
			if(null == companyVO.getZdmj() || new BigDecimal(0).compareTo(companyVO.getZdmj())>=0) {
				return ResponseWrapper.success(HttpStatus.NON_AUTHORITATIVE_INFORMATION.value(), "占地面积必填且不能小于等于0", null);
			}
			/*if(!isCard(companyVO.getFrsfzh())) {
				return ResponseWrapper.success(HttpStatus.NON_AUTHORITATIVE_INFORMATION.value(), "法人身份证号不正确", null);
			}*/
			int x = companyService.updateSlqyInfo(companyVO);
			if(x>0) {
				return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(),null);
			} else if (x==0) {
				return ResponseWrapper.success(HttpStatus.NON_AUTHORITATIVE_INFORMATION.value(), "更新失败", null);
			} else {
				return ResponseWrapper.success(HttpStatus.NON_AUTHORITATIVE_INFORMATION.value(), "更新失败，无此企业信息", null);
			}
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
    }

	/**
	 * 验证身份证真假
	 * @param  carNumber 身份证号
	 * @return boolean*/
	public static boolean isCard(String carNumber) {
		//判断输入身份证号长度是否合法
		if (carNumber.length() != 18) {
			throw new RuntimeException("身份证长度不合法");//不合法 抛出一个异常
		}
		//校验身份证真假
		int sum = 0;
		int[] weight = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};//将加权因子定义为数组
		//遍历weight数组 求身份证前17项系数和
		for (int i = 0; i < weight.length; i++) {
			int n = carNumber.charAt(i) - 48;//获取 身份证对应数
			int w = weight[i];
			sum += w * n;
		}
		//对11求余
		int index = sum % 11;
		//校验码
		String m = "10X98765432";
		//获取身份证最后一位进行比对
		return m.charAt(index) == carNumber.charAt(17);
	}


	/**
	 * @author huangxing
	 * @Description 修改企业信息单表
	 * @param 参数：企业信息实体 models
	 * @return 新增状态
	 */
	@PutMapping(value = "/updateSimple")
	@ApiOperation(value = "更新企业信息", notes = "参数：企业统一社会信用代码")
	public ResponseWrapper updateSimple(@RequestBody CompanyVO companyVO) {
		try{
			if(StringUtils.isEmpty(companyVO.getTyshxydm())) {
				return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "有必传参数为空", null);
			}
			int x = companyService.update(companyVO);
			if(x>0) {
				return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(),null);
			} else if (x==0) {
				return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "更新失败", null);
			} else {
				return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "更新失败，无此企业信息", null);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
		return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
	}

	/**
	 * @author huangxing
	 * @Description 获取企业信息
	 * @param 参数：社会行政代码
	 * @return 企业信息实体
	 */
	@GetMapping(value="/company/{tyshxydm}")
	@ApiOperation(value = "根据统一社会行政代码获取企业信息", notes = "参数：社会行政代码")
	public ResponseWrapper getCompanyBytyshxydm(@PathVariable("tyshxydm") String tyshxydm) {
		try{
			CompanyVO companyVO = companyService.getCompanyBytyshxydm(tyshxydm);
	        return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(),companyVO);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
    }

	@GetMapping(value="/companyType/{qyjgdm}")
	@ApiOperation(value = "根据企业机构代码获取企业的类型", notes = "参数：企业机构代码")
	public ResponseWrapper companyType(@PathVariable("qyjgdm") String qyjgdm) {
		try{
			return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(),companyService.companyType(qyjgdm));
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
		return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
	}


	/**
	 * @author huangxing
	 * @Description 获取企业信息
	 * @param ：企业名称
	 * @return 企业信息实体
	 */
	@GetMapping(value="/findByCompany/{qymc}")
	@ApiOperation(value = "根据企业名称", notes = "参数：企业名称")
	public ResponseWrapper findByCompany(@PathVariable("qymc") String qymc) {
		try{
			CompanyVO companyVO = companyService.findByCompany(qymc);
			return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(),companyVO);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
		return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
	}
	/**
	 * @author huangxing
	 * @Description 删除企业信息
	 * @param 参数：社会行政代码
	 * @return 状态
	 */
	@DeleteMapping(value="/company/{tyshxydm}")
	@ApiOperation(value = "根据统一社会行政代码删除企业信息", notes = "参数：社会行政代码")
	public ResponseWrapper delete(@PathVariable("tyshxydm") String tyshxydm) {
		try{
			int x = companyService.delete(tyshxydm);
			if(x>0) {
	            return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(),null);
			} else if (x==0) {
	            return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "删除失败", null);
			} else {
				 return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "删除失败,请社会行政代码是否正确", null);
			}
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
    }

	/**
	 * 根据企业机构代码查询企业
	 * @param companyQueryVO
	 * @return
	 */
	@PostMapping(value = "/organization/selectByEntity")
	@ApiOperation(value = "根据企业机构代码查询企业", notes = "参数：企业机构代码")
	public ResponseWrapper selectByEntity(@RequestBody CompanyQueryVO companyQueryVO) {
		try{
			List<TzSlqyDO> selectQy = companyService.selectByEntity(companyQueryVO);
			if(null == selectQy || selectQy.size()==0) {
				return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"查询不到结果");
			}
			return ResponseWrapper.success(HttpStatus.OK.value(), "查询成功", selectQy);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
		return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
	}

	/**
	 * 根据企业机构代码查询企业
	 * @param companyQueryVO
	 * @return
	 */
	@PostMapping(value = "/organization/selectById")
	@ApiOperation(value = "根据企业机构代码查询企业", notes = "参数：企业机构代码")
	public ResponseWrapper selectById(@RequestBody CompanyQueryVO companyQueryVO) {
		try{
			TzSlqyDO selectQy = companyService.selectById(companyQueryVO);
			if(null == selectQy) {
				return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"查询不到结果");
			}
			return ResponseWrapper.success(HttpStatus.OK.value(), "查询成功", selectQy);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
		return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
	}

	/**
	 * 根据企业机构代码查询企业
	 * @param qyjgdm
	 * @return
	 */
	@GetMapping(value = "/organization/{qyjgdm}")
	@ApiOperation(value = "根据企业机构代码查询企业", notes = "参数：企业机构代码")
	public ResponseWrapper getSlqy(@PathVariable("qyjgdm") String qyjgdm) {
		try{
			TzSlqyDO selectQy = companyService.getSlqy(qyjgdm);
			if(null == selectQy) {
				return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"查询不到结果");
			}
			return ResponseWrapper.success(HttpStatus.OK.value(), "查询成功", selectQy);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
    }

	/**
	 * 企业机构关联添加
	 * @param tzQyjgDO
	 * @return
	 */
	@PostMapping(value = "/organization")
	@ApiOperation(value = "企业机构关联添加", notes = "参数：企业机构代码")
	public ResponseWrapper insertQyjg(@RequestBody TzQyjgVO tzQyjgDO) {
		try{
			int insertQyjg = companyService.insertQyjg(tzQyjgDO);
			if(insertQyjg == 1) {
				 return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(),null);
			} else {
	            return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "该企业已被绑定！", null);
			}
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
    }

	@PostMapping(value = "/companyAll")
	@ApiOperation(value = "传入规避条件,返回企业列表")
	public ResponseWrapper companyAll(@RequestBody RandomCompanyQuery randomCompanyQuery) {
		System.out.println("companyAll:"+JsonUtils.serialize(randomCompanyQuery));


		try{
			return companyService.companyAll(randomCompanyQuery);
		}catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
		return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
	}

	/**
	 * 企业机构关联添加
	 * @param tzQyjgDO
	 * @return
	 */
	@PostMapping(value = "/randomcompany")
	@ApiOperation(value = "随机抽取企业", notes = "参数：随机抽取企业查询信息")
	public ResponseWrapper randomcompany(@RequestBody RandomCompanyQuery randomCompanyQuery) {
		System.out.println("randomcompany:"+JsonUtils.serialize(randomCompanyQuery));

		String areaCode = CurrentUtil.getAreaCode();
		randomCompanyQuery.setAreaCode(areaCode);
		String orgId= CurrentUtil.getOrgId();
		if(orgId!=null && orgId.length()>=8){
			randomCompanyQuery.setSslsxzglbm(orgId.substring(0,8));
		}

		try{
			Set<CompanyVO> insertQyjg = companyService.randomCompany(randomCompanyQuery);
			Integer num=randomCompanyQuery.getQysl();
			if(num==null || (num!=null && num<=insertQyjg.size())){
				return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(),insertQyjg);
			}else{
				return ResponseWrapper.error("企业数量不足");
			}
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
    }

	/**
	 * 禁用/启用
	 * @param qyzt
	 * @return
	 */
	@PostMapping(value = "/companyStatus/{qyzt}/{id}")
	@ApiOperation(value = "企业信息-更新启用状态", notes = "参数：启用状态，企业ID")
	public ResponseWrapper updateQyzt(@PathVariable(value="qyzt") Integer qyzt,
			   @PathVariable(value="id") Integer id) {
		try {
			if (qyzt == null || id == null) {
				return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "有必传参数为空", null);
			}
			Integer i = companyService.updateQyzt(qyzt, id);
			if (i > 0) {
				return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), "更新成功");
			}else {
				return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), "未更新数据，请联系管理员");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), "服务错误，请联系管理员");
		}
	}


	@PutMapping(value = "/audit")
	@ApiOperation(value = "企业信息审核", notes = "")
	public ResponseWrapper auditCompanyInfo(@RequestParam(value="qyzt") Integer qyzt,
			   @RequestParam(value="id") Integer id,@RequestParam(value = "审核意见",required = false) String shyj) {
		try {
			if (qyzt == null || id == null) {
				return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "有必传参数为空", null);
			}
			Integer i = companyService.auditCompany(id, qyzt, shyj);
			if (i > 0) {
				return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), "审核成功");
			}else {
				return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), "审核失败，请联系管理员");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), "服务错误，请联系管理员");
		}
	}

	/**
	 * 企业信息-更改备案状态
	 * @param companyRecordsVO
	 * @return
	 */
	@PostMapping(value = "/companyFiling")
	@ApiOperation(value = "企业信息-企业备案", notes = "参数：备案信息")
	public ResponseWrapper updateFilingStatus(@RequestBody CompanyRecordsVO companyRecordsVO) {
		try {
			if (companyRecordsVO.getSfba() == null) {
				return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "有必传参数为空", null);
			}
			Integer i = companyService.updateFilingStatus(companyRecordsVO);
			if (i > 0) {
				return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), "操作成功");
			} else if (i==-1) {
				return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "只有已备案和已驳回才能添加记录", null);
			} else if (i==-2) {
				return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "请输入驳回审批意见", null);
			} else {
				return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), "操作失败，请联系管理员");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), "服务错误，请联系管理员");
		}
	}


	/**
	 * @author huangxing
	 * @Description 获取企业信息列表
	 * @param 社会统一行政编码，企业名称，企业类型，企业性质，法定代表人
	 * @return 企业信息列表
	 */
	@ApiOperation(value = "获取企业信息列表", notes = "参数：经纬度")
	@PostMapping(value = "/companyListLaLo/{pageNum}/{pageSize}")
    public ResponseWrapper getCompanyListByLaLo(@RequestBody CompanyQueryVO companyQueryVO,@PathVariable(value="pageNum") Integer pageNum,@PathVariable(value="pageSize") Integer pageSize) {
		try{
        	List<CompanyVO> tzSlqyTOs = companyService.getCompanyListByLaLo(companyQueryVO,pageNum,pageSize);
            return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), tzSlqyTOs);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
    }

	/**
	 * @author ldq
	 * @Description 获取企业信息列表-应急
	 * @param 社会统一行政编码，企业名称，企业类型，企业性质，法定代表人
	 * @return 企业信息列表
	 */
	@ApiOperation(value = "分页获取企业信息列表-应急", notes = "参数：社会统一行政编码，企业名称，企业类型，企业性质，法定代表人")
	@PostMapping(value = "/getYjCompanyPage/{pageNum}/{pageSize}")
    public ResponseWrapper getYjCompanyPage(@RequestBody CompanyQueryVO companyVO,@PathVariable("pageNum")Integer pageNum,@PathVariable("pageSize") Integer pageSize) {
		try{
		    PageInfo<CompanyVO> pageInfos = new PageInfo<CompanyVO>(companyService.getYjCompanyPage(companyVO,pageNum,pageSize));
			List<CompanyVO> companyList = companyService.getYjCompanyList(companyVO);
			pageInfos.setTotal(companyList.size());
            return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), pageInfos);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
    }

	@PutMapping(value = "/update/sfba")
	@ApiOperation(value = "企业信息备案审核", notes = "")
	public ResponseWrapper updatesSfba(@RequestParam(value="sfba") Integer sfba,
											@RequestParam(value="id") Integer id,@RequestParam(value = "审核意见",required = false) String shyj) {
		try {
			if (sfba == null || id == null) {
				return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "有必传参数为空", null);
			}
			Integer i = companyService.updatesSfba(id, sfba, shyj);
			if (i > 0) {
				return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), "审核成功");
			}else {
				return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), "审核失败，请联系管理员");
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), "服务错误，请联系管理员");
		}
	}

	@PostMapping(value = "/echarts/sgzgBar")
	@ApiOperation(value = "收购资格柱状图", notes = "")
	public ResponseWrapper sgzgBar(@RequestBody SgzgBarVO sgzgBarVO){
		if(sgzgBarVO.getYxDate()!=null){
			SimpleDateFormat sdf=new SimpleDateFormat("yyyyMM");
			SimpleDateFormat sdfYyyyMMdd=new SimpleDateFormat("yyyyMMdd");
			String str =sdf.format(sgzgBarVO.getYxDate());

			String nowStr= sdf.format(new Date());
			if(nowStr.equals(str)){
				sgzgBarVO.setYxDateNum(Integer.parseInt(sdfYyyyMMdd.format(new Date())));
			}else{
				Calendar calendar=Calendar.getInstance();
				calendar.setTime(sgzgBarVO.getYxDate());
				calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
				sgzgBarVO.setYxDateNum(Integer.parseInt(sdfYyyyMMdd.format(calendar.getTime())));
			}
		}
		return companyService.sgzgBar(sgzgBarVO);
	}

	@PostMapping(value = "/echarts/sgzgLine")
	@ApiOperation(value = "收购资格折线图", notes = "")
	public ResponseWrapper sgzgLine(@RequestBody SgzgLineVO sgzgLineVO) throws ParseException {
		Calendar calendar=Calendar.getInstance();
		int year= calendar.get(Calendar.YEAR);
		int month= calendar.get(Calendar.MONTH);

		if(sgzgLineVO.getYearStart()!=null && sgzgLineVO.getYearEnd()!=null){
			Date startTime;
			Date endTime;

			calendar.set(Calendar.YEAR, sgzgLineVO.getYearStart());

			if(sgzgLineVO.getMonthStart()!=null && sgzgLineVO.getMonthEnd()!=null){
				calendar.set(Calendar.MONTH, sgzgLineVO.getMonthStart()-1);
				calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
				startTime= calendar.getTime();

				if(sgzgLineVO.getYearEnd().intValue()>year
						||sgzgLineVO.getYearEnd().intValue()==year
						&& (sgzgLineVO.getMonthEnd().intValue()-1)==month){
					calendar.setTime(new Date());
				} else{
					calendar.set(Calendar.YEAR, sgzgLineVO.getYearEnd());
					calendar.set(Calendar.MONTH, sgzgLineVO.getMonthEnd()-1);
					calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
				}
				calendar.set(Calendar.HOUR_OF_DAY, 23);
				calendar.set(Calendar.MINUTE, 59);
				calendar.set(Calendar.SECOND, 59);
				endTime=calendar.getTime();
			}else{
				if(year== sgzgLineVO.getYearStart()){
					calendar.setTime(new Date());
				}else{
					calendar.set(Calendar.MONTH, 11);
					calendar.set(Calendar.DAY_OF_MONTH, 31);
				}
				startTime= calendar.getTime();
				if(sgzgLineVO.getYearEnd().intValue()>=year){
					calendar.setTime(new Date());
				} else{
					calendar.set(Calendar.YEAR, sgzgLineVO.getYearEnd());
					calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
					if(sgzgLineVO.getMonthEnd()!=null){
						calendar.set(Calendar.MONTH, sgzgLineVO.getMonthEnd()-1);
					}else{
						calendar.set(Calendar.DAY_OF_MONTH, 11);
					}
				}
				calendar.set(Calendar.HOUR_OF_DAY, 23);
				calendar.set(Calendar.MINUTE, 59);
				calendar.set(Calendar.SECOND, 59);
				endTime=calendar.getTime();
			}
			sgzgLineVO.setStartTime(startTime);
			sgzgLineVO.setEndTime(endTime);
			return companyService.sgzgLine(sgzgLineVO);
		}else{
			return ResponseWrapper.fail("年份是必填项");
		}
	}

	@ApiOperation(value = "企业信息表---企业信息表---根据条件导出数据", notes = "企业信息表---")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "fields", value = "下载的字段:,分隔属性名-分隔指定中文名,如name-姓名, age-年龄", dataType = "String", paramType = "header")
			,@ApiImplicitParam(name = "tyshxydm", value = "无字段注释 #<唯一>", dataType = "String", paramType = "header")
			,@ApiImplicitParam(name = "id", value = "无字段注释 #<主键><唯一><检索><非空>", dataType = "String", paramType = "header")
			,@ApiImplicitParam(name = "qymc", value = "无字段注释 #<检索>", dataType = "String", paramType = "header")
			,@ApiImplicitParam(name = "qybm", value = "无字段注释 #<检索>", dataType = "String", paramType = "header")
			,@ApiImplicitParam(name = "sfjysgzg", value = "无字段注释 #<检索>", dataType = "int", paramType = "header")
			,@ApiImplicitParam(name = "qyzt", value = "无字段注释 #<检索>", dataType = "int", paramType = "header")
			,@ApiImplicitParam(name = "sslsxzglbm", value = "无字段注释 #<检索>", dataType = "String", paramType = "header")
			,@ApiImplicitParam(name = "qyjgdm", value = "无字段注释 #<检索>", dataType = "String", paramType = "header")
			,@ApiImplicitParam(name = "zzjgdm", value = "无字段注释 #<检索>", dataType = "String", paramType = "header")
			,@ApiImplicitParam(name = "dwdm", value = "无字段注释 #<检索>", dataType = "String", paramType = "header")
			,@ApiImplicitParam(name = "qyxz", value = "无字段注释 #<检索>", dataType = "String", paramType = "header")
			,@ApiImplicitParam(name = "qyzyyw", value = "无字段注释 #<检索>", dataType = "String", paramType = "header")
			,@ApiImplicitParam(name = "sfba", value = "无字段注释 #<检索>", dataType = "Double", paramType = "header")
			,@ApiImplicitParam(name = "sgzt", value = "无字段注释 #<检索>", dataType = "String", paramType = "header")
	})
	@RequestMapping("/company/exportByEntity")
	public void exportByEntity(HttpServletRequest request, HttpServletResponse response
			, @ModelAttribute CompanyQueryVO companyVO
			, @RequestParam(value= "fields", required = false) String fields) throws IOException {
		List<CompanyVO> companyList= companyService.exportByEntityResult(companyVO);
		List dataList = JsonUtils.parseList(
				JsonUtils.serialize(companyList), Map.class);
		//fileName导出文件名
		String fileName= "企业信息表---导出.xls";
		//sheetName表格名
		String sheetName= "企业信息表---数据";
		//headMap表头Map, key为属性名, value为展示名,根据实际情况修改
		LinkedHashMap<String, String> headMap= new LinkedHashMap();
		FieldUtil.getPoweredOrderedFields(headMap, new CompanyVO(), new BaseEntity());
		if(StringUtils.isNotEmpty(fields)){
			FieldUtil.resloveImportFields(fields, headMap);
		}
		JxlModelExcelUtil.exportExcel(request, response, fileName, dataList, sheetName, headMap);
	}

	@ApiOperation(value = "企业信息表---企业信息表---根据条件导入数据   multipart/form-data", notes = "企业信息表---")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "file", value = "文件对象集合,请求必须设置multipart/form-data", dataType = "String", paramType = "header")
			,@ApiImplicitParam(name = "model", value = "user对象,可无如有此属性则必须设置contentTpe= application/json", dataType = "String", paramType = "header")
			,@ApiImplicitParam(name = "config", value = "config对象,上传设置,可无如有此属性则必须设置contentTpe= application/json", dataType = "String", paramType = "header")
	})
	@PostMapping(value= "/company/importByEntity", headers= "content-type= multipart/form-data", consumes= "multipart/*")
	public ResponseWrapper importByEntity(HttpServletRequest request, HttpServletResponse response
			,@RequestParam(value= "file", required = false) List<MultipartFile> fileList
			,@RequestPart(value = "model", required = false) CompanyVO companyShowVO
			,@RequestPart(value = "config", required = false) ImportConfigVO importConfigVO) throws IOException {
		CompanyVO companyVO= JsonUtils.parse(
				JsonUtils.serialize(companyShowVO), CompanyVO.class);
		if(fileList== null || fileList.size()== 0){
			return ResponseWrapper.fail("无文件数据");
		} else{
			return companyService.importByEntityResult(companyVO, fileList, importConfigVO);
		}
	}

	@PutMapping(value = "/saveCompany")
	@ApiOperation(value = "保存企业信息", notes = "参数：保存企业信息 models")
	public ResponseWrapper saveCompany(@RequestBody CompanyVO companyVO) {
		try {
			return companyService.saveCompany(companyVO);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
	}

	@PostMapping(value = "/updateByEntitySelective")
	@ApiOperation(value = "更新企业信息")
	public ResponseWrapper updateByEntitySelective(@RequestBody CompanyVO companyVO) {
		try{
			Integer i = companyService.updateByEntitySelective(companyVO);
			if (i > 0) {
				return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), "更新成功");
			}else {
				return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), "未更新数据，请联系管理员");
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
		return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
	}
}
