package com.palmnest.webapp.controller.backstage;

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.AppConstants;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.HttpKit;
import com.palmnest.application.dto.WebPageResultDto;
import com.palmnest.model.User;
import com.palmnest.model.virtfood.VirtFood;
import com.palmnest.model.virtfood.VirtFoodConfig;
import com.palmnest.model.virtfood.VirtFoodOutConfig;
import com.palmnest.service.virtfood.VirtFoodConfigManager;
import com.palmnest.service.virtfood.VirtFoodManager;
import com.palmnest.service.virtfood.VirtFoodOutConfigManager;
import com.palmnest.webapp.controller.BaseFormController;
import com.palmnest.webapp.controller.utils.AESUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.MessageDigest;
import java.util.*;

/**
 * 企业饭卡
 */
@Slf4j
@Controller
@RequestMapping(value = "/virtfood/*")
public class VirtFoodController extends BaseFormController {

	@Autowired
	private VirtFoodManager          virtFoodManager;
	@Autowired
	private VirtFoodConfigManager    virtFoodConfigManager;
	@Autowired
	private VirtFoodOutConfigManager virtFoodOutConfigManager;

	/**
	 * 饭卡管理页面
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "foodmanager")
	public ModelAndView foodmanagerView(HttpServletRequest request, HttpServletResponse response) {
		Model model = new ExtendedModelMap();
//        User user = (User) request.getSession().getAttribute("UserCache");
//        List<OrgDto> dtos =null;
//        model.addAttribute("orgs",dtos);
//        List<TbBuild> list=new ArrayList<TbBuild>();
//        model.addAttribute("buildList",list);
//        return new ModelAndView("admin/billPush/pushHistory",model.asMap());
		return new ModelAndView("admin/virtfood/foodmanager");
	}

	/**
	 * 饭卡配置页面
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "foodconfig")
	public ModelAndView foodconfigView(HttpServletRequest request, HttpServletResponse response) {
		Model model = new ExtendedModelMap();
		return new ModelAndView("admin/virtfood/foodconfig");
	}

	@RequestMapping(value = "test")
	public ModelAndView testview(HttpServletRequest request, HttpServletResponse response) {
		Model model = new ExtendedModelMap();
		return new ModelAndView("admin/virtfood/test");
	}

	/***
	 * 饭卡管理列表
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "managerList")
	@ResponseBody
	public WebPageResultDto getmanagerList(HttpServletRequest request) {
		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"));
		}
		String food_name = request.getParameter("food_name");
		String org_name  = request.getParameter("org_name");

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("food_name", food_name);
		params.put("org_name", org_name);

		User   user  = (User) request.getSession().getAttribute("UserCache");//----------联调时需放开注释
		String orgId = request.getParameter("orgId");
		if (StringUtils.isBlank(orgId)) {
			orgId = getUserManageOrgIds(user);
		}
		params.put("orgStr", orgId);
		try {
			Page             page = virtFoodManager.findPageBy(params, pageSize, pageNo);
			WebPageResultDto dto  = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", page.getItems());
			dto.setCount(page.getTotalCount());
			return dto;
		} catch (Exception e) {
			e.printStackTrace();
			return new WebPageResultDto("400", "获取列表失败！" + e.getMessage(), "");
		}
	}

	/**
	 * 保存
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "save")
	@ResponseBody
	public WebPageResultDto repairApproval(HttpServletRequest request) {
		String id               = request.getParameter("id");
		String food_name        = request.getParameter("food_name");
		User   user             = (User) request.getSession().getAttribute("UserCache");
		String account_number   = request.getParameter("account_number");
		String account_password = request.getParameter("account_password");
		String card_no          = request.getParameter("card_no");
		String org_id           = request.getParameter("org_id");
		String org_ids          = request.getParameter("org_ids");
		String food_type        = request.getParameter("food_type");

		VirtFood food = new VirtFood();
		food.setFood_type(Byte.valueOf(food_type));
		if (food.getFood_type() == 2) {
			String virt_id = request.getParameter("virt_id");
			if (StringUtils.isNotEmpty(virt_id)) {
				food.setVirt_id(Long.parseLong(virt_id));
			} else {
				return new WebPageResultDto("400", "企业ID为空", "");
			}
		}
		food.setAccount_number(account_number);
		food.setAccount_password(account_password);
		food.setApproval_status(Byte.valueOf("1"));
		food.setCard_no(card_no);
		food.setCreated_at(new Date());
		food.setCreated_by(user.getId());
		food.setEnabled(Byte.valueOf("2"));
		food.setFood_name(food_name);
		if (StringUtils.isNotEmpty(id)) {
			food.setId(Long.parseLong(id));
		}
		if (StringUtils.isNotEmpty(org_id)) {
			food.setOrg_id(Long.parseLong(org_id));
		}

		try {


			if (food.getId() == null) {
				Map<String, Object> params = new HashMap<String, Object>();
				params.put("food_name", food_name);
				List<VirtFood> ls = virtFoodManager.findAll(params);
				if (ls != null && ls.size() > 0) {
					return new WebPageResultDto("400", "保存失败！饭卡名称重复！", "");
				}

				virtFoodManager.saveModel(food);
				if (food.getId() != null && food.getId() > 0) {
					//調取威富通接口
					//獲取第三方配置信息
					VirtFoodOutConfig oc = virtFoodOutConfigManager.get(1L);
					//JSONObject biz_contentjson = new JSONObject();
					//業務
					int    receive_card_type = food.getFood_type() == 1 ? 2 : 1;
					String password          = AESUtil.encode2base64(food.getAccount_password(), oc.getParam1(), true);//AES.Encrypt(food.getAccount_password(), oc.getEncodekey().substring(0,16));
					String mobile            = AESUtil.encode2base64(food.getAccount_number(), oc.getParam1(), true);//AES.Encrypt(food.getAccount_number(), oc.getEncodekey().substring(0,16));
					String name              = food.getFood_name();
					String nonce_str         = UUID.randomUUID().toString();
					String timestamp         = Long.toString(System.currentTimeMillis() / 1000);
					String str = "biz_content={\"receive_card_type\":" + receive_card_type +
							",\"password\":\"" + password + "\",\"mobile\":\"" + mobile + "\",\"name\":\"" + name + "\"}&channel_code=" + oc.getQudaohao() +
							"&charset=utf-8&nonce_str=" + nonce_str +
							"&partner_type=CHANNEL&service=register_enterprise&sign_type=SHA-256&timestamp=" + timestamp +
							"&version=4.0&key=" + oc.getEncodekey();
					MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
					messageDigest.update(str.getBytes("UTF-8"));
					byte   byteBuffer[] = messageDigest.digest();
					String sign         = Base64.encodeBase64URLSafeString(byteBuffer);
					System.out.println("簽名：" + sign);
					System.out.println("傳參：" + str + "&sign=" + sign);
					String postRes = HttpKit.Post(str + "&sign=" + sign, oc.getInterface_url());
					System.out.println("返回" + postRes);
					String retmsg = JSONObject.parseObject(JSONObject.parseObject(postRes).get("biz_content").toString()).get("retmsg").toString();
					if (retmsg.equals("ok")) {
						String spid = JSONObject.parseObject(JSONObject.parseObject(JSONObject.parseObject(postRes).get("biz_content").toString()).get("data").toString()).get("spid").toString();
						food.setCard_no(spid);
						food.setApproval_status(Byte.valueOf("9"));
						virtFoodManager.updateModel(food);
					} else {
						virtFoodManager.remove(food.getId());
						return new WebPageResultDto("400", "保存失败！饭卡数据接口调用失败！" + retmsg, "");
					}
				}
			} else {
				VirtFood getfood = virtFoodManager.get(food.getId());
				if (getfood.getApproval_status() == 2) {
					return new WebPageResultDto("400", "保存失败！已通过审核不可更改！", "");
				}
				virtFoodManager.updateModel(food);
			}
			if (StringUtils.isNotEmpty(org_ids)) {
				String[] orgs = org_ids.split(",");
				for (String item : orgs) {
					virtFoodManager.insertFoodOrg(food.getId(), Long.parseLong(item));
				}
			}

			WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", food);

			return dto;
		} catch (Exception e) {
			e.printStackTrace();
			return new WebPageResultDto("400", "保存失败！" + e.getMessage(), "");
		}
	}

	/**
	 * 启用禁用
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "openorclose")
	@ResponseBody
	public WebPageResultDto openorclose(HttpServletRequest request) {
		String id = request.getParameter("id");

		String status = request.getParameter("status");

		VirtFood food = new VirtFood();

		if (StringUtils.isNotEmpty(id)) {
			food.setId(Long.parseLong(id));
		} else {
			return new WebPageResultDto("400", "更新失败！Id为空", "");
		}
		if (StringUtils.isNotEmpty(status)) {
			food.setEnabled(Byte.valueOf(status));
		}

		try {


			virtFoodManager.updateEnable(food);


			WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", food);

			return dto;
		} catch (Exception e) {
			e.printStackTrace();
			return new WebPageResultDto("400", "保存失败！" + e.getMessage(), "");
		}
	}


	/**
	 * 饭卡配置保存
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "configsave")
	@ResponseBody
	public WebPageResultDto configsave(HttpServletRequest request) {
		User           user           = (User) request.getSession().getAttribute("UserCache");
		String         food_id        = request.getParameter("food_id");//饭卡组名称
		String         merchant_name1 = request.getParameter("merchant_name1");//商户名称1
		String         merchant_name2 = request.getParameter("merchant_name2");//商户名称2
		String         merchant_name3 = request.getParameter("merchant_name3");//商户名称2
		String         merchant_name4 = request.getParameter("merchant_name4");//商户名称2
		String         discount1      = request.getParameter("discount1");//折扣
		String         discount2      = request.getParameter("discount2");//折扣
		String         discount3      = request.getParameter("discount3");//折扣
		String         discount4      = request.getParameter("discount4");//折扣
		String         logo1          = request.getParameter("logo1");//LOGO
		String         logo2          = request.getParameter("logo2");//LOGO
		String         logo3          = request.getParameter("logo3");//LOGO
		String         logo4          = request.getParameter("logo4");//LOGO
		String         out_url        = request.getParameter("out_url");//外链
		VirtFoodConfig config         = new VirtFoodConfig();
		if (StringUtils.isNotEmpty(food_id)) {
			config.setFood_id(Long.parseLong(food_id));
		} else {
			return new WebPageResultDto("400", "饭卡ID为空", "");
		}
		config.setDiscount1(discount1);
		config.setDiscount2(discount2);
		config.setDiscount3(discount3);
		config.setDiscount4(discount4);
		config.setLogo1(logo1);
		config.setLogo2(logo2);
		config.setLogo3(logo3);
		config.setLogo4(logo4);
		config.setMerchant_name1(merchant_name1);
		config.setMerchant_name2(merchant_name2);
		config.setMerchant_name3(merchant_name3);
		config.setMerchant_name4(merchant_name4);
		config.setOut_url(out_url);


		try {


			VirtFoodConfig sModel = virtFoodConfigManager.getByFoodId(config.getFood_id());
			if (sModel != null) {
				config.setUpdated_at(new Date());
				config.setUpdated_by(user.getId());
				config.setId(sModel.getId());
				virtFoodConfigManager.updateModel(config);
			} else {
				config.setCreated_at(new Date());
				config.setCreated_by(user.getId());
				virtFoodConfigManager.saveModel(config);
			}

			WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", config);

			return dto;
		} catch (Exception e) {
			e.printStackTrace();
			return new WebPageResultDto("400", "保存失败！" + e.getMessage(), "");
		}
	}

	/**
	 * 饭卡配置信息
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getconfig")
	@ResponseBody
	public WebPageResultDto getconfig(HttpServletRequest request) {

		String food_id = request.getParameter("food_id");//饭卡组名称
		try {
			if (StringUtils.isNotEmpty(food_id)) {
				VirtFoodConfig   sModel = virtFoodConfigManager.getByFoodId(Long.parseLong(food_id));
				WebPageResultDto dto    = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", sModel);

				return dto;
			} else {
				return new WebPageResultDto("400", "饭卡ID为空", "");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new WebPageResultDto("400", "保存失败！" + e.getMessage(), "");
		}
	}

	/**
	 * 饭卡删除
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "delete")
	@ResponseBody
	public WebPageResultDto deleteFood(HttpServletRequest request) {

		String id = request.getParameter("id");//饭卡组名称
		try {
			if (StringUtils.isNotEmpty(id)) {
				VirtFood vf = virtFoodManager.get(Long.parseLong(id));
				if (vf.getApproval_status() == 2 || vf.getApproval_status() == 9) {
					return new WebPageResultDto("400", "删除失败，饭卡状态审核中或者已通过", "");
				}
				virtFoodManager.remove(Long.parseLong(id));
				WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", "");

				return dto;
			} else {
				return new WebPageResultDto("400", "饭卡ID为空", "");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new WebPageResultDto("400", "保存失败！" + e.getMessage(), "");
		}
	}

	/**
	 * 饭卡删除
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "orgedit")
	@ResponseBody
	public WebPageResultDto orgedit(HttpServletRequest request) {

		String orgid  = request.getParameter("orgid");//饭卡组名称
		String foodid = request.getParameter("foodid");
		String type   = request.getParameter("type");
		try {
			if (StringUtils.isNotEmpty(foodid)) {
				if (type.equals("add")) {
					virtFoodManager.insertFoodOrg(Long.parseLong(foodid), Long.parseLong(orgid));
				} else {
					virtFoodManager.deleteFoodOrg(Long.parseLong(foodid), Long.parseLong(orgid));
				}

				WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", "");

				return dto;
			} else {
				return new WebPageResultDto("400", "饭卡ID为空", "");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new WebPageResultDto("400", "保存失败！" + e.getMessage(), "");
		}
	}


}
