package com.unis.base.app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.netflix.discovery.converters.Auto;
import com.unis.base.app.feign.DictFeign;
import com.unis.base.app.feign.MyuserFeign;
import com.unis.base.app.feign.UserFeign;
import com.unis.base.app.service.CompanyService;
import com.unis.base.app.service.PushService;
import com.unis.base.client.CompanyFeign;
import com.unis.base.common.vo.*;
import com.unis.common.utils.JsonUtils;
import com.unis.common.utils.POI4Util;
import com.unis.common.utils.ResponseWrapper;
import com.unis.common.vo.poi.Column;
import com.unis.common.vo.poi.Line;
import com.unis.user.common.vo.org.OrgainzeVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


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

	@Autowired
	private CompanyService companyService;

	@Autowired
	private CompanyFeign companyFeign;

	@Autowired
	private DictFeign dictFeign;

	@Autowired
	private MyuserFeign myuserFeign;

	@Autowired
	private UserFeign userFeign;

	@Autowired
	private PushService pushService;

	@ApiOperation(value = "获取企业信息列表", notes = "参数：社会统一行政编码，企业名称，企业类型，企业性质，法定代表人，企业状态")
	@PostMapping(value = "/companyList")
	public ResponseWrapper getCompanyList(@RequestBody CompanyQueryVO companyQueryVO) {
		return companyFeign.getCompanyList(companyQueryVO);
	}

	@ApiOperation(value = "分页获取企业信息列表", notes = "参数：社会统一行政编码，企业名称，企业类型，企业性质，法定代表人")
	@PostMapping(value = "/companyPage/{pageNum}/{pageSize}")
	public ResponseWrapper getCompanyPage(@RequestBody CompanyQueryVO companyVO,@PathVariable("pageNum")Integer pageNum,@PathVariable("pageSize") Integer pageSize) {
		return companyFeign.getCompanyPage(companyVO,pageNum,pageSize);
	}

	@PostMapping(value = "/company")
	@ApiOperation(value = "新增企业信息", notes = "参数：统一社会信用代码，企业名称")
    public ResponseWrapper insert(@RequestBody CompanyVO companyVO) {
		companyVO.buildInsertData();
        return companyService.insert(companyVO);
    }

	@PutMapping(value = "/company")
	@ApiOperation(value = "更新企业信息", notes = "参数：企业统一社会信用代码")
    public ResponseWrapper update(@RequestBody CompanyVO companyVO) {
		companyVO.buildUpdateData();
		ResponseWrapper responseWrapper = companyService.update(companyVO);
		if(responseWrapper.isSuccess()) {
			if(5 == companyVO.getSfba()) { // 审核通过，下发库级
				ResponseWrapper result = companyFeign.getCompanyBytyshxydm(companyVO.getTyshxydm());
				CompanyVO vo = JsonUtils.parse(JsonUtils.serialize(result.getData()),CompanyVO.class);
				JSONObject obj = (JSONObject) JSONObject.toJSON(vo);
				String sendResult = pushService.push(obj,"companyApi");
				if(StringUtils.isNotEmpty(sendResult)) {
					companyVO = new CompanyVO();
					companyVO.setId(vo.getId());
					companyVO.setSendResult(sendResult);
					companyFeign.updateByEntitySelective(companyVO);
				}
			}
		}
		return responseWrapper;
    }

	@GetMapping(value="/company/{tyshxydm}")
	@ApiOperation(value = "根据统一社会行政代码获取企业信息", notes = "参数：社会行政代码")
	public ResponseWrapper getCompanyBytyshxydm(@PathVariable("tyshxydm") String tyshxydm) {
        return companyService.getCompanyBytyshxydm(tyshxydm);
    }

	@DeleteMapping(value="/company/{tyshxydm}")
	@ApiOperation(value = "根据统一社会行政代码删除企业信息", notes = "参数：社会行政代码")
	public ResponseWrapper delete(@PathVariable("tyshxydm") String tyshxydm) {
        return companyService.delete(tyshxydm);
    }

	@PostMapping(value = "/companyFiling")
	@ApiOperation(value = "企业信息-企业备案", notes = "参数：备案信息")
	public ResponseWrapper updateFilingStatus(@RequestBody CompanyRecordsVO companyRecordsVO) {
		return companyService.updateFilingStatus(companyRecordsVO);
	}

	/**
	 * 企业信息-区域图表
	 * @param qyszqy
	 * @param sslsxzglbm
	 * @param qyszqybh
	 * @return
	 */
	/*@PostMapping(value = "/company/registerAreaCharts")
	@ApiOperation(value = "企业信息-区域图表", notes = "")
	public ResponseWrapper registerAreaCharts(
			@RequestParam(value = "qyszqy",required = false) String qyszqy
			,@RequestParam(value = "sslsxzglbm",required = false) String sslsxzglbm
			,@RequestParam(value = "qyszqybh",required = false) String qyszqybh){
		return companyFeign.registerAreaCharts(qyszqy,sslsxzglbm,qyszqybh);
	}

	*//**
	 * 企业信息-企业列表
	 * @param companyVO
	 * @return
	 *//*
	@PostMapping(value = "/company/selectByEntity")
	@ApiOperation(value = "企业信息-区域图表-详情", notes = "")
	public ResponseWrapper selectByEntity(@RequestBody CompanyVO companyVO){
		return companyFeign.selectByEntity(companyVO);
	}

	*//**
	 * 企业信息-企业列表
	 * @return
	 *//*
	@PostMapping(value = "/company/selectPageByEntity")
	@ApiOperation(value = "企业信息-区域图表-详情", notes = "")
	public ResponseWrapper selectPageByEntity(@RequestBody CompanyVO companyVO
			,@RequestParam(value = "pageNum", defaultValue = "1") int pageNum
			,@RequestParam(value ="pageSize", defaultValue = "10") int pageSize){
		return companyFeign.selectPageByEntity(companyVO,pageNum,pageSize);
	}*/

	@ApiOperation(value = "企业信息--导入")
	@PostMapping(value = "/impCompany")
	public ResponseWrapper impContract(@RequestPart(value = "file") MultipartFile file) {

		Map<String, Object> map;
		int success = 0;
		int fail = 0;
		try {
			List<String> columns = new ArrayList<String>();
			Field[] declaredFields = CompanyVO.class.getDeclaredFields();
			for (Field field : declaredFields) {
				System.out.println(field.getName());
				columns.add(field.getName());
			}
			map = POI4Util.uploadExcel(file, columns);
			Integer state = Integer.valueOf(map.get("state")+"");
			if(state == 1) {
				List<Line> lines = (List<Line>) map.get("lines");
				for (int i = 0; i < lines.size(); i++) {
					Line line = lines.get(i);
					List<Column> columnsL = line.getColumns();
					CompanyVO vo = new CompanyVO();
					if (!"".equals(columnsL.get(0).getValue()) && columnsL.get(0).getValue() != null) {
						vo.setQymc(columnsL.get(0).getValue().toString());
					} else {
						return ResponseWrapper.error("企业名称不能为空");
					}
					if (!"".equals(columnsL.get(1).getValue()) && columnsL.get(1).getValue() != null) {
						vo.setTyshxydm(columnsL.get(1).getValue()+"");
					} else {
						return ResponseWrapper.error("统一社会信用代码不能为空");
					}
					if (!"".equals(columnsL.get(2).getValue()) && columnsL.get(2).getValue() != null) {
						vo.setDwdm(columnsL.get(2).getValue()+"");
					} else {
						return ResponseWrapper.error("单位代码不能为空");
					}
					if (!"".equals(columnsL.get(3).getValue()) && columnsL.get(3).getValue() != null) {
						String dwlx = columnsL.get(3).getValue()+"";
						if("应急".equals(dwlx)) {
							dwlx = "1";
						} else if("仓储".equals(dwlx)) {
							dwlx = "2";
						} else if("加工".equals(dwlx)) {
							dwlx = "3";
						} else if("物流".equals(dwlx)) {
							dwlx = "4";
						} else if("配送".equals(dwlx)) {
							dwlx = "5";
						}
						vo.setDwlx(dwlx);
					} else {
						return ResponseWrapper.error("单位类型不能为空");
					}
					if (!"".equals(columnsL.get(4).getValue()) && columnsL.get(4).getValue() != null) {
						vo.setQyxz(columnsL.get(4).getValue()+"");
					} else {
						return ResponseWrapper.error("单位性质不能为空");
					}
					if (!"".equals(columnsL.get(5).getValue()) && columnsL.get(5).getValue() != null) {
						ResponseWrapper data = myuserFeign.getProvinByAreaName(columnsL.get(5).getValue().toString());
						Object resultObj = data.getData();
						if (data.isSuccess() && !ObjectUtils.isEmpty(resultObj)) {
							JSONArray array = JSONArray.parseArray(JsonUtils.serialize(resultObj));
							if(array.size() > 0) {
								String provinCode = array.getJSONObject(0).getString("provinCode");
								vo.setTxprovince(provinCode);
							}
						} else {
							return ResponseWrapper.error("注册地省有误");
						}
					} else {
						return ResponseWrapper.error("所在地省不能为空");
					}
					if (!"".equals(columnsL.get(6).getValue()) && columnsL.get(6).getValue() != null) {
						ResponseWrapper data = myuserFeign.getCityByAreaName(columnsL.get(6).getValue().toString());
						Object resultObj = data.getData();
						if (data.isSuccess() && !ObjectUtils.isEmpty(resultObj)) {
							JSONArray array = JSONArray.parseArray(JsonUtils.serialize(resultObj));
							if (array.size() > 0) {
								String cityCode = array.getJSONObject(0).getString("cityCode");
								if(StringUtils.isNotBlank(cityCode)) {
									vo.setTxcity(cityCode);
								} else {
									String countyCode = array.getJSONObject(0).getString("countyCode");
									if(StringUtils.isNotBlank(countyCode)) {
										vo.setTxcity(countyCode);
									}
								}

							}
						}
					} else {
						return ResponseWrapper.error("所在地市不能为空");
					}
					if (!"".equals(columnsL.get(7).getValue()) && columnsL.get(7).getValue() != null) {
						vo.setQytxdz(columnsL.get(7).getValue()+"");
					} else {
						return ResponseWrapper.error("所在地详细地址不能为空");
					}
					if (!"".equals(columnsL.get(8).getValue()) && columnsL.get(8).getValue() != null) {
						vo.setFddbr(columnsL.get(8).getValue()+"");
					} else {
						return ResponseWrapper.error("法定代表人不能为空");
					}
					if (!"".equals(columnsL.get(9).getValue()) && columnsL.get(9).getValue() != null) {
						vo.setFrsfzh(columnsL.get(9).getValue()+"");
					} else {
						return ResponseWrapper.error("法人身份证号不能为空");
					}
					if (!"".equals(columnsL.get(10).getValue()) && columnsL.get(10).getValue() != null) {
						vo.setFrsjh(columnsL.get(10).getValue()+"");
					} else {
						return ResponseWrapper.error("手机不能为空");
					}
					if (!"".equals(columnsL.get(11).getValue()) && columnsL.get(11).getValue() != null) {
						vo.setLxdh(columnsL.get(11).getValue()+"");
					} else {
						return ResponseWrapper.error("电话不能为空");
					}
					if (!"".equals(columnsL.get(12).getValue()) && columnsL.get(12).getValue() != null) {
						vo.setQyczhm(columnsL.get(12).getValue()+"");
					} else {
						return ResponseWrapper.error("传真不能为空");
					}
					if (!"".equals(columnsL.get(13).getValue()) && columnsL.get(13).getValue() != null) {
						vo.setQyjd(columnsL.get(13).getValue()+"");
					} else {
						return ResponseWrapper.error("经度不能为空");
					}
					if (!"".equals(columnsL.get(14).getValue()) && columnsL.get(14).getValue() != null) {
						vo.setQywd(columnsL.get(14).getValue()+"");
					} else {
						return ResponseWrapper.error("纬度不能为空");
					}
					if (!"".equals(columnsL.get(15).getValue()) && columnsL.get(15).getValue() != null) {
						vo.setZdmj(new BigDecimal(columnsL.get(15).getValue()+""));
					} else {
						return ResponseWrapper.error("占地面积不能为空");
					}
					if (!"".equals(columnsL.get(16).getValue()) && columnsL.get(16).getValue() != null) {
						vo.setZcr(new BigDecimal(columnsL.get(16).getValue()+""));
					} else {
						return ResponseWrapper.error("总仓容不能为空");
					}
					if (!"".equals(columnsL.get(17).getValue()) && columnsL.get(17).getValue() != null) {
						vo.setGr(new BigDecimal(columnsL.get(17).getValue()+""));
					} else {
						return ResponseWrapper.error("总罐容不能为空");
					}
					if (!"".equals(columnsL.get(18).getValue()) && columnsL.get(18).getValue() != null) {
						String qyzyyw=columnsL.get(18).getValue()+"";
						String[] arr = qyzyyw.split("，");
						StringBuffer qyzyywSb = new StringBuffer();
						for (String str:arr) {
							if(qyzyywSb.length()<=0) {
								qyzyywSb.append("'"+str+"'");
							} else {
								qyzyywSb.append(",");
								qyzyywSb.append("'"+str+"'");
							}
						}
						ResponseWrapper data = dictFeign.getDataDictionaryByGroupIdAndInDictName("43439",qyzyywSb.toString());
						Object resultObj = data.getData();
						if (data.isSuccess() && !ObjectUtils.isEmpty(resultObj)) {
							vo.setQyzyyw(data.getData().toString());
						} else {
							return ResponseWrapper.error("单位主营业务有误");
						}
					} else {
						return ResponseWrapper.error("单位主营业务不能为空");
					}
					if (!"".equals(columnsL.get(19).getValue()) && columnsL.get(19).getValue() != null) {
						String qyType = columnsL.get(19).getValue().toString();
						String[] arr = qyType.split("，");
						StringBuffer qyTypeSb = new StringBuffer();
						for (String str:arr) {
							if(qyTypeSb.length()<=0) {
								qyTypeSb.append("'"+str+"'");
							} else {
								qyTypeSb.append(",");
								qyTypeSb.append("'"+str+"'");
							}
						}
						ResponseWrapper data = dictFeign.getDataDictionaryByGroupIdAndInDictName("QYLX",qyTypeSb.toString());
						Object resultObj = data.getData();
						if (data.isSuccess() && !ObjectUtils.isEmpty(resultObj)) {
							List<TzQylxVO> tzQylxVOList = new ArrayList<>();
							vo.setQylx(data.getData().toString().split("@"));
							String[] result = data.getData().toString().split(",");
							for (String str:result) {
								TzQylxVO tzQylxVO = new TzQylxVO();
								tzQylxVO.setQylxbh(str);
								tzQylxVOList.add(tzQylxVO);
							}
							vo.setTzQylxVOList(tzQylxVOList);
						} else {
							return ResponseWrapper.error("企业类型有误");
						}
					} else {
						return ResponseWrapper.error("企业类型不能为空");
					}
					if (!"".equals(columnsL.get(20).getValue()) && columnsL.get(20).getValue() != null) {
						vo.setQycj(columnsL.get(20).getValue()+"");
					} else {
						return ResponseWrapper.error("企业层级不能为空");
					}
					if (!"".equals(columnsL.get(21).getValue()) && columnsL.get(21).getValue() != null) {
						vo.setXsqygs(Integer.valueOf(columnsL.get(21).getValue().toString()));
					} else {
						return ResponseWrapper.error("下属企业个数不能为空");
					}
					if (!"".equals(columnsL.get(22).getValue()) && columnsL.get(22).getValue() != null) {
						ResponseWrapper data = myuserFeign.getProvinByAreaName(columnsL.get(22).getValue().toString());
						Object resultObj = data.getData();
						if (data.isSuccess() && !ObjectUtils.isEmpty(resultObj)) {
							JSONArray array = JSONArray.parseArray(JsonUtils.serialize(resultObj));
							if(array.size() > 0) {
								String provinCode = array.getJSONObject(0).getString("provinCode");
								vo.setZcprovince(provinCode);
							}
						} else {
							return ResponseWrapper.error("注册地省有误");
						}
					} else {
						return ResponseWrapper.error("注册地省不能为空");
					}
					if (!"".equals(columnsL.get(23).getValue()) && columnsL.get(23).getValue() != null) {
						ResponseWrapper data = myuserFeign.getCityByAreaName(columnsL.get(23).getValue().toString());
						Object resultObj = data.getData();
						if (data.isSuccess() && !ObjectUtils.isEmpty(resultObj)) {
							JSONArray array = JSONArray.parseArray(JsonUtils.serialize(resultObj));
							if (array.size() > 0) {
								String cityCode = array.getJSONObject(0).getString("cityCode");
								if(StringUtils.isNotBlank(cityCode)) {
									vo.setZccity(cityCode);
								} else {
									String countyCode = array.getJSONObject(0).getString("countyCode");
									if(StringUtils.isNotBlank(countyCode)) {
										vo.setZccity(countyCode);
									}
								}
							}
						}
					} else {
						return ResponseWrapper.error("注册地市不能为空");
					}
					if (!"".equals(columnsL.get(24).getValue()) && columnsL.get(24).getValue() != null) {
						vo.setQygszcd(columnsL.get(24).getValue()+"");
					} else {
						return ResponseWrapper.error("注册地详细地址不能为空");
					}
					if (!"".equals(columnsL.get(25).getValue()) && columnsL.get(25).getValue() != null) {
						String rtzt = columnsL.get(25).getValue().toString();
						if(rtzt.equals("启用")) {
							vo.setRtzt(1);
						} else {
							vo.setRtzt(0);
						}
					} else {
						return ResponseWrapper.error("入统状态不能为空");
					}
					if (!"".equals(columnsL.get(26).getValue()) && columnsL.get(26).getValue() != null) {
						String sslsxzglbm = columnsL.get(26).getValue()+"";
						ResponseWrapper result = userFeign.findByOrgNameAndParentCode(sslsxzglbm,"LS001");
						Object resultObj = result.getData();
						if (result.isSuccess() && !ObjectUtils.isEmpty(resultObj)) {
							OrgainzeVO orgainzeVO = JSON.parseObject(JSON.toJSONString(resultObj), OrgainzeVO.class);
							if (orgainzeVO != null) {
								vo.setSslsxzglbm(orgainzeVO.getOrgCode());
							}
						}
					} else {
						return ResponseWrapper.error("所属粮食行政管理部门不能为空");
					}
					if (!"".equals(columnsL.get(27).getValue()) && columnsL.get(27).getValue() != null) {
						String sslsxzglbm = columnsL.get(27).getValue().toString();
						if(sslsxzglbm.equals("是")) {
							vo.setSfzdzgqy("1");
						} else {
							vo.setSfzdzgqy("0");
						}
					} else {
						return ResponseWrapper.error("是否最低最高企业不能为空");
					}
					if (!"".equals(columnsL.get(28).getValue()) && columnsL.get(28).getValue() != null) {
						vo.setZcze(new BigDecimal(columnsL.get(28).getValue()+""));
					} else {
						return ResponseWrapper.error("资金总额不能为空");
					}
					companyFeign.update(vo);
					success++;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			fail ++ ;
		}
		return ResponseWrapper.success("成功："+success+",失败："+fail);
	}
}
