package lingtao.net.service;

import java.io.OutputStream;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import lingtao.net.bean.Msg;
import lingtao.net.bean.QuoteData;
import lingtao.net.bean.SysRole;
import lingtao.net.bean.SysUser;
import lingtao.net.controller.CustomerDataControlle;
import lingtao.net.dao.QuoteDataMapper;
import lingtao.net.dao.SysRoleMapper;
import lingtao.net.util.DateFormatUtils;

@Service
public class QuoteDataService {

	@Autowired
	private QuoteDataMapper quoteDataMapper;

	@Autowired
	private SysRoleMapper roleMapper;

	@Autowired
	private SysRoleMapper sysRolemapper;

	/**
	 * 根据角色身份查询数据列表
	 */
	public List<QuoteData> quoteDatas(QuoteData quoteData) {
		quoteData.setQuoteTimeEnd(new DateFormatUtils().formatEndTime(quoteData.getQuoteTimeBegin()));
		quoteData.setQuoteTimeBegin(new DateFormatUtils().formatBeginTime(quoteData.getQuoteTimeBegin()));
		// 用户所拥有的角色
		SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
		String[] roleArr = user.getRole().split(",");
		// 转成list，拿掉‘组长’身份
		List<String> list = new ArrayList<String>(Arrays.asList(roleArr));
		// 判断是否拥有超管身份标识
		boolean isSuper = false;
		boolean isAllShop = false;
		for (int i = 0; i < roleArr.length; i++) {
			// 有【超级管理员】身份,状态改为true
			if ("1".equals(roleArr[i])) {
				isSuper = true;
				break;
			}
			// 有【全部店铺】身份,状态改为true
			if ("777".equals(roleArr[i])) {
				isAllShop = true;
				break;
			}
			// 如果有【店长/考试审核员/客服/组长/IP管理员/操作日志/不填旺旺】身份，去掉。不带去查询
			if ("666".equals(roleArr[i]) || "888".equals(roleArr[i]) || "999".equals(roleArr[i])
					|| "1011".equals(roleArr[i]) || "1015".equals(roleArr[i]) || "1042".equals(roleArr[i])
					|| "1049".equals(roleArr[i])) {
				list.remove(roleArr[i]);
			}
		}
		// 将list转为String[] 数组
		roleArr = list.toArray(new String[list.size()]);
		// 如果没有【超级管理员/全部店铺】身份
		if (!isSuper && !isAllShop) {
			// 再判断有没有查询条件且没有选择查找条件
			// 全部属性为空 true:没有查询条件 false:有查询条件
			boolean isNullFlag = true;
			try {
				// 前台会带用户的角色回来，上面已经获取，这里设置null不影响
				quoteData.setRole(null);
				// 判断quoteData对象是否有属性(查询条件)
				for (Field f : quoteData.getClass().getDeclaredFields()) {
					f.setAccessible(true);
					if (f.get(quoteData) != null && StringUtils.isNotBlank(f.get(quoteData).toString())) {
						// 有属性
						isNullFlag = false;
						break;
					}
				}
			} catch (IllegalArgumentException | IllegalAccessException e) {
				e.printStackTrace();
			}
			// 如果有多个店铺角色
			if (roleArr.length > 1) {
				// 全部属性为空 即没有条件查询，默认查出所有的店铺数据
				if (isNullFlag) {
					quoteData.setRoleArr(roleArr);
				} else {// 不为空，根据店铺和条件查询数据
					quoteData.setRoleSearchArr(roleArr);
				}
			} else {// 只有一个角色
				quoteData.setRoleSearch(roleArr[0]);
			}
		}
		// 如果有【超管】，但是没有【所有店铺】，隐藏非本部店铺
		if (isSuper && !isAllShop) {
			quoteData.setIsSelfShop("0");
		}
		// 有【超管、全部店铺】直接走这
		return quoteDataMapper.quoteDatas(quoteData);
	}

	public Msg updateById(int id, String field, String value, String username) {
		QuoteData quoteData = new QuoteData();
		SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
		boolean flag = new CustomerDataControlle().isSuperOrManager();
		// 如果修改的是店长评语，判断有没有【组长】身份
		if ("commentManager".equals(field)) {
			// 超管、组长身份才允许修改comment
			if (!flag) {
				return Msg.fail("只允许店长修改！");
			}
			quoteData.setCommentManager(value);
		} else if ("price".equals(field) || "buyPrice".equals(field)) {// 如果是价格/成交价格，组长和自己都能改
			if (!flag && !username.equals(user.getUsername())) {
				return Msg.fail("除店长外，不允许修改他人的数据！");
			}
			if ("price".equals(field)) {
				quoteData.setPrice(Double.valueOf(value));
			} else if ("buyPrice".equals(field)) {
				quoteData.setBuyPrice(Double.valueOf(value));
			}
		} else {
			// 只有自己的数据才能更改【客户旺旺】
			if (!username.equals(user.getUsername())) {
				return Msg.fail("只允许修改自己的数据！");
			}
			if ("wangwang".equals(field)) {
				quoteData.setWangwang(value);
				// 填写客户旺旺的时候，更改填写状态
				quoteData.setIsFillIn("1");
			} else if ("commentSelf".equals(field)) {
				quoteData.setCommentSelf(value);
			}
		}
		quoteData.setId(id);
		quoteDataMapper.updateById(quoteData);

		return Msg.success();
	}

	/**
	 * 获取报价过的产品种类
	 * 
	 * @return
	 */
	public List<String> getProType() {
		return quoteDataMapper.getProType();
	}

	/**
	 * 修改【是否当天成交】状态
	 * 
	 * @param id
	 * @return
	 */

	public Msg changeIsBuyToDay(Integer id) {
		try {
			quoteDataMapper.changeIsBuyToDay(id);
			return Msg.success();
		} catch (Exception e) {
			return Msg.fail();
		}
	}

	/**
	 * 修改【是否成交】状态
	 * 
	 * @param id
	 * @return
	 */
	public Msg changeIsBuy(Integer id) {
		try {
			quoteDataMapper.changeIsBuy(id);
			return Msg.success();
		} catch (Exception e) {
			return Msg.fail();
		}
	}

	/**
	 * 修改所属店铺以及选择状态
	 * 
	 * @param id
	 * @return
	 */
	public Msg updateShopnameSelect(String shopname, Integer id) {
		try {
			quoteDataMapper.updateShopnameSelect(shopname, id);
			return Msg.success();
		} catch (Exception e) {
			return Msg.fail();
		}
	}

	/**
	 * 填写成交订单号
	 * 
	 * @param orderNumber
	 * @return
	 */
	public Msg addOrderNumber(Integer id, String orderNumber) {
		try {
			quoteDataMapper.addOrderNumber(id, orderNumber);
			return Msg.success();
		} catch (Exception e) {
			return Msg.fail();
		}
	}

	/**
	 * 柱状图
	 * 
	 * @param quoteData
	 * @return
	 */
	public Map<String, Object> echartZhuList(QuoteData quoteData,int isKefu) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<String> sname = new ArrayList<String>();// 获取数据中有的店铺名称
		List<Double> allData = new ArrayList<Double>();// 所有数据条数
		List<Double> allNotBuy = new ArrayList<Double>();// 合计未成交
		List<Double> allBuy = new ArrayList<Double>();// 合计已成交
		List<Double> todayBuy = new ArrayList<Double>();// 合计当天已成交
		List<Double> notTodaybuy = new ArrayList<Double>();// 合计跟单后已成交
		List<Double> allBuyPrice = new ArrayList<Double>();// 所有成交金额
		List<Double> todayBuyPrice = new ArrayList<Double>();// 当天成交金额
		List<Double> notTodayBuyPrice = new ArrayList<Double>();// 跟单成交金额
		List<Double> allBuyPercentage = new ArrayList<Double>();// 成交百分比
		List<QuoteData> allDataList = new ArrayList<QuoteData>();// 所有数据

		// 判断是否拥有超管身份标识
		boolean isNoSuper = true;
		boolean isNoAllShop = true;
		long startTime, endTime = 0;
		startTime = System.currentTimeMillis();
		quoteData.setQuoteTimeEnd(new DateFormatUtils().formatEndTime(quoteData.getQuoteTimeBegin()));
		quoteData.setQuoteTimeBegin(new DateFormatUtils().formatBeginTime(quoteData.getQuoteTimeBegin()));
		// 如果是通过‘所属店铺’查询
		// 只根据店铺查===>查出该店铺人员该店铺的报价数据
		if(isKefu != 0) {//判断是否统计客服大单信息
			List<String> realnameList = new ArrayList<String>();
			// 根据店铺搜索该店铺有的人员
			String roleSearch = "999";
			if(quoteData.getRoleSearch() != "") {
				roleSearch = roleSearch.concat(",").concat(quoteData.getRoleSearch());
			}
			realnameList = quoteDataMapper.getRealnames(roleSearch);
			// 根据人员查询数据
			for (String realname : realnameList) {
				quoteData.setShopname(quoteData.getRoleSearch());
				quoteData.setRealname(realname);
				QuoteData echartList = quoteDataMapper.getKefuEchartList(quoteData);
				// X坐标展示客服名字
				sname.add(realname);
				allDataList.add(echartList);
			}
		}else if (StringUtils.isNotEmpty(quoteData.getRoleSearch()) && StringUtils.isEmpty(quoteData.getRealname())
				&& !"1".equals(quoteData.getByProTypeLabel())) {
			// 店铺人员集合
			List<String> realnameList = new ArrayList<String>();
			// 根据店铺搜索该店铺有的人员
			realnameList = quoteDataMapper.getRealnames(quoteData.getRoleSearch());
			// 根据人员查询数据
			for (String realname : realnameList) {
				quoteData.setShopname(quoteData.getRoleSearch());
				quoteData.setRealname(realname);
				QuoteData echartList = quoteDataMapper.getEchartList(quoteData);
				// X坐标展示客服名字
				sname.add(realname);
				allDataList.add(echartList);
			}
		} else if ("1".equals(quoteData.getByProTypeLabel()) && StringUtils.isEmpty(quoteData.getRoleSearch())
				&& StringUtils.isEmpty(quoteData.getRealname())) { // 只根据产品查==>查出报价的所有产品
			// 产品
			List<String> productList = new ArrayList<String>();
			// 报价中有的产品
			productList = this.getProType();
			// 根据人员查询数据
			for (String product : productList) {
				quoteData.setProTypeLabel(product);
				QuoteData echartList = quoteDataMapper.getEchartList(quoteData);
				// X坐标展示产品
				sname.add(product);
				allDataList.add(echartList);
			}
		} else if (StringUtils.isNotEmpty(quoteData.getRoleSearch())
				&& StringUtils.isNotEmpty(quoteData.getRealname())) { // 根据店铺及人员查==>查询人员该店铺的产品报价
			// 产品
			List<String> productList = new ArrayList<String>();
			// 报价中有的产品
			productList = this.getProType();
			// 根据人员查询数据
			for (String product : productList) {
				quoteData.setProTypeLabel(product);
				quoteData.setShopname(quoteData.getRoleSearch());
				quoteData.setRealname(quoteData.getRealname());
				QuoteData echartList = quoteDataMapper.getEchartList(quoteData);
				// X坐标展示产品
				sname.add(product);
				allDataList.add(echartList);
			}
		} else if (StringUtils.isNotEmpty(quoteData.getRoleSearch()) && "1".equals(quoteData.getByProTypeLabel())
				&& StringUtils.isEmpty(quoteData.getRealname())) { // 查询店铺的产品
			// 产品
			List<String> productList = new ArrayList<String>();
			// 报价中有的产品
			productList = this.getProType();
			// 根据人员查询数据
			for (String product : productList) {
				quoteData.setShopname(quoteData.getRoleSearch());
				quoteData.setProTypeLabel(product);
				QuoteData echartList = quoteDataMapper.getEchartList(quoteData);
				// X坐标展示产品
				sname.add(product);
				allDataList.add(echartList);
			}
		} else if (StringUtils.isNotEmpty(quoteData.getRealname()) && StringUtils.isEmpty(quoteData.getRoleSearch())
				&& !"1".equals(quoteData.getByProTypeLabel())) { // 只根据名字查==>查该人员所有店铺的产品报价
			// 产品
			List<String> productList = new ArrayList<String>();
			// 报价中有的产品
			productList = this.getProType();
			// 根据人员查询数据
			for (String product : productList) {
				quoteData.setProTypeLabel(product);
				quoteData.setRealname(quoteData.getRealname());
				QuoteData echartList = quoteDataMapper.getEchartList(quoteData);
				sname.add(product);
				allDataList.add(echartList);
			}
		} else {
			// 用户所拥有的角色
			SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
			String[] roleArr = user.getRole().split(",");
			for (int i = 0; i < roleArr.length; i++) {
				// 有【超级管理员、全部店铺】身份,状态改为false
				if ("1".equals(roleArr[i])) {
					isNoSuper = false;
					break;
				}
				if ("777".equals(roleArr[i])) {
					isNoAllShop = false;
					break;
				}
			}
			// 报价数据中拥有的店铺
			// List<String> shopName = quoteDataMapper.getShopName(quoteData);
			List<String> shopName = new ArrayList<String>();

			// 如果没有【超管、所有店铺】，直接把自己的拥有的店铺拿去查询数据，同时排除特殊角色
			if (isNoSuper && isNoAllShop) {
				// 获取【不允许被创建】的特殊角色id
				List<Integer> specialRoleIdList = roleMapper.getRoleIdsWhenIsNotRegist();
				// shopName.clear();
				for (String shopname : roleArr) {
					// 是否拥有特殊角色标识
					boolean specialFlag = false;
					for (int j = 0; j < specialRoleIdList.size(); j++) {
						// 如果用户拥有的角色属于不可被创建的特殊角色，就排除，不加到图形中统计
						if (specialRoleIdList.get(j).toString().equals(shopname)) {
							specialFlag = true;
							break;
						}
					}
					// 不是特殊角色，就加到列表中
					if (!specialFlag) {
						shopName.add(shopname);
					}
				}
			} else {// 有【超管】或者有【所有店铺】
				// 报价数据中拥有的店铺
				shopName = quoteDataMapper.getShopName(quoteData);
				// 如果有【超管】，但是没有【所有店铺】，把非公司店铺去除掉
				if (!isNoSuper && isNoAllShop) {
					// 别的公司的店铺ID
					List<Integer> otherRoleIdList = roleMapper.getRoleIdsWhenIsNotLingTao();
					for (int i = 0; i < shopName.size(); i++) {
						// 其他公司店铺标识
						boolean otherFlag = false;
						for (int j = 0; j < otherRoleIdList.size(); j++) {
							// 如果报价中的店铺是别的公司的店铺，就排除，不加到图形中统计
							if (otherRoleIdList.get(j).toString().equals(shopName.get(i).toString())) {
								otherFlag = true;
								break;
							}
						}
						// 是别的公司的店铺，就移除
						if (otherFlag) {
							shopName.remove(i);
							i--;
						}
					}
				}
			}
			// 根据店铺查询数据
			for (String shopname : shopName) {
				quoteData.setShopname(shopname);
				QuoteData echartList = quoteDataMapper.getEchartList(quoteData);
				sname.add(shopname);
				allDataList.add(echartList);
			}
		}

		// 排序
		Collections.sort(allDataList, new Comparator<QuoteData>() {
			@Override
			public int compare(QuoteData o1, QuoteData o2) {
				return (int) (o2.getAllData() - o1.getAllData());
			}
		});

		for (QuoteData data : allDataList) {
			allData.add(data.getAllData());
			allBuy.add(data.getAllBuy());
			allNotBuy.add(data.getAllNotBuy());
			todayBuy.add(data.getTodayBuy());
			notTodaybuy.add(data.getNotTodayBuy());
			allBuyPrice.add(data.getAllBuyPrice());
			todayBuyPrice.add(data.getTodayBuyPrice());
			notTodayBuyPrice.add(data.getNotTodayBuyPrice());
			allBuyPercentage.add(data.getAllBuyPercentage());
		}
		map.put("sname", sname);
		map.put("one", allData);
		map.put("two", allBuy);
		map.put("three", allNotBuy);
		map.put("four", todayBuy);
		map.put("five", notTodaybuy);
		map.put("six", allBuyPrice);
		map.put("seven", todayBuyPrice);
		map.put("eight", notTodayBuyPrice);
		map.put("nine", allBuyPercentage);
		endTime = System.currentTimeMillis();
		System.out.println("getShopName使用的时间:" + (endTime - startTime));
		return map;
	}

	@SuppressWarnings("resource")
	public void excel(HttpServletResponse response, QuoteData quoteData) throws Exception {
		response.setCharacterEncoding("UTF-8");
		List<QuoteData> quoteDatasList = new ArrayList<QuoteData>();
		List<SysRole> allRoleNameList = sysRolemapper.getAllRoleName(null);

		// 需要导出的数据
		quoteDatasList = quoteDatas(quoteData);

		// 创建excel文件
		XSSFWorkbook wb = new XSSFWorkbook();
		// 创建sheet页
		XSSFSheet sheet = wb.createSheet("总表");
		// 创建excel文件
//		HSSFWorkbook wb = new HSSFWorkbook();
		// 创建sheet页
//		HSSFSheet sheet = wb.createSheet("总表");
		String filename = "客服操作数据";
		String shopname = "";
		String isToDayBuy = "未成交";
		String isBuy = "未成交";

		// 创建标题行
		XSSFRow titleRow = sheet.createRow(0);
		// 创建标题行
//		HSSFRow titleRow = sheet.createRow(0);
		titleRow.createCell(0).setCellValue("操作人");
		titleRow.createCell(1).setCellValue("数据所属店铺");
		titleRow.createCell(2).setCellValue("客户旺旺");
		titleRow.createCell(3).setCellValue("操作");
		titleRow.createCell(4).setCellValue("金额");
		titleRow.createCell(5).setCellValue("当天成交");
		titleRow.createCell(6).setCellValue("未成交原因");
		titleRow.createCell(7).setCellValue("跟单后成交");
		titleRow.createCell(8).setCellValue("成交金额");
		titleRow.createCell(9).setCellValue("店长追踪情况汇报");
		titleRow.createCell(10).setCellValue("操作时间");
		// 遍历将数据放到excel列中
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for (QuoteData quoteDatas : quoteDatasList) {
			shopname = "";
			isToDayBuy = "未成交";
			isBuy = "未成交";
			for (SysRole sysRole : allRoleNameList) {
				if (String.valueOf(sysRole.getRoleId()).equals(quoteDatas.getShopname())) {
					shopname = sysRole.getRoleName();
					break;
				}
			}
			if (quoteDatas.getIsBuyToDay().equals("1")) {
				isToDayBuy = "已成交";
			}
			if (quoteDatas.getIsBuy().equals("1")) {
				isBuy = "已成交";
			}
			XSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
//			HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
			dataRow.createCell(0).setCellValue(quoteDatas.getRealname());
			dataRow.createCell(1).setCellValue(shopname);
			dataRow.createCell(2).setCellValue(quoteDatas.getWangwang());
			dataRow.createCell(3).setCellValue(quoteDatas.getRemark());
			dataRow.createCell(4).setCellValue(quoteDatas.getPrice());
			dataRow.createCell(5).setCellValue(isToDayBuy);
			dataRow.createCell(6).setCellValue(quoteDatas.getCommentSelf());
			dataRow.createCell(7).setCellValue(isBuy);
			dataRow.createCell(8).setCellValue(quoteDatas.getBuyPrice() != null ? quoteDatas.getBuyPrice() : 0);
			dataRow.createCell(9).setCellValue(quoteDatas.getCommentManager());
			dataRow.createCell(10).setCellValue(formatter.format(quoteDatas.getQuoteTime()));
		}

		// 设置下载时客户端Excel的名称
		response.setContentType("application/octet-stream;charset=utf-8");
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String(filename.getBytes(), "iso-8859-1") + ".xls");// + ".xls"

		OutputStream ouputStream = response.getOutputStream();
		wb.write(ouputStream);
		ouputStream.flush();
		ouputStream.close();
	}
}
