package com.palmnest.webapp.controller.backstage;

import com.palmnest.application.core.util.FileUploadUtils;
import com.palmnest.application.core.util.LogExceptionStackUtil;
import com.palmnest.model.Element;
import com.palmnest.model.estateserve.DepositItemInformationForm;
import com.palmnest.model.estateserve.SignBasics;
import com.palmnest.model.estateserve.SignServiceInvoice;
import com.palmnest.service.estateserve.DepositItemInformationFormManager;
import com.palmnest.service.property.PropertyManager;
import com.palmnest.service.wechat.SignContractManager;
import com.palmnest.webapp.controller.BaseFormController;
import lombok.extern.slf4j.Slf4j;
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.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.List;
import java.util.Map;

/**
 * 签约协议信息管理前端控制器
 *
 * @author yubing
 * @since 2017-05-24
 */
@Slf4j
@Controller
@RequestMapping(value = "/admin/signContact/*")
public class SignContractWebController extends BaseFormController {


	@Autowired
	private SignContractManager               signContractManager;
	@Autowired
	private PropertyManager                   propertyManager;
	@Autowired
	private DepositItemInformationFormManager depositItemInformationFormManager;

	public void init(Model model) {
		List<Element> paymentTypeGroup       = this.getElementGroupManager().getElementsByGroupName("paymentTypeGroup");
		List<Element> signContactStatusGroup = this.getElementGroupManager().getElementsByGroupName("signContactStatusGroup");//状态
		model.addAttribute("paymentTypeGroup", paymentTypeGroup);
		model.addAttribute("signContactStatusGroup", signContactStatusGroup);
		model.addAttribute("imageServer", FileUploadUtils.getVisitPrefix());
	}

	/**
	 * 查询签约的信息
	 */
	@RequestMapping(value = "query")
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response) throws Exception {
		initFunctionOperate(request);
		Model  model     = new ExtendedModelMap();
		String virtualId = request.getParameter("virtualId");
		//查询签约记录明细集合
		List<Map<String, Object>> list = signContractManager.getSignContractListByVirId(Integer.parseInt(virtualId));
		model.addAttribute("list", list);
		model.addAttribute("virtualId", virtualId);
		model.addAttribute("virtualArchitecture", propertyManager.getVirtualArchitectureById(Integer.parseInt(virtualId)));
		init(model);
		return new ModelAndView("admin/contract/signContactList", model.asMap());
	}

	/**
	 * 获取押金集合信息
	 */
	@RequestMapping(value = "/getSignBasics", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	List<Map<String, Object>> getSignBasics(HttpServletRequest request,
											HttpServletResponse response) {
		String signId = request.getParameter("signId"); //协议ID
		try {
			return signContractManager.getSignContractListBySignid(signId);
		} catch (Exception e) {
			log.error("getSignBasics occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

	/**
	 * 根据服务ID获取相对的服务项
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/getDepositItemInformationFormList", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	public @ResponseBody
	List<DepositItemInformationForm> getDepositItemInformationFormList(HttpServletRequest request,
																	   HttpServletResponse response) {
		String serviceTypeInfoId = request.getParameter("serviceTypeInfoId"); //服务ID
		try {
			return depositItemInformationFormManager.getDepositItemInformationFormList(Integer.parseInt(serviceTypeInfoId));
		} catch (Exception e) {
			log.error("getDepositItemInformationFormList occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

	/**
	 * 保存或修改押金项信息
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/saveUpdateDeposit", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	public @ResponseBody
	String saveUpdateDeposit(HttpServletRequest request,
							 HttpServletResponse response) {
		String     id          = request.getParameter("id"); //主键ID
		String     number      = request.getParameter("number"); //数量
		String     totalAmount = request.getParameter("totalAmount"); //价格
		String     basicsId    = request.getParameter("basicsId");//押金项信息ID
		String     signid      = request.getParameter("signId");
		JSONObject jsonObject  = new JSONObject();
		SignBasics signBasics  = null;
		try {
			if (StringUtils.isNotBlank(id)) {
				Map<String, Object> map = signContractManager.getIsSignBasics(signid, basicsId, Integer.parseInt(id));
				if (map == null) {
					signBasics = signContractManager.getSignBasicsObj(Integer.parseInt(id));
					signBasics.setBasicsId(Integer.parseInt(basicsId));
					signBasics.setNumber(Integer.parseInt(number));
					signBasics.setTotalAmount(new BigDecimal(totalAmount));
					signBasics.setModifier(request.getRemoteUser());
					signBasics.setModifyTime(new Date());
					signBasics.setSignId(signid);
					propertyManager.updateModel(signBasics);
					jsonObject.put("flag", true);
					jsonObject.put("desc", "编辑成功！");
					jsonObject.put("id", signBasics.getId());
				} else {
					jsonObject.put("flag", false);
					jsonObject.put("desc", "已存在相同的押金项！");
				}
			} else {
				Map<String, Object> map = signContractManager.getIsSignBasics(signid, basicsId, null);
				if (map == null) {
					signBasics = new SignBasics();
					signBasics.setBasicsId(Integer.parseInt(basicsId));
					signBasics.setNumber(Integer.parseInt(number));
					signBasics.setTotalAmount(new BigDecimal(totalAmount));
					signBasics.setCreator(request.getRemoteUser());
					signBasics.setCreateTime(new Date());
					signBasics.setSignId(signid);
					signBasics.setIsEnabled("1");
					propertyManager.saveModel(signBasics);
					jsonObject.put("flag", true);
					jsonObject.put("desc", "保存成功！");
					jsonObject.put("id", signBasics.getId());
				} else {
					jsonObject.put("flag", false);
					jsonObject.put("desc", "已存在相同的押金项！");
				}
			}
		} catch (Exception e) {
			if (StringUtils.isNotBlank(id)) {
				jsonObject.put("desc", "编辑失败！");
			} else {
				jsonObject.put("desc", "保存失败！");
			}
			jsonObject.put("flag", false);
			log.error("saveUpdateDeposit occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return jsonObject.toString();
	}

	/**
	 * 删除押金项信息
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/deleteDeposit", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	public @ResponseBody
	String deleteDeposit(HttpServletRequest request,
						 HttpServletResponse response) {
		String     id         = request.getParameter("id"); //主键ID
		JSONObject jsonObject = new JSONObject();
		SignBasics signBasics = null;
		try {
			if (StringUtils.isNotBlank(id)) {
				signBasics = signContractManager.getSignBasicsObj(Integer.parseInt(id));
				signBasics.setIsEnabled("0");
				signBasics.setModifier(request.getRemoteUser());
				signBasics.setModifyTime(new Date());
				propertyManager.updateModel(signBasics);
				jsonObject.put("flag", true);
				jsonObject.put("desc", "删除成功！");
			}
		} catch (Exception e) {
			jsonObject.put("desc", "删除失败！");
			jsonObject.put("flag", false);
			log.error("deleteDeposit occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return jsonObject.toString();
	}

	/**
	 * 根据企业ID和发票类型查询发票信息
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/getSignServiceInvoiceObj", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	public @ResponseBody
	SignServiceInvoice getSignServiceInvoiceObj(HttpServletRequest request,
												HttpServletResponse response) {
		String virtualId = request.getParameter("virtualId"); //企业ID
		String type      = request.getParameter("type");//发票类型
		try {
			if (StringUtils.isNotBlank(virtualId) && StringUtils.isNotBlank(type)) {
				return signContractManager.getSignServiceInvoiceObj(Integer.parseInt(virtualId), type);
			}
		} catch (Exception e) {
			log.error("getDepositItemInformationFormList occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

	/**
	 * 保存或修改发票信息
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/saveUpdateInvoiceBillTab", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	public @ResponseBody
	String saveUpdateInvoiceBillTab(HttpServletRequest request,
									HttpServletResponse response) {
		JSONObject jsonObject = new JSONObject();
		try {
			String             type                 = request.getParameter("type");
			String             virtualId            = request.getParameter("virtualId");
			String             raise                = request.getParameter("raise");
			String             identificationNumber = request.getParameter("identificationNumber");
			String             address              = request.getParameter("address");
			String             mobile               = request.getParameter("mobile");
			String             bank                 = request.getParameter("bank");
			String             bankCard             = request.getParameter("bankCard");
			SignServiceInvoice serviceInvoice       = signContractManager.getSignServiceInvoiceObj(Integer.parseInt(virtualId), type);
			if (serviceInvoice != null) {
				serviceInvoice.setRaise(raise);
				serviceInvoice.setIdentificationNumber(identificationNumber);
				if (serviceInvoice.getType() == 2) {
					serviceInvoice.setVirtualarchitectureId(Integer.parseInt(virtualId));
					serviceInvoice.setIdentificationNumber(identificationNumber);
					serviceInvoice.setAddress(address);
					serviceInvoice.setMobile(mobile);
					serviceInvoice.setBank(bank);
					serviceInvoice.setBankCard(bankCard);
				}
				serviceInvoice.setModifier(request.getRemoteUser());
				serviceInvoice.setModifyTime(new Date());
				propertyManager.updateModel(serviceInvoice);
				jsonObject.put("flag", true);
				jsonObject.put("desc", "编辑成功！");
			} else {
				serviceInvoice = new SignServiceInvoice();
				serviceInvoice.setRaise(raise);
				serviceInvoice.setIdentificationNumber(identificationNumber);
				serviceInvoice.setType(Integer.parseInt(type));
				serviceInvoice.setVirtualarchitectureId(Integer.parseInt(virtualId));
				serviceInvoice.setIsEnabled("1");
				if (serviceInvoice.getType() == 2) {
					serviceInvoice.setVirtualarchitectureId(Integer.parseInt(virtualId));
					serviceInvoice.setAddress(address);
					serviceInvoice.setMobile(mobile);
					serviceInvoice.setBank(bank);
					serviceInvoice.setBankCard(bankCard);
				}
				serviceInvoice.setCreateTime(new Date());
				serviceInvoice.setCreator(request.getRemoteUser());
				propertyManager.saveModel(serviceInvoice);
				jsonObject.put("flag", true);
				jsonObject.put("desc", "保存成功！");
			}
		} catch (Exception e) {
			log.error("saveUpdateInvoiceBillTab occur error." + LogExceptionStackUtil.LogExceptionStack(e));
			jsonObject.put("flag", false);
			jsonObject.put("desc", "操作失败！");
		}
		return jsonObject.toString();
	}

	/**
	 * 根据签约ID查询意向商品
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/getIntentionalGoods", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
	public @ResponseBody
	List<Map<String, Object>> getIntentionalGoods(HttpServletRequest request,
												  HttpServletResponse response) {
		String id = request.getParameter("id"); //签约ID
		try {
			if (StringUtils.isNotBlank(id)) {
				return signContractManager.getIntentionalGoods(Integer.parseInt(id));
			}
		} catch (Exception e) {
			log.error("getDepositItemInformationFormList occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

}
