package com.palmnest.webapp.controller.backstage;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.bean.Pagenation;
import com.palmnest.application.core.util.ExcelUtils;
import com.palmnest.application.core.util.LogExceptionStackUtil;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.service.estateserve.RechargeWebManager;
import com.palmnest.service.wechat.RechargeManager;
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.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping(value = "/admin/recharge*")
public class RechargeWebController {


	@Autowired
	private RechargeWebManager rechargeWebManager;
	@Autowired
	private RechargeManager    rechargeManager;

	/**
	 * 查询充值列表
	 *
	 * @param params
	 * @return
	 */
	@RequestMapping(value = "queryRechargeList")
	public String queryRechargeList(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		String startTime       = request.getParameter("startTime");
		String endTime         = request.getParameter("endTime");
		String type            = request.getParameter("type");
		String mobile          = request.getParameter("mobile");
		String productName     = request.getParameter("productName");
		String pageNo          = request.getParameter("pageNo");
		String status          = request.getParameter("status");
		String payStatus       = request.getParameter("payStatus");
		String id              = request.getParameter("id");
		String province        = request.getParameter("province");
		String carrieroperator = request.getParameter("carrieroperator");
		String wxUserId        = request.getParameter("wxUserId");
		if (StringUtils.isEmpty(pageNo)) {
			pageNo = "1";
		}
		modelMap.put("pageNo", pageNo);
		modelMap.put("mobile", mobile);
		modelMap.put("status", status);
		modelMap.put("id", id);
		modelMap.put("productName", productName);
		modelMap.put("payStatus", payStatus);
		modelMap.put("wxUserId", wxUserId);
		modelMap.put("province", province);
		modelMap.put("carrieroperator", carrieroperator);
		modelMap.put("type", type);
		modelMap.put("startTime", startTime);
		modelMap.put("endTime", endTime);
		modelMap.put("pageSize", 10);
		try {
			Pagenation<Map<String, String>> page = rechargeWebManager.queryRechargeList(modelMap);
			modelMap.put("page", page);
			modelMap.remove("pageNo");
		} catch (Exception e) {
			log.error("findRechargeList occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return "admin/recharge/rechargeList";
	}

	/**
	 * 查询产品列表
	 *
	 * @param params
	 * @return
	 */
	@RequestMapping(value = "queryProductList")
	public String queryProductList(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		try {
			String startTime       = request.getParameter("startTime");
			String endTime         = request.getParameter("endTime");
			String type            = request.getParameter("type");
			String province        = request.getParameter("province");
			String carrieroperator = request.getParameter("carrieroperator");
			modelMap.put("type", type);
			modelMap.put("province", province);
			modelMap.put("carrieroperator", carrieroperator);
			modelMap.put("startTime", startTime);
			modelMap.put("endTime", endTime);
			String pageNo = request.getParameter("pageNo");
			if (StringUtils.isEmpty(pageNo)) {
				pageNo = "1";
			}
			modelMap.put("pageNo", pageNo);
			try {
				Pagenation<Map<String, String>> page = rechargeWebManager.queryProductList(modelMap);
				modelMap.put("page", page);
				modelMap.remove("pageNo");
			} catch (Exception e) {
				log.error("findRechargeList occur error." + LogExceptionStackUtil.LogExceptionStack(e));
			}
		} catch (Exception e) {
			log.error("findProduct occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return "admin/recharge/productList";
	}

	/**
	 * 产品导入
	 *
	 * @return
	 * @throws IOException
	 * @throws IllegalStateException
	 */
	@RequestMapping(value = "importProduct")
	public String importProduct(HttpServletRequest request, HttpServletResponse response) throws IllegalStateException, IOException {
		JSONObject    json     = new JSONObject();
		MultipartFile file     = null;
		String        fileName = "";
		//创建一个通用的多部分解析器
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		//判断 request 是否有文件上传
		if (multipartResolver.isMultipart(request)) {
			// 转换成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 取得上传文件
			file = multiRequest.getFile("fileUpload");
			fileName = file.getOriginalFilename();
			if (fileName == null) {
				json.put("code", -1);
				json.put("msg", "文件不存在，请重新上传!");
				StringUtil.charSet(json, request, response);
				return null;
			}
		}
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		try {
			if (fileName.toLowerCase().endsWith(".xls")) {
				list = ExcelUtils.readExcelByXls(file.getInputStream(), 1, 0, 0);
			} else {
				list = ExcelUtils.readExcelByXlsx(file.getInputStream(), 1, 0, 0);
			}
			if (list == null || list.size() == 0) {
				json.put("code", -1);
				json.put("msg", "数据导入为空,请按照模板填写资料后再导入!");
				StringUtil.charSet(json, request, response);
				return null;
			}
			json = rechargeWebManager.importProduct(list, request.getRemoteUser());
			StringUtil.charSet(json, request, response);
		} catch (Exception e) {
			StringUtil.charSet(json, request, response);
			return null;
		}

		return null;
	}

	/**
	 * 手动充值
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "recharege")
	public String recharege(HttpServletRequest request, HttpServletResponse response) {
		String     id   = request.getParameter("id");
		String     type = request.getParameter("productId");
		JSONObject json = new JSONObject();
		try {
			json = rechargeWebManager.updaterecharge(type, id);
			StringUtil.charSet(json, request, response);
			return null;
		} catch (Exception e) {
			log.error("recharege occur error.{}", e, e.getMessage());
		}
		return null;
	}

	/**
	 * 手动退款
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "drawback")
	public String drawback(HttpServletRequest request, HttpServletResponse response) {
		String     id   = request.getParameter("id");
		JSONObject json = new JSONObject();
		try {
			json = rechargeWebManager.updateDrawback(id);
			StringUtil.charSet(json, request, response);
			return null;
		} catch (Exception e) {
			log.error("drawback occur error.{}", e, e.getMessage());
		}
		return null;
	}

	/**
	 * 导出充值列表
	 *
	 * @param request
	 * @param response
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/exportRecharge")
	public String exportPlanList(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		File        file      = null;
		String      filename  = "exportRecharge.xls";
		String      type      = request.getParameter("type");
		String      status    = request.getParameter("status");
		String      payStatus = request.getParameter("payStatus");
		String      startTime = request.getParameter("startTime");
		String      endTime   = request.getParameter("endTime");
		InputStream fileInputStream;
		modelMap.put("pageNo", 0);
		modelMap.put("pageSize", 65000);
		modelMap.put("type", type);
		modelMap.put("payStatus", payStatus);
		modelMap.put("status", status);
		modelMap.put("startTime", startTime);
		modelMap.put("endTime", endTime);
		String name = "用户充值列表";
		try {
			Pagenation<Map<String, String>> page = null;
			try {
				page = rechargeWebManager.queryRechargeList(modelMap);
			} catch (Exception e) {
				e.printStackTrace();
			}
			JSONArray arrBills = (JSONArray) JSONArray.toJSON(page.getItems());
			for (Object obj : arrBills) {
				JSONObject detail        = (JSONObject) obj;
				int        status_       = detail.getIntValue("status");
				int        payStatus_    = detail.getIntValue("payStatus");
				int        refundStatus_ = detail.getIntValue("refundStatus");
				String     type_         = detail.getString("type");
				String     channelCode   = detail.getString("channelCode");
				String     recharTime    = detail.getString("recharTime");
				String     refundTime    = detail.getString("refundTime");
				String     oname         = detail.getString("oname");
				String     vname         = detail.getString("vname");
				String     transactionId = detail.getString("transactionId");
				if (StringUtils.isEmpty(recharTime)) {
					detail.put("recharTime_", "--");
				} else {
					detail.put("recharTime_", recharTime);
				}
				if (StringUtils.isEmpty(refundTime)) {
					detail.put("refundTime_", "--");
				} else {
					detail.put("refundTime_", refundTime);
				}
				if (StringUtils.isEmpty(transactionId)) {
					detail.put("transactionId", "--");
				} else {
					detail.put("transactionId", transactionId);
				}
				switch (status_) {
					case 0:
						detail.put("status_", "充值中");
						break;
					case 1:
						detail.put("status_", "充值成功");
						break;
					case 2:
						detail.put("status_", "充值失败");
						break;
					default:
						detail.put("status_", "未充值");
						break;
				}
				if (type_.equals("0")) {
					detail.put("type_", "流量");
				}
				if (type_.equals("1")) {
					detail.put("type_", "话费");
				}
				if (type_.equals("MGTV")) {
					detail.put("type_", "芒果会员");
				}
				if (type_.equals("AIQIYI")) {
					detail.put("type_", "爱奇艺会员");
				}
				if (type_.equals("YOUKU")) {
					detail.put("type_", "优酷会员");
				}
				if (type_.equals("QQTV")) {
					detail.put("type_", "腾讯vip会员");
				}
				if (type_.equals("PPTV")) {
					detail.put("type_", "PPTV聚力会员");
				}
				if (type_.equals("SOHU")) {
					detail.put("type_", "搜狐黄金会员");
				}
				if (type_.equals("LETV")) {
					detail.put("type_", "乐视影视会员");
				}
				if (type_.equals("SINOPEC")) {
					detail.put("type_", "中石化");
				}
				switch (payStatus_) {
					case 0:
						detail.put("payStatus_", "支付成功");
						break;
					case 1:
						detail.put("payStatus_", "支付失败");
						break;
					default:
						detail.put("payStatus_", "未支付");
						break;
				}
				switch (refundStatus_) {
					case 1:
						detail.put("refundStatus_", "退款成功");
						break;
					case 2:
						detail.put("refundStatus_", "退款失败");
						break;
					default:
						detail.put("refundStatus_", "--");
						break;
				}

				if (StringUtils.isEmpty(oname)) {
					detail.put("oname_", "--");
				} else {
					detail.put("oname_", oname);
				}

				if (StringUtils.isEmpty(vname)) {
					detail.put("vname_", "--");
				} else {
					detail.put("vname_", vname);
				}

				if (StringUtils.isEmpty(channelCode)) {
					detail.put("channelCode_", "--");
				} else {
					detail.put("channelCode_", channelCode);
				}
			}

			file = ExcelUtils.export(
					name,
					arrBills,
					new String[]{"充值订单号", "微信订单号", "充值号码", "产品名称", "产品类型", "支付状态", "充值状态", "产品价格（元）", "支付价格（元）", "订单创建时间", "充值时间", "退款状态", "退款时间", "所属项目", "所属企业", "充值渠道编码"},
					new String[]{"outTradeNo", "transactionId", "mobile", "productName", "type_", "payStatus_", "status_", "productPrice", "price", "createTime", "recharTime_", "refundStatus_", "refundTime_", "oname_", "vname_", "channelCode_"});
			fileInputStream = new FileInputStream(file);

			byte[] arrayStr = filename.getBytes("UTF-8");
			filename = new String(arrayStr, "UTF-8");

			response.setContentType("application/ms-excel");
			response.setHeader("content-disposition", "attachment;filename=" + filename);
			response.setCharacterEncoding("UTF-8");
			FileCopyUtils.copy(fileInputStream, response.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
			return "error/error500";
		}
		return null;
	}


	/**
	 * 查询充值信息
	 *
	 * @param params
	 * @return
	 */
	@RequestMapping(value = "findProduct")
	public String findProduct(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		String     id   = request.getParameter("id");
		JSONObject json = new JSONObject();
		try {
			Map<String, String> map = rechargeManager.findProductById(Integer.valueOf(id));
			json.put("code", 0);
			json.put("msg", map);
			StringUtil.charSet(json, request, response);
			return null;
		} catch (Exception e) {
			log.error("findProduct occur error." + LogExceptionStackUtil.LogExceptionStack(e));
			json.put("code", -1);
			json.put("msg", "");
			StringUtil.charSet(json, request, response);
		}
		return null;
	}

	/**
	 * 更新产品信息
	 *
	 * @param params
	 * @return
	 */
	@RequestMapping(value = "updateProduct")
	public String updateProduct(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		String              all             = request.getParameter("all");
		String              id              = request.getParameter("id");
		String              type            = request.getParameter("type");
		String              province        = request.getParameter("province");
		String              carrieroperator = request.getParameter("carrieroperator");
		String              upDiscount      = request.getParameter("upDiscount");
		String              realPrice       = request.getParameter("realPrice");
		String              productPrice    = request.getParameter("productPrice");
		String              isEnabled       = request.getParameter("isEnabled");
		String              discount        = request.getParameter("discount");
		JSONObject          json            = new JSONObject();
		Map<String, String> map             = new HashMap<String, String>();
		map.put("all", all);
		map.put("id", id);
		map.put("province", province);
		map.put("carrieroperator", carrieroperator);
		map.put("upDiscount", upDiscount);
		map.put("realPrice", realPrice);
		map.put("productPrice", productPrice);
		map.put("isEnabled", isEnabled);
		map.put("discount", discount);
		map.put("type", type);
		try {
			json = rechargeWebManager.updateProduct(map);
			StringUtil.charSet(json, request, response);
			return null;
		} catch (Exception e) {
			log.error("updateProduct occur error." + LogExceptionStackUtil.LogExceptionStack(e));
			json.put("code", -1);
			json.put("msg", "");
			StringUtil.charSet(json, request, response);
		}
		return null;
	}

	/**
	 * 上架下架
	 *
	 * @param params
	 * @return
	 */
	@RequestMapping(value = "updateAvailable")
	public String updateAvailable(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		String              id     = request.getParameter("id");
		String              status = request.getParameter("status");
		JSONObject          json   = new JSONObject();
		Map<String, String> map    = new HashMap<String, String>();
		map.put("status", status);
		map.put("id", id);
		try {
			json = rechargeWebManager.updateAvailable(map);
			StringUtil.charSet(json, request, response);
			return null;
		} catch (Exception e) {
			log.error("updateAvailable occur error." + LogExceptionStackUtil.LogExceptionStack(e));
			json.put("code", -1);
			json.put("msg", "");
			StringUtil.charSet(json, request, response);
		}
		return null;
	}

}
