package com.palmnest.webapp.controller.backstage;

import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.DateUtils;
import com.palmnest.application.core.util.LogExceptionStackUtil;
import com.palmnest.model.Element;
import com.palmnest.model.bill.DepositRecord;
import com.palmnest.model.bill.GeneralBills;
import com.palmnest.model.bill.GeneralbillService;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.service.estateserve.GeneralBillsManager;
import com.palmnest.service.property.PropertyManager;
import com.palmnest.webapp.controller.BaseFormController;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 账单控制层
 *
 * @author 金牙
 */

@Controller
@RequestMapping("/admin/bill/*")
public class GeneralBillsController extends BaseFormController {

	@Autowired
	private GeneralBillsManager generalBillsManager;

	@Autowired
	private PropertyManager propertyManager;

	public void initModel(Model model) {
		List<Element> depositRecordStatusGroup = this.getElementGroupManager()
				.getElementsByGroupName("depositRecordStatusGroup");// 状态
		model.addAttribute("depositRecordStatusGroup", depositRecordStatusGroup);
	}

	/**
	 * 分页查询账单列表信息
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/generalBillsPage")
	public ModelAndView generalBillsPage(HttpServletRequest request,
										 HttpServletResponse response) throws Exception {
		Model model = new ExtendedModelMap();
		try {
			initFunctionOperate(request);
			initModel(model);
			String  pageNo    = request.getParameter("pageNo");
			Integer virtualId = null;
			if (StringUtils.isBlank(pageNo)) {
				pageNo = "1";
			}
			String outMonth = request.getParameter("outMonth");
			if (StringUtils.isNotBlank(outMonth)) {
				model.addAttribute("outMonth", outMonth);
			}
			String virtualIdParaMs = request.getParameter("virtualId");
			if (StringUtils.isNotBlank(virtualIdParaMs)) {
				virtualId = Integer.parseInt(virtualIdParaMs);
				model.addAttribute("virtualId", virtualId);
			}
			Page page = generalBillsManager.generalBillsPage(10,
					Integer.parseInt(pageNo), virtualId, outMonth);
			model.addAttribute("page", page);
			model.addAttribute("virtualArchitecture",
					propertyManager.getVirtualArchitectureById(virtualId));
			return new ModelAndView("/admin/bill/generalBillsList", model.asMap());
		} catch (Exception e) {
			LogExceptionStackUtil.LogExceptionStack(e);
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/saveUpdateDepositRecord", method = {
			RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	String saveUpdateDepositRecord(
			HttpServletRequest request) throws Exception {
		JSONObject jsonObject = new JSONObject();
		try {
			String        virtualId     = request.getParameter("virtualId");
			String        status        = request.getParameter("status");
			String        remark        = request.getParameter("remark");
			String        amountFee     = request.getParameter("amountFee");
			DepositRecord depositRecord = new DepositRecord();
			depositRecord.setVirtualId(Integer.parseInt(virtualId));
			depositRecord.setStatus(status);
			depositRecord.setRemark(remark);
			depositRecord.setAmountFee(new BigDecimal(amountFee));
			depositRecord.setCreateTime(new Date());
			depositRecord.setCreator(request.getRemoteUser());
			Map<String, Object> result = generalBillsManager
					.saveUpdateDepositRecord(depositRecord);
			return JSONObject.fromObject(result).toString();
		} catch (Exception e) {
			jsonObject.put("flag", false);
			jsonObject.put("desc", "操作异常！");
			LogExceptionStackUtil.LogExceptionStack(e);
		}
		return jsonObject.toString();
	}

	/**
	 * 根据企业ID查询扣减预存记录信息
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getDepositRecordPage", method = {
			RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	Page getDepositRecordPage(HttpServletRequest request)
			throws Exception {
		JSONObject jsonObject = new JSONObject();
		try {
			String virtualId = request.getParameter("virtualId");
			String pageNo    = request.getParameter("pageNo");
			String pageSize  = request.getParameter("pageSize");
			if (StringUtils.isBlank(pageNo)) {
				pageNo = "1";
			}
			return generalBillsManager.getDepositRecordPage(
					Integer.parseInt(pageSize), Integer.parseInt(pageNo),
					Integer.parseInt(virtualId));
		} catch (Exception e) {
			jsonObject.put("flag", false);
			jsonObject.put("desc", "操作异常！");
			LogExceptionStackUtil.LogExceptionStack(e);
		}
		return null;
	}

	/**
	 * 根据企业ID查询企业余额
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getVirtualArchitecture", method = {
			RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	VirtualArchitecture getVirtualArchitecture(
			HttpServletRequest request) throws Exception {
		JSONObject jsonObject = new JSONObject();
		try {
			String virtualId = request.getParameter("virtualId");
			return propertyManager.getVirtualArchitectureById(Integer
					.parseInt(virtualId));
		} catch (Exception e) {
			jsonObject.put("flag", false);
			jsonObject.put("desc", "操作异常！");
			LogExceptionStackUtil.LogExceptionStack(e);
		}
		return null;
	}

	/**
	 * 跳转编辑账单页面
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/generalBillsEidtView")
	public ModelAndView generalBillsEidtView(HttpServletRequest request)
			throws Exception {
		Model model = new ExtendedModelMap();
		try {
			initFunctionOperate(request);
			String              virtualId           = request.getParameter("virtualId");
			String              generalBillsId      = request.getParameter("generalBillsId");
			VirtualArchitecture virtualArchitecture = propertyManager.getVirtualArchitectureById(Integer.parseInt(virtualId));


			/**
			 * 修正空指针错误
			 * SET SQL_SAFE_UPDATES = 0;
			 * SELECT * FROM super_reception_real.tb_virtualarchitecture where reserveBalance is null;
			 * update super_reception_real.tb_virtualarchitecture set reserveBalance = 0.00 where reserveBalance is null;
			 */
			if (virtualArchitecture.getReserveBalance() == null) {
				virtualArchitecture.setReserveBalance(new BigDecimal(0.00));
			}

			GeneralBills             generalBills           = generalBillsManager.getGeneralBillsById(Integer.parseInt(generalBillsId));// 当前账单信息
			BigDecimal               sumPrice               = generalBillsManager.getArrearsRecord(generalBills.getOutMonth(), Integer.parseInt(virtualId));// 欠费总金额
			BigDecimal               sumOwed                = sumPrice.setScale(2).subtract(generalBills.getTotalFee());// 历史欠费
			BigDecimal               payable                = sumPrice.subtract(virtualArchitecture.getReserveBalance());// 应缴费用
			List<GeneralbillService> generalbillServiceList = generalBillsManager.getGeneralbillServiceList(Integer.parseInt(generalBillsId));

			for (int i = 0; i < generalbillServiceList.size(); i++) {
				generalbillServiceList.get(i).setList(
						generalBillsManager.geteneralBillOrdersList(
								generalbillServiceList.get(i).getBillId(),
								generalbillServiceList.get(i).getServiceCode()));
			}
			List<Element> signingServiceGroup = this.getElementGroupManager().getElementsByGroupName("signingServiceGroup");// 状态
			model.addAttribute("signingServiceGroup", signingServiceGroup);
			model.addAttribute("sumOwed", sumOwed);
			model.addAttribute("startTime", DateUtils.formatDate(generalBills.getStartTime(), "yyyy-MM-dd"));
			model.addAttribute("endTime", DateUtils.formatDate(generalBills.getEndTime(), "yyyy-MM-dd"));
			model.addAttribute("payable", payable);
			model.addAttribute("generalBills", generalBills);
			model.addAttribute("generalbillServiceList", generalbillServiceList);
			model.addAttribute("virtualArchitecture", virtualArchitecture);// 企业信息
			model.addAttribute("generalBillsId", generalBillsId);
			model.addAttribute("virtualId", virtualId);
			return new ModelAndView("/admin/bill/generalBillsEidt", model.asMap());

		} catch (Exception e) {
			e.printStackTrace();
			LogExceptionStackUtil.LogExceptionStack(e);
		}
		return null;
	}

	/**
	 * 根据企业ID和账单ID查询账单信息
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/loadServiceInfo", method = {RequestMethod.GET,
			RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	List<Element> loadServiceInfo(
			HttpServletRequest request) throws Exception {
		try {
			List<Element> signingServiceGroup = this.getElementGroupManager()
					.getElementsByGroupName("signingServiceGroup");// 状态
			return signingServiceGroup;
		} catch (Exception e) {
			LogExceptionStackUtil.LogExceptionStack(e);
		}
		return null;
	}

	/**
	 * 账单保存和编辑
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/saveUpdateGeneralBills", method = {
			RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	Map<String, Object> saveUpdateGeneralBills(
			HttpServletRequest request) throws Exception {
		try {
			String generalBissData  = request.getParameter("generalBissData");
			String delServiceData   = request.getParameter("delServiceData");
			String delOrderData     = request.getParameter("delOrderData");
			String generalBillsDate = request.getParameter("generalBillsDate");
			return generalBillsManager.saveUpdateGeneralBills(generalBissData,
					delServiceData, delOrderData, generalBillsDate,
					request.getRemoteUser());
		} catch (Exception e) {
			LogExceptionStackUtil.LogExceptionStack(e);
		}
		return null;
	}

	/**
	 * 支付状态管理 --欠费账单等费用查询
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryPayBills", method = {RequestMethod.GET,
			RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	Map<String, Object> queryPayBills(
			HttpServletRequest request) throws Exception {
		String virtualId = request.getParameter("virtualId");

		List<GeneralBills> bills = generalBillsManager.getGeneralBillsList(
				Integer.parseInt(virtualId), "0");
		VirtualArchitecture virtual = propertyManager
				.getVirtualArchitectureById(Integer.parseInt(virtualId));
		Map<String, Object> retMap = new HashMap<String, Object>();

		if (!CollectionUtils.isEmpty(bills)) {

			BigDecimal totalFee = new BigDecimal(0.00);
			for (GeneralBills generalBills : bills) {
				totalFee = totalFee.add(generalBills.getTotalFee());
			}
			retMap.put("totalFee", totalFee.toString());
			retMap.put("reserveBalance", virtual.getReserveBalance().toString());
			retMap.put("bills", bills);
		} else {
			retMap.put("dealFlag", "noData");
		}
		return retMap;
	}

	/**
	 * 支付状态管理 --更新
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/billPayStatusUpdate", method = {
			RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	Map<String, String> billPayStatusUpdate(
			HttpServletRequest request) throws Exception {

		String virtualId = request.getParameter("virtualId");
		String billId    = request.getParameter("billId");
		String payFee    = request.getParameter("payFee"); // 实收
		String dedFee    = request.getParameter("dedFee"); // 预存款抵扣
		return generalBillsManager.updateGeneralBillPaystatus(virtualId,
				billId, payFee, dedFee, request.getRemoteUser());
	}

	/**
	 * 账单打印
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/generalBillsPutView")
	public ModelAndView generalBillsPutView(HttpServletRequest request)
			throws Exception {
		Model model = new ExtendedModelMap();
		try {
			initFunctionOperate(request);

			String generalBillsId = request.getParameter("generalBillsId");
			String virtualId      = request.getParameter("virtualId");

			VirtualArchitecture virtualArchitecture = propertyManager
					.getVirtualArchitectureById(Integer.parseInt(virtualId));
			GeneralBills generalBills = generalBillsManager
					.getGeneralBillsById(Integer.parseInt(generalBillsId));// 当前账单信息

			BigDecimal sumPrice = generalBillsManager.getArrearsRecord(
					generalBills.getOutMonth(),
					Integer.parseInt(virtualId));// 欠费总金额
			BigDecimal sumOwed = null;

			if (generalBills.getPayStatus().equals("1")) {
				sumOwed = sumPrice.subtract(new BigDecimal(0));// 历史欠费
			} else {
				sumOwed = sumPrice.subtract(generalBills.getTotalFee());// 历史欠费
			}

			BigDecimal payable = sumPrice.subtract(virtualArchitecture
					.getReserveBalance());// 应缴费用
			List<GeneralbillService> generalbillServiceList = generalBillsManager
					.getGeneralbillServiceList(Integer.parseInt(generalBillsId));

			for (int i = 0; i < generalbillServiceList.size(); i++) {
				generalbillServiceList.get(i).setList(
						generalBillsManager.geteneralBillOrdersList(
								generalbillServiceList.get(i).getBillId(),
								generalbillServiceList.get(i).getServiceCode()));
			}

			List<Element> signingServiceGroup = this.getElementGroupManager()
					.getElementsByGroupName("signingServiceGroup");// 状态

			String endOutMonth = DateUtils.getPreMonthDates(
					DateUtils.StrToDate(generalBills.getOutMonth(), "yyyy-MM"), -6);

			List<Map<String, Object>> resultList = generalBillsManager
					.getHistoryBill(Integer.parseInt(generalBillsId),
							endOutMonth, generalBills.getOutMonth(),
							virtualArchitecture.getOrganizationId() + "",
							virtualArchitecture.getId() + "");

			model.addAttribute("signingServiceGroup", signingServiceGroup);
			model.addAttribute("sumOwed", sumOwed);
			model.addAttribute("startTime", DateUtils.formatDate(generalBills.getStartTime(), "yyyy-MM-dd"));
			model.addAttribute("endTime", DateUtils.formatDate(generalBills.getEndTime(), "yyyy-MM-dd"));
			model.addAttribute("payable", payable);
			model.addAttribute("generalBills", generalBills);
			model.addAttribute("generalbillServiceList", generalbillServiceList);
			model.addAttribute("virtualArchitecture", virtualArchitecture);// 企业信息
			model.addAttribute("generalBillsId", generalBillsId);
			model.addAttribute("virtualId", virtualId);
			model.addAttribute("resultList", resultList);

			return new ModelAndView("/admin/bill/generalBillsPutSeal",
					model.asMap());
		} catch (Exception e) {
			LogExceptionStackUtil.LogExceptionStack(e);
		}
		return null;
	}

	public static void main(String[] args) {
		BigDecimal sumOwed  = new BigDecimal(613.4);
		BigDecimal sumOwed1 = new BigDecimal(0);
		System.out.println(sumOwed.subtract(sumOwed1).doubleValue());
	}

}
