package com.uas.platform.b2b.erp.controller;

import com.alibaba.fastjson.JSON;
import com.uas.platform.b2b.erp.model.B2BCustomer;
import com.uas.platform.b2b.erp.model.B2BVendor;
import com.uas.platform.b2b.erp.model.PageInfo;
import com.uas.platform.b2b.model.InvitationRecord;
import com.uas.platform.b2b.model.SearchFilter;
import com.uas.platform.b2b.model.User;
import com.uas.platform.b2b.search.SearchService;
import com.uas.platform.b2b.service.*;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.b2b.temporary.model.BasePartnersInfo;
import com.uas.platform.core.model.Constant;
import com.uas.platform.core.model.Status;
import com.uas.platform.core.util.serializer.FlexJsonUtils;
import com.uas.search.b2b.model.MultiValue;
import com.uas.search.b2b.model.PageParams;
import com.uas.search.b2b.model.SPage;
import com.uas.search.b2b.model.Sort;
import com.uas.search.b2b.util.SearchConstants;
import com.uas.sso.entity.UserSpaceView;
import com.uas.sso.support.Page;
import com.uas.sso.util.AccountUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

/**
 * erp查询企业圈数据接口
 * 
 * @author hejq
 * @time 创建时间：2017年5月23日
 */
@RestController
@RequestMapping(value = "/erp/userSpaceDetail")
public class UserSpaceDetailController {

	@Autowired
	private SearchService searchService;

	@Autowired
	private InvitationRecordService invitationRecordService;

	@Autowired
	private PurcOrderService purcOrderService;

	@Autowired
	private AddPartnerService addPartnerService;

	@Autowired
	private UserService userService;

	@Autowired
	private VendorService vendorService;

	/**
	 * 获取添加合作伙伴数据
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(method = RequestMethod.GET)
	public Page<UserSpaceView> UserSpaceInfo(@RequestParam("data") String data) throws UnsupportedEncodingException {
		Page<UserSpaceView> details = new Page<UserSpaceView>();
		String jsonStr = URLDecoder.decode(data, "UTF-8");
		PageInfo pageInfo = FlexJsonUtils.fromJson(jsonStr, PageInfo.class);
		com.uas.platform.core.model.PageParams params = new com.uas.platform.core.model.PageParams();
		params.setPage(pageInfo.getPageNumber());
		params.setCount(pageInfo.getPageSize());
		PageParams pageParams = searchService.convertPageParams(params, null);
		pageParams.getFilters().put("searchstatus", Constant.YES);
		try {
			details = AccountUtils.getUserSpacesByKeyword(pageInfo.getKeyword(), params.getPage(), params.getCount());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return details;
	}
	
	/**
	 * 获取邀请记录
	 *
	 * @param data
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value="/invitations", method = RequestMethod.GET)
	public Page<InvitationRecord> invitations(@RequestParam("data") String data, @RequestParam("onlySelf") String onlySelf) throws UnsupportedEncodingException {
		Page<InvitationRecord> records = new Page<InvitationRecord>();
		String jsonStr = URLDecoder.decode(data, "UTF-8");
		PageInfo pageInfo = FlexJsonUtils.fromJson(jsonStr, PageInfo.class);
		onlySelf = URLDecoder.decode(onlySelf, "UTF-8");
		// 是否只看自己，是为1，查看所有为0
		Integer ifSelf = FlexJsonUtils.fromJson(onlySelf, Integer.class);
		com.uas.platform.core.model.PageParams params = new com.uas.platform.core.model.PageParams();
		params.setPage(pageInfo.getPageNumber());
		params.setCount(pageInfo.getPageSize());
		PageParams pageParams = searchService.convertPageParams(params, null);
		try {
			if (pageInfo.getEnuu() != null) {
				pageParams.getFilters().put("in_enuu", pageInfo.getEnuu());
			} else {
				pageParams.getFilters().put("in_enuu", SystemSession.getUser().getEnterprise().getUu());
			}
			if (ifSelf == 1) { // 只看自己就加入自己uu过滤，查看所有就加入已激活状态，只显示已注册邀请。
				if (pageInfo.getUseruu() != null) {
					// 如果传入的uu在本企业找不到角色，就返回空
					User user = userService.findUserByEnUUAndUserUU(SystemSession.getUser().getEnterprise().getUu(), pageInfo.getUseruu());
					if (null == user) {
						return records;
					} else {
						pageParams.getFilters().put("in_useruu", pageInfo.getUseruu());
					}
				}
			} else {
				pageParams.getFilters().put("in_active", Constant.YES);
			}
			SPage<InvitationRecord> details = searchService.getInvitationByKeyword(pageInfo.getKeyword(), pageParams);
			records.setContent(details.getContent());
			records.setNumber(details.getPage());
			records.setTotalElements(details.getTotalElement());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return records;
	}

	/**
	 * ERP获取供应商
	 */
	@RequestMapping(value = "/vendor", method = RequestMethod.GET)
	@ResponseBody
	public Page<B2BVendor> getVendors(@RequestParam("pageInfo") String pageInfo) throws UnsupportedEncodingException {
		String jsonStr = URLDecoder.decode(pageInfo, "UTF-8");
		PageInfo info = JSON.parseObject(jsonStr, PageInfo.class);
		String keyword = info.getKeyword();
		PageParams pageParams = new PageParams();
		pageParams.setSize(info.getPageSize());
		pageParams.setPage(info.getPageNumber());
		ModelMap map = new ModelMap();
		map.put("ve_myenuu", SystemSession.getUser().getEnterprise().getUu());
		map.put("ve_vendswitch", Constant.YES);
		ModelMap notMap = new ModelMap();
		pageParams.setNotEqualFilters(notMap);
		List<Sort> sortList = new ArrayList<>();
		sortList.add(new Sort("ve_id", false, Sort.Type.LONG, new Long(1)));
		map.put(SearchConstants.SORT_KEY, sortList);
		pageParams.setFilters(map);
		return searchService.searchVendorForErp(keyword, pageParams);
	}

	/**
	 * ERP获取服务商
	 */
	@RequestMapping(value = "/servicer", method = RequestMethod.GET)
	@ResponseBody
	public Page<B2BVendor> getServicer(@RequestParam("pageInfo") String pageInfo) throws UnsupportedEncodingException {
		String jsonStr = URLDecoder.decode(pageInfo, "UTF-8");
		PageInfo info = JSON.parseObject(jsonStr, PageInfo.class);
		String keyword = info.getKeyword();
		PageParams pageParams = new PageParams();
		pageParams.setSize(info.getPageSize());
		pageParams.setPage(info.getPageNumber());
		ModelMap map = new ModelMap();
		map.put("ve_myenuu", SystemSession.getUser().getEnterprise().getUu());
		map.put("ve_servicerswitch", Constant.YES);
		ModelMap notMap = new ModelMap();
		pageParams.setNotEqualFilters(notMap);
		List<Sort> sortList = new ArrayList<>();
		sortList.add(new Sort("ve_id", false, Sort.Type.LONG, new Long(1)));
		map.put(SearchConstants.SORT_KEY, sortList);
		pageParams.setFilters(map);
		return searchService.searchVendorForErp(keyword, pageParams);
	}


	/**
	 * 获取客户
	 */
	@RequestMapping(value = "/customer", method = RequestMethod.GET)
	@ResponseBody
	public Page<B2BCustomer> getCustomers(@RequestParam("pageInfo") String pageInfo) throws UnsupportedEncodingException {
		String jsonStr = URLDecoder.decode(pageInfo, "UTF-8");
		PageInfo info = JSON.parseObject(jsonStr, PageInfo.class);
//		customer = URLDecoder.decode(customer, "UTF-8");
//		List<Object> custUUs = JSON.parseArray(customer, Object.class);
		String keyword = info.getKeyword();
		com.uas.search.b2b.model.PageParams pageParams = new com.uas.search.b2b.model.PageParams();
		pageParams.setSize(info.getPageSize());
		pageParams.setPage(info.getPageNumber());
		ModelMap map = new ModelMap();
		map.put("ve_vendenuu", SystemSession.getUser().getEnterprise().getUu());
		map.put("ve_custswitch", Constant.YES);
		ModelMap notMap = new ModelMap();
//        notMap.put("ve_myenuu", new MultiValue(custUUs, true));
		pageParams.setNotEqualFilters(notMap);
		List<Sort> sortList = new ArrayList<>();
		SearchFilter filter = userService.distribute();
		if (filter != null && filter.getDistribute() == null) {
			return null;
		}
		if (filter != null && !org.springframework.util.CollectionUtils.isEmpty(filter.getDistribute())) {
			List<Object> list = new ArrayList<>();
			list.addAll(filter.getDistribute());
			map.put("ve_myenuu", new MultiValue(list, true));
		}
		sortList.add(new Sort("ve_id", false, Sort.Type.LONG, new Long(1)));
		map.put(SearchConstants.SORT_KEY, sortList);
		pageParams.setFilters(map);
		return searchService.searchCustomerForErp(keyword, pageParams);
	}

	/**
	 * UAS合作伙伴<br>
	 * 请求者的名义查看个人的发出的请求<br>
	 * 已通过(全部合作伙伴)
	 *
	 * @param data
	 * @return
	 */
	@RequestMapping(value = "/request", method = RequestMethod.GET)
	@ResponseBody
	public Page<BasePartnersInfo> getDoneRequest(@RequestParam("data") String data) throws Exception {
		String jsonStr = URLDecoder.decode(data, "UTF-8");
		PageInfo info = JSON.parseObject(jsonStr, PageInfo.class);
//		vendor = URLDecoder.decode(vendor, "UTF-8");
//		List<Long> vendUUs = JSON.parseArray(vendor, Long.class);
//		customer = URLDecoder.decode(customer, "UTF-8");
//		List<Long> custUUs = JSON.parseArray(customer, Long.class);
		String keyword = info.getKeyword();
		PageParams pageParams = new PageParams();
		pageParams.setSize(info.getPageSize());
		pageParams.setPage(info.getPageNumber());
		return addPartnerService.findByBusCodeAndKeyWordForERP(keyword, Status.ENABLED.value(), pageParams.getSize(),
				pageParams.getPage());
	}


	/**
	 * 添加为供应商
	 *
	 * @param businessCode
	 * @return
	 */
	@RequestMapping(value = "/addSupplier", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap addSupplier(@RequestParam("businessCode") String businessCode) throws UnsupportedEncodingException {
		businessCode = URLDecoder.decode(businessCode, "UTF-8");
		return addPartnerService.addSupplier(businessCode);
	}

	/**
	 * 添加为服务商
	 *
	 * @param businessCode
	 * @return
	 */
	@RequestMapping(value = "/addServicer", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap addServicer(@RequestParam("businessCode") String businessCode) throws UnsupportedEncodingException {
		businessCode = URLDecoder.decode(businessCode, "UTF-8");
		return addPartnerService.addServicer(businessCode);
	}

	/**
	 * 添加为客户
	 *
	 * @param businessCode
	 * @return
	 */
	@RequestMapping(value = "/addCust", method = RequestMethod.POST)
	@ResponseBody
	public ModelMap addCust(@RequestParam("businessCode") String businessCode) throws UnsupportedEncodingException {
		businessCode = URLDecoder.decode(businessCode, "UTF-8");
		return addPartnerService.addCust(businessCode);
	}

	/**
	 * 解除供应商关系（禁用）
	 *
	 * @param id
	 */
	@RequestMapping(value = "/relieve", method = RequestMethod.POST)
	@ResponseBody
	private ModelMap relieve(@RequestParam("id") Long id) {
		return purcOrderService.relieve(id);
	}

	/**
	 * 启用供应商
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/activeVend", method = RequestMethod.POST)
	@ResponseBody
	private ModelMap activeVend(@RequestParam("id") Long id) {
		return purcOrderService.activeVend(id);
	}

	/**
	 * 解除服务商关系（禁用）
	 *
	 * @param id
	 */
	@RequestMapping(value = "/relieveServicer", method = RequestMethod.POST)
	@ResponseBody
	private ModelMap relieveServicer(@RequestParam("id") Long id) {
		return purcOrderService.relieveServicer(id);
	}

	/**
	 * 启用服务商
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/activeServicer", method = RequestMethod.POST)
	@ResponseBody
	private ModelMap activeServicer(@RequestParam("id") Long id) {
		return purcOrderService.activeServicer(id);
	}

	/**
	 * 禁用客户
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/disableCust", method = RequestMethod.POST)
	@ResponseBody
	private ModelMap disableCust(@RequestParam("id") Long id) {
		return purcOrderService.disableCust(id);
	}

	/**
	 * 启用客户
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/activeCust", method = RequestMethod.POST)
	@ResponseBody
	private ModelMap activeCust(@RequestParam("id") Long id) {
		return purcOrderService.activeCust(id);
	}

	/**
	 * 邀请开通平台
	 *
	 * @param data
	 * @return
	 */
	@RequestMapping(value = "/invite", method = RequestMethod.POST)
	private ModelMap invite(@RequestParam("data")String data) throws UnsupportedEncodingException {
		String formStore = URLDecoder.decode(data, "UTF-8");
		InvitationRecord record = FlexJsonUtils.fromJson(formStore, InvitationRecord.class);
		return invitationRecordService.invite(record);
	}

	/**
	 * 一键同步供应商和客户(接口是返回B2B端所有该企业的供应商和客户)
	 *
	 * @return
	 */
	@RequestMapping(value = "/synchronize", method = RequestMethod.GET)
	private ModelMap  oneClickSync(Long enUU) {
		return vendorService.getVendorsAndCustomers(enUU);
	}
}
