package com.sifang.modules.insurance.web;

import com.google.common.collect.Maps;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.Service.CustomerEntryService;
import com.sifang.modules.customer.Service.OperatingLeaseService;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.customer.pdf.PdfReport;
import com.sifang.modules.insurance.constants.InsuranceOrderConstants;
import com.sifang.modules.insurance.entity.CrmCustomerEntryInsurance;
import com.sifang.modules.insurance.request.CorrectOrderReq;
import com.sifang.modules.insurance.request.EditInsurantOrderReq;
import com.sifang.modules.insurance.service.CrmCustomerNoSystemEntryInsuranceService;
import com.sifang.modules.insurance.service.CustomerEntryInsuranceService;
import com.sifang.modules.insurance.service.InsuranceListService;
import com.sifang.modules.order.utils.WebPageFunUtils;
import com.sifang.modules.platform.service.AddressService;
import com.sifang.modules.setting.service.MemberService;
import com.sifang.modules.sunshine.SystemSetting.service.TraderService;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sunshine.partnerManagement.service.PartnerService;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.utils.FileUtils;
import com.sifang.modules.sys.util.EntryUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.insurance.InsuranceBizService;
import com.sifang.modules.sys.web.BaseController;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author DQChen
 * @date 2024-01-19 10:15
 */
@Controller
@RequestMapping("${adminPath}/customerEntry/insurance")
public class CustomerEntryInsuranceController extends BaseController {

	@Autowired
	CustomerEntryInsuranceService insuranceService;

	@Autowired
	TraderService traderService;

	@Autowired
	AddressService addressService;

	@Autowired
	MemberService memberService;

	@Autowired
	InsuranceListService insuranceListService;

	@Autowired
	InsuranceBizService insuranceBizService;

	@Autowired
	CustomerEntryService entryService;

	@Autowired
	PartnerService partnerService;

	@Autowired
	OperatingLeaseService operatingLeaseService;

	@Autowired
	CrmCustomerNoSystemEntryInsuranceService noSystemEntryInsuranceService;


	/**
	 * 保险公司列表页面跳转接口
	 */
	@RequestMapping(value = "list")
	public String list(HttpServletRequest request, Model model) {
		User user = UserUtils.getUser();
		model.addAttribute("user", user);
		String traderId = user.getTraderId();
		List<Record> list;
		if (StringUtil.isBlank(traderId)) {
			list = memberService.getProjectLists();
		} else {
			list = memberService.getProjectByTraderLists(traderId);
		}
		//代理商列表
		List<Record> traderList = traderService.getTopTrader();
		model.addAttribute("traderList", traderList);
		List<Record> pros = addressService.getProvinces();
		model.addAttribute("province", pros);
		model.addAttribute("projectList", list);
		model.addAttribute("paterns", partnerService.partnerList());
		return "modules/insurance/customerEntryInsuranceList";
	}

	/**
	 * 保险公司列表页面跳转接口
	 */
	@RequestMapping(value = "renewalList")
	public String renewalList(HttpServletRequest request, Model model) {
		User user = UserUtils.getUser();
		model.addAttribute("user", user);
		String traderId = user.getTraderId();
		List<Record> list;
		if (StringUtil.isBlank(traderId)) {
			list = memberService.getProjectLists();
		} else {
			list = memberService.getProjectByTraderLists(traderId);
		}
		//代理商列表
		List<Record> traderList = traderService.getTopTrader();
		model.addAttribute("traderList", traderList);
		List<Record> pros = addressService.getProvinces();
		model.addAttribute("province", pros);
		model.addAttribute("projectList", list);
		model.addAttribute("paterns", partnerService.partnerList());
		return "modules/insurance/customerEntryInsuranceRenewalList";
	}


	/**
	 * 保险公司信息列表数据
	 */
	@ResponseBody
	@RequestMapping(value = "insuranceData")
	public Object insuranceListData(HttpServletRequest request) {
		LayuiPage layuiPage = new LayuiPage(request);
		insuranceService.list(getParams(request), layuiPage);
		return layuiPage.renderJson();
	}

	@RequestMapping(value = "detail/{id}")
	public String detail(@PathVariable("id") String id, Model model) {
		Record record = insuranceService.selectDetailById(id, null);
		model.addAttribute("insurance", record);
		model.addAttribute("processList", WebPageFunUtils.getOrderProcessDesc(record.getStr("process_detail")));
		return "modules/insurance/insuranceOrderDetail";
	}

	@RequestMapping(value = "renewalDetail/{id}")
	public String renewalDetail(@PathVariable("id") String id, Model model) {
		Record record = insuranceService.selectDetailById(id, null);
		model.addAttribute("insurance", record);
		model.addAttribute("processList", WebPageFunUtils.getOrderProcessDesc(record.getStr("process_detail")));
		return "modules/insurance/insuranceRenewalDetail";
	}


	/**
	 * 批改页面
	 *
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "edit/{id}")
	public String edit(@PathVariable("id") String id, Model model) {
		Record record = insuranceService.selectDetailById(id, "1");
		model.addAttribute("insurance", record);
		model.addAttribute("insuranceList", insuranceListService.insuranceList());
		if (InsuranceOrderConstants.SOURCE_SELF.equals(record.getStr("source"))) {
			return "modules/insurance/editInsuranceOrder";
		}else{
			CustomerEntry entry = entryService.getById(record.getStr("entry_id"));
			model.addAttribute("insuranceSet", insuranceListService.selectDetailById(record.getStr("insurance_id")));
			model.addAttribute("entry", entry);
			model.addAttribute("nowSumMoney", insuranceBizService.calcSumAmount(entry));
			return "modules/insurance/correctOrder";
		}
	}

	/**
	 * 跳转到新增保单页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "toAddPage")
	public String toAddPage(Model model) {
		List<Record> entryS = insuranceService.findEntryForInsurance();
		model.addAttribute("entryS",entryS);
		model.addAttribute("insuranceList", insuranceListService.insuranceList());
		return "modules/insurance/addInsuranceOrder";
	}

	/**
	 * 修改保单(线下保单修改操作)
	 *
	 * @param orderReq
	 * @return
	 */
	@ResponseBody
	@RequestMapping("doEdit")
	public Result doEdit(@RequestBody EditInsurantOrderReq orderReq) {
		return insuranceService.doEdit(orderReq);
	}


	/**
	 * 获取电站列表
	 * @param stationCode
	 * @return
	 */
	@ResponseBody
	@RequestMapping("selectEntryForInsurance/{stationCode}")
	public Object selectEntryForInsurance(@PathVariable("stationCode") String stationCode) {
		List<Record> list = insuranceService.selectEntryForInsurance(stationCode);
		return JsonKit.toJson(list);
	}

	/**
	 * 线下购买保单
	 * @param orderReq
	 * @return
	 */
	@ResponseBody
	@RequestMapping("doAdd")
	public Result doAdd(@RequestBody EditInsurantOrderReq orderReq) {
		return insuranceService.doAdd(orderReq);
	}

	/**
	 * 线上投保订单 批改操作
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping("correctOrder")
	public Result correctOrder(@RequestBody CorrectOrderReq orderReq) {
		Result ret = Result.ok();
		try {
			CrmCustomerEntryInsurance entryInsurance = insuranceService.selectById(orderReq.getId());
			CustomerEntry entry = entryService.getById(entryInsurance.getEntryId());
			return insuranceBizService.endorse(orderReq.getType(), orderReq.getId(), entry);
		} catch (BusinessException e) {
			ret = Result.fail(e.getMessage());
			e.printStackTrace();
		} catch (Exception e) {
			ret = Result.fail("未知错误");
			e.printStackTrace();
		}
		return ret;
	}

	/**
	 * 批量下载
	 * @param insuranceIds
	 * @return
	 */
	@RequestMapping("batchDownload/{insuranceIds}")
	public void batchDownload(@PathVariable("insuranceIds") List<String> insuranceIds, HttpServletResponse response) {
		FileOutputStream outputStream = null;
		String filename = "保单下载.zip";
		String filePath = "";
		try {
			filePath = Files.createTempDirectory("insuranceTmp").toFile().getAbsolutePath() + "/" + filename;
			outputStream = new FileOutputStream(filePath);
			insuranceService.batchDownload(insuranceIds, outputStream);
			EntryUtils.downloadLocal(filename, filePath, response);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			FileUtils.deleteFile(filePath);
		}
	}

	/**
	 * 推送保单
	 * @param id
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/push")
	public Result orderSubmit1(@RequestParam String id) throws IOException {
		CrmCustomerEntryInsurance insurance = insuranceService.get(id);
		CustomerEntry entry = entryService.getById(insurance.getEntryId());
		insuranceBizService.push(entry, null, null, UserUtils.getUser(),"1");
		return Result.ok();
	}

	/**
	 * 推送保单到资方
	 * @param id
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("/pushInsuranceToYueXiu")
	public Object push(@RequestParam String id) {
		CrmCustomerEntryInsurance insurance = insuranceService.get(id);
		CustomerEntry entry = entryService.getById(insurance.getEntryId());
		Result result = new Result();
		try {
			String code = operatingLeaseService.renewalInsurance(insurance,entry);
			if (Objects.equals("200", code)) {
				result.setCode(code);
			} else {
				result.setCode("201");
				result.setErrMsg(code);
			}
			return result;
		} catch (BusinessException ex) {
			return Result.fail(ex.getMessage());
		} catch (Exception ex) {
			return Result.fail("重新推送失败");
		}

	}

	/**
	 * 续保文件上传
	 * @param id
	 * @param downUrl
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/uploadInsuranceFile")
	public Result uploadInsuranceFile(@RequestParam String id,@RequestParam String downUrl) throws IOException {
		Result result = new Result();
		insuranceService.uploadInsuranceFile(id,downUrl);
		result.setOk();
		return result;
	}

	@RequestMapping(value = "toImportInsurance")
	public String toImport() {
		return "modules/insurance/importInsurance";
	}

	@ResponseBody
	@RequestMapping(value = "checkImportInsurance")
	public Object checkImportInsurance(@RequestParam MultipartFile file) throws IOException {
		Map<String, String> params = Maps.newHashMap();
		params.put("extName", StringUtil.getFileExtName(file.getOriginalFilename()));
		Map<String, Object> retMap = insuranceService.checkImportInsurance(params, file.getInputStream());
		return JSONObject.fromObject(retMap);
	}

	@RequestMapping(value = "importInsurance")
	@ResponseBody
	public Object importInsurance(@RequestParam MultipartFile file) throws IOException {
		Map<String, String> params = Maps.newHashMap();
		params.put("fileName", file.getOriginalFilename());
		Map<String, Object> retMap = insuranceService.importInsurance(params, file.getInputStream());
		return retMap;
	}

	/**
	 * 保险公司列表页面跳转接口
	 */
	@RequestMapping(value = "renewalListNoSystem")
	public String renewalNoSystemList(HttpServletRequest request, Model model) {
		User user = UserUtils.getUser();
		model.addAttribute("user", user);
		String traderId = user.getTraderId();
		List<Record> list;
		if (StringUtil.isBlank(traderId)) {
			list = memberService.getProjectLists();
		} else {
			list = memberService.getProjectByTraderLists(traderId);
		}
		//代理商列表
		List<Record> traderList = traderService.getTopTrader();
		model.addAttribute("traderList", traderList);
		List<Record> pros = addressService.getProvinces();
		model.addAttribute("province", pros);
		model.addAttribute("projectList", list);
		model.addAttribute("paterns", partnerService.partnerList());
		return "modules/insurance/customerEntryInsuranceNoSystemRenewalList";
	}

}
