package org.cs.mgr.product.ctl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSONArray;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.cs.constants.Constants;
import org.cs.core.ctl.BaseCtl;
import org.cs.core.service.IDicService;
import org.cs.mgr.product.model.MgmProduct;
import org.cs.mgr.product.service.IMgmProductCategoryService;
import org.cs.mgr.product.service.IMgmProductService;
import org.cs.util.Pager;
import org.cs.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;


/**
 * 
 * @ClassName: MgmProduct 
 * @Description:  
 * @author: sunny_shi
 * @date: 2018-06-09 13:29:09
 */
@Controller
@RequestMapping("/mgmProductCtl")
public class MgmProductCtl extends BaseCtl {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private IMgmProductService mgmProductService;
	
	@Autowired
	private IMgmProductCategoryService mgmProductCategoryService;
	
	@Autowired
	private IDicService dicService;
	
	@RequestMapping("list")
	public String list(ModelMap mm, @RequestParam(required=false)String menuCode){
		mm.put(MENU_CODE, menuCode);
		this.set(MENU_CODE, menuCode);
		
		mm.put("diclist", this.dicService.getByType("xm"));
		mm.put("firstCategory", this.mgmProductCategoryService.firstCategory());
		mm.put("role", this.get(Constants.USER_ROLE));
		List<Map<String, Object>> twoCategory =  (List<Map<String, Object>>) this.get(Constants.TWOCATEGORY);
		mm.put("twoCategory", twoCategory);
		List<Map<String, Object>> threeCategory =  (List<Map<String, Object>>) this.get(Constants.THREECATEGORY);
		mm.put("threeCategory", threeCategory);
		List<Map<String, Object>> fourCategory =  (List<Map<String, Object>>) this.get(Constants.FOURCATEGORY);
		mm.put("fourCategory", fourCategory);
		
		return "mgr/product/list";	
	}
	
	@RequestMapping(value="list2", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
	@ResponseBody
	public String list2(int page, int pageSize, String search){
		search = search.replaceAll("null", "\"\"");
		Map<String, String> map = getMapFromJson(search);
		Map<String, Object> role = (Map<String, Object>) this.get(Constants.USER_ROLE);
		if(role.get("ONE_CATEGORY_ID") == null){
			map.put("oneid", "");
		}else{
			map.put("oneid", role.get("ONE_CATEGORY_ID").toString());
		}
		if(role.get("TWO_CATEGORY_ID") == null){
			map.put("twoid", "");
		}else{
			map.put("twoid", role.get("TWO_CATEGORY_ID").toString());
		}
		if(role.get("THREE_CATEGORY_ID") == null){
			map.put("threeid", "");
		}else{
			map.put("threeid", role.get("THREE_CATEGORY_ID").toString());
		}
		if(role.get("FOUR_CATEGORY_ID") == null){
			map.put("fourid", "");
		}else{
			map.put("fourid", role.get("FOUR_CATEGORY_ID").toString());
		}
		
		Pager pager = this.mgmProductService.getMgmProducts(new Pager(page, pageSize), map);
		JSONObject json = new JSONObject();
		json.put("rows", pager.getResults());
		json.put("total", pager.getTotal());
		return JSONObject.toJSONString(json, features);
	
	}
	
	@RequestMapping("transfer")
	public String transfer(Integer id, String action, ModelMap mm){
		MgmProduct mgmProduct = null;
		if(id != null){
			mgmProduct = this.mgmProductService.findById(id);
			mm.put("mgmProduct", mgmProduct);
		}
		mm.put("diclist", this.dicService.getByType("xm"));
		mm.put("firstCategory", this.mgmProductCategoryService.firstCategory());
//		mm.put("fc", this.mgmProductCategoryService.findById(id));
		mm.put("role", this.get(Constants.USER_ROLE));
		List<Map<String, Object>> twoCategory =  (List<Map<String, Object>>) this.get(Constants.TWOCATEGORY);
		Map<String, String> map = new HashMap<>();
		if((twoCategory == null || twoCategory.isEmpty()) && mgmProduct != null){
			map.put("id", mgmProduct.getGcId().toString());
			mm.put("twoCategory", this.mgmProductCategoryService.queryShowCategory(map));
		}else{
			mm.put("twoCategory", twoCategory);
		}
		List<Map<String, Object>> threeCategory =  (List<Map<String, Object>>) this.get(Constants.THREECATEGORY);
		if((threeCategory == null || threeCategory.isEmpty()) && mgmProduct != null){
			map.put("id", mgmProduct.getGcParentId().toString());
			mm.put("threeCategory", this.mgmProductCategoryService.queryShowCategory(map));
		}else{
			mm.put("threeCategory", threeCategory);
		}
		List<Map<String, Object>> fourCategory =  (List<Map<String, Object>>) this.get(Constants.FOURCATEGORY);
		if((fourCategory == null || fourCategory.isEmpty()) && mgmProduct != null){
			if(mgmProduct.getGcThreeId() != null){
				map.put("id", mgmProduct.getGcThreeId().toString());
				mm.put("fourCategory", this.mgmProductCategoryService.queryShowCategory(map));
			}else{
				mm.put("fourCategory", fourCategory);
			}
		}else{
			mm.put("fourCategory", fourCategory);
		}
		return "mgr/product/" + action;
	}
	
	@RequestMapping(value="add", method = RequestMethod.POST)
	@ResponseBody
	public String add(MgmProduct mgmProduct,String id1, String id2, String id3, String id4){
		if(mgmProduct != null ){
			if(StringUtil.isNotBlank(id1)){
				mgmProduct.setGcId(Integer.valueOf(id1));
			}
			if(StringUtil.isNotBlank(id2)){
				mgmProduct.setGcParentId(Integer.valueOf(id2));
						}
			if(StringUtil.isNotBlank(id3)){
				mgmProduct.setGcThreeId(Integer.valueOf(id3));
			}
			if(StringUtil.isNotBlank(id4)){
				mgmProduct.setGcFourId(Integer.valueOf(id4));
			}
			return this.mgmProductService.addMgmProduct(mgmProduct);
		}
		return AJAX_SUCCESS;
	}

    @RequestMapping(value="edit", method = RequestMethod.POST)
    @ResponseBody
    public String edit(MgmProduct mgmProduct){
        if(mgmProduct != null ){
        	return this.mgmProductService.updateMgmProduct(mgmProduct);
        }
        return AJAX_SUCCESS;
    }

	
	
	
	@RequestMapping("del")
	@ResponseBody
	public String del(Integer id){
		if(id != null){
			this.mgmProductService.delMgmProduct(id);
		}
		
		return AJAX_SUCCESS;
	}
	
	@RequestMapping("updown")
	@ResponseBody
	public String upDown(Integer id, String state){
		if(id != null){
			MgmProduct mgmProduct = this.mgmProductService.findById(id);
			mgmProduct.setProductState(state);
			if("2".equals(state)){
				mgmProduct.setUnsaleTime(new Date());
			}
			this.mgmProductService.update(mgmProduct);
		}
		
		return AJAX_SUCCESS;
	}

	/**
	 *
	 * Description:TODO 將當前產品推送到遠端服務器
	 * Author:JJT
	 * Date:2018年10月19日
	 * @param id
	 * @return
	 **/
	@RequestMapping("remote")
	@ResponseBody
	public String remoteApp(Integer id){
		if(id != null){
			MgmProduct mgmProduct = this.mgmProductService.findById(id);
			String remoteUrl = "https://nuxls.com/breeze/mamy/Ingress?vendor=dxt";

			JSONObject data = new JSONObject();
			data.put("id",mgmProduct.getId()==null?" ":mgmProduct.getId());
			data.put("name",mgmProduct.getProductName()==null?"":mgmProduct.getProductName());
			String productPrice=mgmProduct.getProductPrice();
			if(productPrice==null){
//						"{\"code\":500,\"data\":价格为空\"\"}"
				return AJAX_FAIL;
			}else{
				boolean isNum=isNumeric(productPrice);
				if(!isNum){
//							AJAX_FAIL="{\"code\":500,\"data\":价格不是一个数字\"\"}";
					return AJAX_FAIL;
				}
			}
			data.put("price", productPrice);
			String productMsg=mgmProduct.getProductMsg();
			if(productMsg==null){
				return AJAX_FAIL;
			}
			data.put("description", productMsg);
			data.put("deliveryType", 0);
			JSONArray ar = new JSONArray();
			ar.add(data);
			JSONObject data1 = new JSONObject();
			data1.put("dataType", "Product");
			data1.put("data", ar);

			JSONArray a = new JSONArray();
			a.add(data1);

			JSONObject o = new JSONObject();
			o.put("appSecret", "c623710d-6ba4-4b46-a653-9c168bf9e27b");
			o.put("payload", a);
			String jsonData = o.toString();
			boolean flag=postBody(remoteUrl,jsonData);
			if(flag){
				return AJAX_SUCCESS;
			}else{
				return AJAX_FAIL;
			}
		}
		return AJAX_FAIL;

	}
	/**
	 * 利用正则表达式判断字符串是否是数字
	 * @param str
	 * @return
	 */
	public boolean isNumeric(String str){
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if( !isNum.matches() ){
			return false;
		}
		return true;
	}
	public static boolean postBody(String URL, String param) {
		boolean flag=false;
		// 创建默认的httpClient实例.
		CloseableHttpClient httpclient = HttpClients.createDefault();

		// 创建httppost
		HttpPost httppost = new HttpPost(URL);

		String result = null;

		UrlEncodedFormEntity uefEntity;
		try {
			StringEntity entity = new StringEntity(param);

			entity.setContentEncoding("UTF-8");

			entity.setContentType("application/json");// 设置为 json数据

			httppost.setEntity(entity);

			System.out.println("executing request " + httppost.getURI());

			CloseableHttpResponse response = httpclient.execute(httppost);
			int remoteCode=response.getStatusLine().getStatusCode();
			if(remoteCode==200){
				flag=true;
			}
			try {
				HttpEntity resentity = response.getEntity();
				if (resentity != null) {
					result = EntityUtils.toString(resentity, "UTF-8");
					System.out.println("--------------------------------------");
					System.out.println("Response content: " + result);
					System.out.println("--------------------------------------");
				}
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭连接,释放资源
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return flag;
	}
}

