package com.yeejoin.precontrol.controller.publics;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
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.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
import com.yeejoin.precontrol.common.entity.CompanyDepartment;
import com.yeejoin.precontrol.common.entity.CompanyQualifications;
import com.yeejoin.precontrol.common.entity.Districts;
import com.yeejoin.precontrol.common.param.CompanyParam;
import com.yeejoin.precontrol.common.param.PersonParam;
import com.yeejoin.precontrol.common.service.ICompanyDepartmentService;
import com.yeejoin.precontrol.common.service.ICompanyQualificationService;
import com.yeejoin.precontrol.common.service.ICompanyService;
import com.yeejoin.precontrol.common.service.IDistrictsService;
import com.yeejoin.precontrol.common.service.IPersonService;
import com.yeejoin.precontrol.common.utils.CommonResponseUtil;
import com.yeejoin.precontrol.common.utils.FileHelper;
import com.yeejoin.precontrol.common.vo.CompanyExcelVo;
import com.yeejoin.precontrol.common.vo.PersonExcelVo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * @author DELL
 */
@RestController
@RequestMapping(value = "/api/excel")
@Api(tags = "导入导出excel")
public class ExcelController extends BaseController {

	private final Logger logger = LoggerFactory.getLogger(ExcelController.class);

	@Autowired
	private ICompanyService companyService;

	@Autowired
	private IPersonService personService;

	@Autowired
	ICompanyQualificationService iCompanyQualificationService;

	@Autowired
	ICompanyDepartmentService iCompanyDepartmentService;

	@Autowired
	IDistrictsService iDistrictsService;

	@ApiOperation(value = "导入", notes = "导入")
	@PostMapping(value = "/import/{modeName}")
	public ResponseModel importFireEquipment(@RequestPart("file") MultipartFile file,
			@ApiParam(value = "导入资源类型 （person：人员；company：公司）", required = true) @PathVariable("modeName") String modeName) {
		String fileName = file.getOriginalFilename();
		if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
			if ("person".equals(modeName)) {
				List<PersonExcelVo> list = FileHelper.importExcel(file, 1, 1, PersonExcelVo.class);
				personService.importExcel(list);
			}
			return CommonResponseUtil.success();
		} else {
			return CommonResponseUtil.failure("文件格式错误");
		}
	}

	@ApiOperation(value = "导出数据", notes = "导出数据")
	@PostMapping(value = "/export")
	public void export(HttpServletResponse response,
			@ApiParam(value = "data：导出数据；model：导出模板", required = true) @RequestParam String exportType,
			@ApiParam(value = "person：人员；company：公司", required = true) @RequestParam String modelName,
			@ApiParam(value = "查询条件") @RequestBody(required = false) Map<String, Object> paramsMap)
			throws UnsupportedEncodingException {
		String fileName = UUID.randomUUID().toString() + ".xls";
		String title = "人员";
		Class cls = null;
		if ("person".equals(modelName)) {
			title = "人员";
			fileName = java.net.URLEncoder.encode("人员信息表", "UTF-8") + ".xls";
			cls = PersonExcelVo.class;
		} else if ("company".equals(modelName)) {
			title = "分包商";
			fileName = java.net.URLEncoder.encode("分包商信息表", "UTF-8") + ".xls";
			cls = CompanyExcelVo.class;
		}
		if (cls != null) {
			List<?> list = Lists.newArrayList();
			if ("data".equals(exportType)) {
				if ("person".equals(modelName)) {
					PersonParam param = JSON.parseObject(JSON.toJSONString(paramsMap), PersonParam.class);
					List<PersonExcelVo> exportExcel = personService.exportExcel(param);
					// 过滤重复数据
					List<PersonExcelVo> data = new ArrayList<>();
					Map<Long, Object> idMap = new HashMap<>();
					for (PersonExcelVo personExcelVo : exportExcel) {
						if (!idMap.containsKey(personExcelVo.getId())) {
//							// 用工来源所在地
//							if (StringUtils.isNotBlank(personExcelVo.getEmployPlace())) {
//								personExcelVo.setEmployPlaceName(getPlaceName(personExcelVo.getEmployPlace()));
//							}
//							// 籍贯
//							if (StringUtils.isNotBlank(personExcelVo.getNativePlace())) {
//								personExcelVo.setNativePlaceName(getPlaceName(personExcelVo.getNativePlace()));
//							}
							// 过滤无效合同
//							if (personExcelVo.getUseful()==1) {
//								personExcelVo.setNativePlaceName(getPlaceName(personExcelVo.getNativePlace()));
//							}
						
							if (personExcelVo.getDepartmentId() != null && personExcelVo.getDepartmentName() == null) {
								CompanyDepartment companyDepartment = iCompanyDepartmentService
										.getById(personExcelVo.getDepartmentId());
								if (companyDepartment != null) {
									personExcelVo.setDepartmentName(
											companyDepartment != null ? companyDepartment.getName() : null);
								} else {
									DepartmentModel department = getDepartment(
											Long.valueOf(personExcelVo.getDepartmentId()));
									personExcelVo.setDepartmentName(
											department != null ? department.getDepartmentName() : null);
								}
							}
							// 保障期限
							if (personExcelVo.getInsurePeriodStart() != null
									&& personExcelVo.getInsurePeriodEnd() != null) {
								personExcelVo.setInsurePeriod(personExcelVo.getInsurePeriodStart().replace("-", "/")
										+ "~" + personExcelVo.getInsurePeriodEnd().replace("-", "/"));
							}

							data.add(personExcelVo);
							idMap.put(personExcelVo.getId(), "");
						}
					}
					list = data;
				} else if ("company".equals(modelName)) {
					CompanyParam param = JSON.parseObject(JSON.toJSONString(paramsMap), CompanyParam.class);
					List<CompanyExcelVo> exportExcel = companyService.exportExcel(param);
					// 资质表有多个数据 只取一个
					for (CompanyExcelVo companyExcelVo : exportExcel) {
						Long id = companyExcelVo.getId();
						CompanyQualifications companyExceptions = iCompanyQualificationService
								.getOne(new LambdaQueryWrapper<CompanyQualifications>()
										.eq(CompanyQualifications::getCompanyId, id)
										.eq(CompanyQualifications::getOrders, 0L));
						if (companyExceptions != null) {
							companyExcelVo.setCertificateName(companyExceptions.getCertificateName());
							companyExcelVo.setCertificateNumber(companyExceptions.getCertificateNumber());
							companyExcelVo.setExpireToDate(companyExceptions.getExpireToDate());
							companyExcelVo.setIssuingAuthority(companyExceptions.getIssuingAuthority());
						}

						if (StringUtils.isNotBlank(companyExcelVo.getRegion())) {
							String[] split = companyExcelVo.getRegion().split(",");
							companyExcelVo.setRegionName(getPlaceName(companyExcelVo.getRegion()));
						}

					}
					list = exportExcel;
				}
			}
			FileHelper.exportExcel(list, title, title, cls, fileName, response);
		}
	}

	private String getPlaceName(String key) {
		String[] split = key.split(",");
		if (split.length == 0) {
			return "";
		}
		LinkedList<Long> collect = Arrays.stream(split).map(Long::parseLong)
				.collect(Collectors.toCollection(LinkedList::new));
		Collection<Districts> districts = iDistrictsService.listByIds(collect);
		StringBuffer districtsName = new StringBuffer("");
		districts.forEach(districts1 -> districtsName.append(districts1.getExtName()).append(","));
		if (districtsName.length() > 0) {
			districtsName.deleteCharAt(districtsName.length() - 1);
		}
		return districtsName.toString();
	}
}
