package com.palmnest.webapp.controller.backstage;

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.AppConstants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.application.dto.OrgDto;
import com.palmnest.application.dto.WebPageResultDto;
import com.palmnest.application.dto.output.PushBillOutputDto;
import com.palmnest.model.Element;
import com.palmnest.model.PushBill;
import com.palmnest.model.User;
import com.palmnest.model.estateserve.PushBillSaveInfo;
import com.palmnest.model.property.TbBuild;
import com.palmnest.service.AppUserService;
import com.palmnest.service.ElementGroupManager;
import com.palmnest.service.estateserve.FloorInfoManager;
import com.palmnest.service.estateserve.PushBillManager;
import com.palmnest.service.estateserve.VirtualArchManager;
import com.palmnest.webapp.controller.BaseFormController;
import lombok.extern.slf4j.Slf4j;
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.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 新增推送账单的控制器
 *
 * @author longmeizhen
 */
@Slf4j
@Controller
@RequestMapping("/admin/push/*")
public class PushBillController extends BaseFormController {


	@Autowired
	private PushBillManager     pushBillManager;
	@Autowired
	private ElementGroupManager elementGroupManager;
	@Autowired
	private FloorInfoManager    floorInfoManager;
	@Autowired
	private VirtualArchManager  virtualArchManager;
	@Autowired
	private AppUserService      appUserService;

	/**
	 * 推送账单(入口)
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/pushBill")
	public ModelAndView pushBill(HttpServletRequest request,
								 HttpServletResponse response) throws Exception {
		Model        model = new ExtendedModelMap();
		User         user  = (User) request.getSession().getAttribute("UserCache");
		List<OrgDto> dtos  = appUserService.getUserOrgs(user.getId());
		model.addAttribute("orgs", dtos);
		List<TbBuild> list = new ArrayList<TbBuild>();
		if (dtos != null && dtos.size() > 0) {
			if (dtos.size() == 1) {
				OrgDto org = dtos.get(0);
				list = floorInfoManager.getTbBuildListByOrgaid(org.getId().toString());
			}
		}
		model.addAttribute("buildList", list);
		return new ModelAndView("admin/billPush/billPush", model.asMap());
	}

	/**
	 * 推送历史(入口)
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "jumpPushBillList")
	public ModelAndView jumpVirModel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Model        model = new ExtendedModelMap();
		User         user  = (User) request.getSession().getAttribute("UserCache");
		List<OrgDto> dtos  = appUserService.getUserOrgs(user.getId());
		model.addAttribute("orgs", dtos);
		List<TbBuild> list = new ArrayList<TbBuild>();
		if (dtos != null && dtos.size() > 0) {
			if (dtos.size() == 1) {
				OrgDto org = dtos.get(0);
				list = floorInfoManager.getTbBuildListByOrgaid(org.getId().toString());
			}
		}
		model.addAttribute("buildList", list);
		return new ModelAndView("admin/billPush/pushHistory", model.asMap());
	}

	/**
	 * 获取备注和标题
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/getTitleAndRemark")
	@ResponseBody
	public AppResultDto getTitleAndRemark(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> map    = new HashMap<String, Object>();
		List<Element>       elList = this.getElementGroupManager().getElementsByGroupName("title");
		if (elList != null && elList.size() > 0) {
			for (int i = 0; i < elList.size(); i++) {
				Element ele = elList.get(i);
				if ("0".equals(ele.getItemcode())) {
					//出账账单标题
					map.put("title1", ele.getItemname());
				} else if ("1".equals(ele.getItemcode())) {
					//逾期账单标题
					map.put("title2", ele.getItemname());
				}
			}
		}

		List<Element> eleList = this.getElementGroupManager().getElementsByGroupName("remark");
		if (eleList != null && eleList.size() > 0) {
			for (int i = 0; i < eleList.size(); i++) {
				Element ele = eleList.get(i);
				if ("0".equals(ele.getItemcode())) {
					//出账账单备注
					map.put("remark1", ele.getItemname());
				} else if ("1".equals(ele.getItemcode())) {
					//逾期账单备注
					map.put("remark2", ele.getItemname());
				}
			}
		}

		AppResultDto dto = AppResultUtil.createSuccesDto(map);
		return dto;
	}

	/**
	 * 推送历史
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/pushBillList")
	@ResponseBody
	public WebPageResultDto pushBillList(HttpServletRequest request,
										 HttpServletResponse response) throws Exception {
		String floorIds  = request.getParameter("floorIds");
		String buildId   = request.getParameter("buildId");
		String beginTime = request.getParameter("beginTime");
		String virName   = request.getParameter("virName");
		String endTime   = request.getParameter("endTime");
		String billType  = request.getParameter("billType");
		String proId     = request.getParameter("proId");

		User         user = (User) request.getSession().getAttribute("UserCache");
		List<OrgDto> dtos = appUserService.getUserOrgs(user.getId());

		if (StringUtils.isEmpty(proId) || "0".equals(proId)) {
			if (dtos != null && dtos.size() > 0) {
				proId = "";
				for (int i = 0; i < dtos.size(); i++) {
					OrgDto dto = dtos.get(i);
					proId = proId + dto.getId() + ";";
				}
			}
		}

		int pageNo = 1;
		if (StringUtils.isNotBlank(request.getParameter("page"))) {
			pageNo = Integer.parseInt(request.getParameter("page"));
		}
		int pageSize = 10;
		if (StringUtils.isNotBlank(request.getParameter("limit"))) {
			pageSize = Integer.parseInt(request.getParameter("limit"));
		}
		if (StringUtils.isNotEmpty(virName)) {
			virName = virName.trim();
		}
		Page page = pushBillManager.queryBillPushList(proId, beginTime, endTime, billType, buildId, floorIds, virName, pageNo, pageSize);

		WebPageResultDto dto = new WebPageResultDto();
		dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", page == null ? null : page.getItems());
		if (page != null) {
			dto.setCount(page.getTotalCount());
		} else {
			dto.setCount(Long.parseLong("0"));
		}
		return dto;
	}

	/**
	 * 点击发送时调用发送消息的方法，将列表中所对应的条数发送出去
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/sendPushBill")
	public void sendPushBill(@RequestBody PushBillSaveInfo pushBillSaveInfo, HttpServletRequest request, HttpServletResponse response) throws Exception {
		//账单类型
		int              billType = pushBillSaveInfo.getBillType();
		SimpleDateFormat sf       = new SimpleDateFormat("yyyy-MM-dd");
		//账单截止日
		String pushUpDate = sf.format(new Date());
		//根据企业的发送方式来判断负责人以什么样的方式来接收推送的账单消息，从而获取相应的模板
		User                    userLi    = (User) request.getSession().getAttribute("UserCache");//----------联调时需放开注释
		List<PushBillOutputDto> objList   = pushBillSaveInfo.getObjList();
		String                  monthDate = pushBillSaveInfo.getMonthDate();
		String                  beginTime = pushBillSaveInfo.getBeginTime();
		String                  endTime   = pushBillSaveInfo.getEndTime();
		String                  title     = "";
		String                  remark    = "";
		List<Element>           elList    = this.getElementGroupManager().getElementsByGroupName("title");
		if (elList != null && elList.size() > 0) {
			for (int i = 0; i < elList.size(); i++) {
				Element ele = elList.get(i);
				if (billType == 0) {//出账日账单
					if ("0".equals(ele.getItemcode())) {
						title = ele.getItemname();//出账账单标题
					}
				} else if (billType == 1) {//逾期账单
					if ("1".equals(ele.getItemcode())) {
						title = ele.getItemname();//逾期账单标题
					}
				}

			}
		}
		List<Element> eleList = this.getElementGroupManager().getElementsByGroupName("remark");
		if (eleList != null && eleList.size() > 0) {
			for (int i = 0; i < eleList.size(); i++) {
				Element ele = eleList.get(i);
				if (billType == 0) {//出账日账单
					if ("0".equals(ele.getItemcode())) {
						remark = ele.getItemname();//出账账单备注
					}
				} else if (billType == 1) {//逾期账单
					if ("1".equals(ele.getItemcode())) {
						remark = ele.getItemname();//逾期账单备注
					}
				}
			}
		}

		User         user  = (User) request.getSession().getAttribute("UserCache");
		List<OrgDto> dtos  = appUserService.getUserOrgs(user.getId());
		String       orgId = "";
		if (StringUtils.isNotBlank(pushBillSaveInfo.getOrgId())) {
			orgId = pushBillSaveInfo.getOrgId();
		} else {
			if (dtos != null && dtos.size() == 1) {
				OrgDto dto = dtos.get(0);
				orgId = dto.getId().toString();
			}
		}
		List<PushBill> list = pushBillManager.getPushBillListByListObj(orgId, title, remark, monthDate, beginTime, endTime, billType, pushUpDate, objList, userLi);
		JSONObject     json = new JSONObject();
		try {
			//首先将列表中的数据保存到数据库中，然后再发送
			int count = pushBillManager.savePushBill(list);
			//发送列表中的信息
			if (count > 0 && count == list.size()) {
				json.put("result", "success");
				json.put("message", "");
				StringUtil.charSet(json, request, response);
			} else {
				int bugNum = list.size() - count;
				json.put("result", "fail");
				json.put("message", "添加到数据库异常,异常条数：" + bugNum);
				StringUtil.charSet(json, request, response);
			}

		} catch (Exception e) {
			log.error(e.getMessage());
			json.put("result", "fail");
			json.put("message", e.getMessage());
			StringUtil.charSet(json, request, response);
			throw new Exception(e);
		}
	}


	/**
	 * 账单推送导入接口
	 *
	 * @throws Exception
	 */
	@RequestMapping(value = "/confirmImportPushBill", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=utf-8")
	@ResponseBody
	public AppResultDto confirmImportPushBill(@RequestParam("excelFile") MultipartFile excelFile, HttpServletRequest request, HttpServletResponse response) throws Exception {
//		JSONObject json=new JSONObject();
		//首先判断模板的准确性，然后展示到列表上去
		Map<String, Object> map = null;
		try {
			map = pushBillManager.saveImportPushBillData(excelFile.getInputStream());
			int bugCount = Integer.parseInt(map.get("bugCount").toString());
			if (bugCount > 0) {
				return AppResultUtil.createErrorDto("100", map.get("bugStr").toString());
			} else {
				List<PushBillOutputDto> list = (List<PushBillOutputDto>) map.get("list");
				return AppResultUtil.createSuccesDto(list);
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			return AppResultUtil.createErrorDto("100", "导入账单失败：" + e.getMessage());
		}

	}

	@RequestMapping(value = "getDataByPush")
	@ResponseBody
	public AppResultDto getDataByPush(String id, String type) {
		String data = "";
		if (StringUtils.isNotEmpty(id)) {
			PushBill pushBill = pushBillManager.get(Integer.parseInt(id));
			if (pushBill != null) {
				if ("message".equals(type)) {
					data = pushBill.getMessageData();
				} else if ("email".equals(type)) {
					data = pushBill.getEmailData();
				}
			}
		}
		return AppResultUtil.createSuccesDto(data);
	}

}
