package com.winsun.controller;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.bind.annotation.RestController;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.winsun.auth.core.annotion.Permission;
import com.winsun.auth.core.base.controller.BaseController;
import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.auth.core.shiro.ShiroUser;
import com.winsun.auth.core.util.IOUtils;
import com.winsun.bean.OrderView;
import com.winsun.bean.School;
import com.winsun.bean.SysUser;
import com.winsun.bean.YrymReport;
import com.winsun.bean.activity.HhrActivity;
import com.winsun.bean.activity.HhrActivityRecord;
import com.winsun.constant.OrderStatus;
import com.winsun.mapper.OrderViewMapper;
import com.winsun.mapper.PartnerMapper;
import com.winsun.mapper.SchoolMapper;
import com.winsun.mapper.SysUserMapper;
import com.winsun.mapper.activity.ActivityMapper;
import com.winsun.mapper.activity.ActivityRecordMapper;
import com.winsun.utils.MapUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 活动参与记录 controller
 * @Author: dongyp
 * @Date: 2020/4/14 
 */
@Slf4j
@RestController
@RequestMapping("/activityRecord")
public class ActivityRecordController extends BaseController {

	private static ActivityRecordMapper activityRecordMapper;
	private static ActivityMapper activityMapper;
	private static SysUserMapper sysUserMapper;
	private static SchoolMapper schoolMapper;
	
	@Autowired
	private PartnerMapper partnerMapper;
	@Autowired
	private OrderViewMapper orderViewMapper;

	@Autowired
	public ActivityRecordController(ActivityRecordMapper activityRecordMapper,ActivityMapper activityMapper,SysUserMapper sysUserMapper,SchoolMapper schoolMapper) {
		ActivityRecordController.activityRecordMapper = activityRecordMapper;
		ActivityRecordController.activityMapper = activityMapper;
		ActivityRecordController.sysUserMapper = sysUserMapper;
		ActivityRecordController.schoolMapper = schoolMapper;
	}
	
	@Permission(menuname = "查询活动参与信息", value = "list", method = RequestMethod.POST)
	public ResponseData<Page<Map<String, Object>>> list(@RequestParam("title") String title,
			@RequestParam("activityType") String activityType, @RequestParam("subclass") String subclass,
			@RequestParam(name = "status", required = false) String status,
			@RequestParam(name = "creator", required = false) String creator,
			@RequestParam(name = "createTimeStart", required = false) String createTimeStart,
			@RequestParam(name = "createTimeEnd", required = false) String createTimeEnd,
			@RequestParam(name = "pageNo", required = false) int pageIndex,
			@RequestParam(name = "pageSize", required = false) int pageSize) {
		Wrapper<HhrActivity> wrapperActivity = new EntityWrapper<HhrActivity>();
		wrapperActivity.like(StringUtils.isNotBlank(title), "title", title, SqlLike.DEFAULT);
		wrapperActivity.eq(StringUtils.isNotBlank(activityType), "activity_type", activityType);
		wrapperActivity.eq(StringUtils.isNotBlank(subclass), "subclass", subclass);
		wrapperActivity.eq("del_flag", 0);
		List<HhrActivity> listActivity = activityMapper.selectList(wrapperActivity);
		
		Wrapper<HhrActivityRecord> wrapperRecord = new EntityWrapper<HhrActivityRecord>();
		wrapperRecord.like(StringUtils.isNotBlank(creator), "creator", creator, SqlLike.DEFAULT);
		wrapperRecord.eq(StringUtils.isNotBlank(status), "status", status);
		List<HhrActivityRecord> listRecord = activityRecordMapper.selectList(wrapperRecord);
		
		Page<Map<String, Object>> page = new Page<>(pageIndex, pageSize);
		List<Map<String, Object>> newList = new ArrayList<Map<String,Object>>();
		for(HhrActivityRecord activityRecord : listRecord) {
			String activityId = activityRecord.getActivityId();
			
			for(HhrActivity activity : listActivity) {
				if(activityId.equals(activity.getId())) {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("title", activity.getTitle());
					map.put("desc", activity.getDesc());
					map.put("integral", activity.getIntegral());
					map.put("activityType", activity.getActivityType());
					map.put("subclass", activity.getSubclass());
					map.put("id", activityRecord.getId());
					map.put("status", activityRecord.getStatus());
					map.put("remark", activityRecord.getRemark());
					map.put("recordIntegral", activityRecord.getRecordIntegral());
					map.put("creator", activityRecord.getCreator());
					map.put("message", activityRecord.getMessage());
					map.put("createTime", activityRecord.getCreateTime());
					
					newList.add(map);
				}
			}
		}
		
		List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
		if(newList.size() < pageSize) {
			dataList = newList;
		}else {
			dataList = newList.subList((pageIndex-1)*pageSize, pageIndex*pageSize);
		}
		
		page.setRecords(dataList);
		page.setTotal(newList.size());
		return ResponseData.success(page, "查询完毕！");
	}
	
	@Permission(menuname = "审核活动参与记录", value = "auditActivityRecord", method = RequestMethod.POST)
	public ResponseData<String> auditActivityRecord(@RequestParam("id") String id, 
			@RequestParam("status") String status, @RequestParam("integral") String integral,
			@RequestParam("remark") String remark){

		HhrActivityRecord activityRecord = new HhrActivityRecord();
		activityRecord.setId(id);
		activityRecord.setStatus(status);
		activityRecord.setRecordIntegral(Integer.parseInt(integral));
		activityRecord.setRemark(remark);
		activityRecord.setUpdateTime(new Date());
		int num = activityRecordMapper.updateById(activityRecord);
		
		if (num > 0) {
			return ResponseData.success("审核完毕！");
		}

		return ResponseData.error("审核失败");
	}
	
	@Permission(menuname = "查询积分记录信息", value = "getIntegralList", method = RequestMethod.POST)
	public ResponseData<Page<Map<String, Object>>> getIntegralList(@RequestParam("title") String title,
			@RequestParam("activityType") String activityType, @RequestParam("subclass") String subclass,
			@RequestParam(name = "account", required = false) String account,
			@RequestParam(name = "name", required = false) String name,
			@RequestParam(name = "createTimeStart", required = false) String createTimeStart,
			@RequestParam(name = "createTimeEnd", required = false) String createTimeEnd,
			@RequestParam(name = "pageNo", required = false) int pageIndex,
			@RequestParam(name = "pageSize", required = false) int pageSize) {
		Wrapper<HhrActivity> wrapperActivity = new EntityWrapper<HhrActivity>();
		wrapperActivity.like(StringUtils.isNotBlank(title), "title", title, SqlLike.DEFAULT);
		wrapperActivity.eq(StringUtils.isNotBlank(activityType), "activity_type", activityType);
		wrapperActivity.eq(StringUtils.isNotBlank(subclass), "subclass", subclass);
		wrapperActivity.eq("del_flag", 0);
		List<HhrActivity> listActivity = activityMapper.selectList(wrapperActivity);
		
		Wrapper<HhrActivityRecord> wrapperRecord = new EntityWrapper<HhrActivityRecord>();
		List<HhrActivityRecord> listRecord = activityRecordMapper.selectList(wrapperRecord);
		
		Wrapper<SysUser> wrapperUser = new EntityWrapper<SysUser>();
		wrapperUser.like(StringUtils.isNotBlank(name), "name", name, SqlLike.DEFAULT);
		wrapperUser.eq(StringUtils.isNotBlank(account), "account", account);
		List<SysUser> userList = sysUserMapper.selectList(wrapperUser);
		
		Wrapper<School> wrapperSchool = new EntityWrapper<School>();
		List<School> schoolList = schoolMapper.selectList(wrapperSchool);
		
		Map<String, Object> refMap = MapUtil.listToMap(schoolMapper.getSchoolRef(), "user_id", "school_id");
		
		for(SysUser sysUser : userList) {
			String userId = sysUser.getId();
			if(null != refMap.get(userId)) {
				for(School school : schoolList) {
					if(refMap.get(userId).toString().equals(school.getId())) {
						sysUser.setSubstName(school.getSubName());
						sysUser.setSchoolName(school.getSubName());
					}
				}
			}
		}
		
		
		Page<Map<String, Object>> page = new Page<>(pageIndex, pageSize);
		List<Map<String, Object>> newList = new ArrayList<Map<String,Object>>();
		for(HhrActivityRecord activityRecord : listRecord) {
			String activityId = activityRecord.getActivityId();
			Map<String, Object> map = new HashMap<String, Object>();
			int num = 0;
			
			for(HhrActivity activity : listActivity) {
				if(activityId.equals(activity.getId())) {
					
					map.put("title", activity.getTitle());
					map.put("desc", activity.getDesc());
					map.put("integral", activity.getIntegral());
					map.put("activityType", activity.getActivityType());
					map.put("subclass", activity.getSubclass());
					map.put("id", activityRecord.getId());
					map.put("status", activityRecord.getStatus());
					map.put("remark", activityRecord.getRemark());
					map.put("recordIntegral", activityRecord.getRecordIntegral());
					map.put("creator", activityRecord.getCreator());
					map.put("message", activityRecord.getMessage());
					map.put("createTime", activityRecord.getCreateTime());
					num++;
					break;
				}
			}
			
			for(SysUser sysUser : userList) {
				if(sysUser.getId().equals(activityRecord.getCreateId())) {
					map.put("account", sysUser.getAccount());
					map.put("name", sysUser.getName());
					map.put("substName", sysUser.getSubstName());
					map.put("schoolName", sysUser.getSchoolName());
					num++;
					break;
				}
			}
			
			if(num == 2) {

				newList.add(map);
			}
		}
		
		List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
		if(newList.size() < pageSize) {
			dataList = newList;
		}else {
			dataList = newList.subList((pageIndex-1)*pageSize, pageIndex*pageSize);
		}
		
		page.setRecords(dataList);
		page.setTotal(newList.size());
		return ResponseData.success(page, "查询完毕！");
	}
	
	@Permission(menuname = "导出活动积分记录", value = "exportIntegralRecord", method = RequestMethod.POST)
    public void exportIntegralRecord(@RequestParam("title") String title,
			@RequestParam("activityType") String activityType, @RequestParam("subclass") String subclass,
			@RequestParam(name = "status", required = false) String status,
			@RequestParam(name = "creator", required = false) String creator,
			@RequestParam(name = "createTimeStart", required = false) String createTimeStart,
			@RequestParam(name = "createTimeEnd", required = false) String createTimeEnd
    		) throws IOException {


        Wrapper<HhrActivity> wrapperActivity = new EntityWrapper<HhrActivity>();
		wrapperActivity.like(StringUtils.isNotBlank(title), "title", title, SqlLike.DEFAULT);
		wrapperActivity.eq(StringUtils.isNotBlank(activityType), "activity_type", activityType);
		wrapperActivity.eq(StringUtils.isNotBlank(subclass), "subclass", subclass);
		wrapperActivity.eq("del_flag", 0);
		List<HhrActivity> listActivity = activityMapper.selectList(wrapperActivity);
		
		Wrapper<HhrActivityRecord> wrapperRecord = new EntityWrapper<HhrActivityRecord>();
		wrapperRecord.like(StringUtils.isNotBlank(creator), "creator", creator, SqlLike.DEFAULT);
		wrapperRecord.eq(StringUtils.isNotBlank(status), "status", status);
		List<HhrActivityRecord> listRecord = activityRecordMapper.selectList(wrapperRecord);
		
		Wrapper<SysUser> wrapperUser = new EntityWrapper<SysUser>();
		wrapperUser.like(StringUtils.isNotBlank(creator), "creator", creator, SqlLike.DEFAULT);
		wrapperUser.eq(StringUtils.isNotBlank(status), "status", status);
		List<SysUser> userList = sysUserMapper.selectList(wrapperUser);
		
		Wrapper<School> wrapperSchool = new EntityWrapper<School>();
		wrapperSchool.like(StringUtils.isNotBlank(creator), "creator", creator, SqlLike.DEFAULT);
		wrapperSchool.eq(StringUtils.isNotBlank(status), "status", status);
		List<School> schoolList = schoolMapper.selectList(wrapperSchool);
		
		Map<String, Object> refMap = MapUtil.listToMap(schoolMapper.getSchoolRef(), "user_id", "school_id");
		
		for(SysUser sysUser : userList) {
			String userId = sysUser.getId();
			if(null != refMap.get(userId)) {
				for(School school : schoolList) {
					if(refMap.get(userId).toString().equals(school.getId())) {
						sysUser.setSubstName(school.getSubName());
						sysUser.setSchoolName(school.getSubName());
					}
				}
			}
		}
		
		List<Map<String, Object>> newList = new ArrayList<Map<String,Object>>();
		for(HhrActivityRecord activityRecord : listRecord) {
			String activityId = activityRecord.getActivityId();
			Map<String, Object> map = new HashMap<String, Object>();
			int num = 0;
			
			for(HhrActivity activity : listActivity) {
				if(activityId.equals(activity.getId())) {
					
					map.put("title", activity.getTitle());
					map.put("desc", activity.getDesc());
					map.put("integral", activity.getIntegral());
					map.put("activityType", activity.getActivityType());
					map.put("subclass", activity.getSubclass());
					map.put("id", activityRecord.getId());
					map.put("status", activityRecord.getStatus());
					map.put("remark", activityRecord.getRemark());
					map.put("recordIntegral", activityRecord.getRecordIntegral());
					map.put("creator", activityRecord.getCreator());
					map.put("message", activityRecord.getMessage());
					map.put("createTime", activityRecord.getCreateTime());
					num++;
				}
			}
			
			for(SysUser sysUser : userList) {
				if(sysUser.getId().equals(activityRecord.getCreateId())) {
					map.put("account", sysUser.getAccount());
					map.put("name", sysUser.getName());
					map.put("substName", sysUser.getSubstName());
					map.put("schoolName", sysUser.getSchoolName());
					num++;
				}
			}
			
			if(num == 2) {
				newList.add(map);
			}
		}
		
        List<String> tops = new ArrayList<>();
        tops.add("姓名");
        tops.add("账号");
        tops.add("所得积分");
        tops.add("积分类型");
        tops.add("积分小类");
        tops.add("县分");
        tops.add("学校");
        tops.add("创建时间");
        List<String> columns = new ArrayList<>();
        columns.add("name");
        columns.add("account");
        columns.add("recordIntegral");
        columns.add("activityType");
        columns.add("subclass");
        columns.add("substName");
        columns.add("schoolName");
        ServletOutputStream os = null;
        XSSFWorkbook workbook = new XSSFWorkbook();
        try {
            //创建工作表
            XSSFSheet sheet = workbook.createSheet("积分记录清单");
            //添加表头
            final XSSFRow row = sheet.createRow(0);
            //设置列宽度
            sheet.setColumnWidth(1, 6500);
            sheet.setColumnWidth(2, 6500);
            sheet.setColumnWidth(3, 6500);
            sheet.setColumnWidth(4, 6500);
            sheet.setColumnWidth(5, 7000);
            sheet.setColumnWidth(6, 4000);
            sheet.setColumnWidth(7, 4000);
            //第一行字段名称
            tops.forEach(column -> {
                XSSFCell cell = row.createCell(Math.max(row.getLastCellNum(), 0));
                cell.setCellValue(column);
            });
            //数据
            int rowIndex = row.getRowNum();
            for (Map<String, Object> maps: newList) {
                final XSSFRow rowdata = sheet.createRow(++rowIndex);
                for (String column : columns) {
                    XSSFCell cell = rowdata.createCell(Math.max(rowdata.getLastCellNum(), 0));
                    if (maps.get(column) != null) {
                        cell.setCellValue(maps.get(column).toString());
                    }
                }
            }

            HttpServletResponse response = getHttpServletResponse();
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            os = response.getOutputStream();
            workbook.write(os);
            os.flush();
        } catch (Exception e) {
            log.error("文件出错！" + e.getMessage(), e);
        } finally {
            IOUtils.closeQuite(workbook, os);
        }
        
    }
	
	 @Permission(menuname = "导出宽带订单", value = "download", method = RequestMethod.POST)
    public void downloadOrderView(@RequestParam("startTime") String startTime, @RequestParam("endTime") String endTime,
                                                       @RequestParam("orderseq") String orderseq, @RequestParam("orderUniversityName") String orderUniversityName,
                                                       @RequestParam("status") String status, @RequestParam("ordername") String ordername) {
        String dateFormat = "YYYY-MM-DD";
        if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            startTime = startTime.substring(0, dateFormat.length()) + " 00:00:00";
            endTime = endTime.substring(0, dateFormat.length()) + " 23:59:59";
        } else {
            startTime = null;
            endTime = null;
        }
        String state=null;
        if(StringUtils.isNotBlank(status)){
            state = OrderStatus.findById(status).getId();
        }
        Wrapper<OrderView> wrapper = new EntityWrapper();
        wrapper.like(StringUtils.isNotBlank(orderseq), "orderSeq", orderseq, SqlLike.DEFAULT);
        wrapper.like(StringUtils.isNotBlank(ordername), "orderName", ordername, SqlLike.DEFAULT);
        wrapper.like(StringUtils.isNotBlank(orderUniversityName), "order_university_name", orderUniversityName, SqlLike.DEFAULT);
        wrapper.eq(StringUtils.isNotBlank(status), "status",state);
        wrapper.ge(StringUtils.isNotBlank(startTime),"orderDate",startTime);
        wrapper.le(StringUtils.isNotBlank(endTime),"orderDate",endTime);
        List<Map<String, Object>> OrderViews = orderViewMapper.downloadOrderView(wrapper);
       List<String> tops = new ArrayList<>();
        tops.add("订单id");
        tops.add("订单编号");
        tops.add("产品名称");
        tops.add("产品价格");
        tops.add("套餐");
        tops.add("学校");
        tops.add("区域");
        tops.add("客户姓名");
        tops.add("联系电话");
        tops.add("订单状态");
        tops.add("备注");
        tops.add("创建时间");
        tops.add("支付平台");
        tops.add("支付方式");
        tops.add("支付时间");
        tops.add("穗易付订单号");
        tops.add("接入商");
        tops.add("支付平台流水号");
        tops.add("智能平台订单号");
        List<String> columns = new ArrayList<>();
        columns.add("order_id");
        columns.add("orderSeq");
        columns.add("productName");
        columns.add("webOrderAmount");
        columns.add("order_set_meal");
        columns.add("order_university_name");
        columns.add("order_region");
        columns.add("orderName");
        columns.add("orderPhone");
        columns.add("status");
        columns.add("order_customer_remarks");
        columns.add("orderDate");
        columns.add("ipay");
        columns.add("payType");
        columns.add("order_payment_time");
        columns.add("orderReqtranSeq");
        columns.add("customeRid");
        columns.add("uptranseq");
        columns.add("orderSeqTHD");
        ServletOutputStream os = null;
        XSSFWorkbook workbook = new XSSFWorkbook();
        try {
            //创建工作表
            XSSFSheet sheet = workbook.createSheet("宽带订单清单");
            //添加表头
            final XSSFRow row = sheet.createRow(0);
            //设置列宽度
            sheet.setColumnWidth(1, 6500);
            sheet.setColumnWidth(2, 6500);
            sheet.setColumnWidth(5, 7000);
            sheet.setColumnWidth(8, 4000);
            sheet.setColumnWidth(10, 6500);
            sheet.setColumnWidth(11, 6500);
            sheet.setColumnWidth(14, 6500);
            sheet.setColumnWidth(15, 7000);
            sheet.setColumnWidth(17, 7500);
            sheet.setColumnWidth(18, 600);
            //第一行字段名称
            tops.forEach(column -> {
                XSSFCell cell = row.createCell(Math.max(row.getLastCellNum(), 0));
                cell.setCellValue(column);
            });
            //数据
            int rowIndex = row.getRowNum();
            for (Map<String, Object> maps: OrderViews) {
                final XSSFRow rowdata = sheet.createRow(++rowIndex);
                for (String column : columns) {
                    XSSFCell cell = rowdata.createCell(Math.max(rowdata.getLastCellNum(), 0));
                    if (maps.get(column) != null) {
                        cell.setCellValue(maps.get(column).toString());
                    }
                }
            }

            HttpServletResponse response = getHttpServletResponse();
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            os = response.getOutputStream();
            workbook.write(os);
            os.flush();
        } catch (Exception e) {
            log.error("文件出错！" + e.getMessage(), e);
        } finally {
            IOUtils.closeQuite(workbook, os);
        }
    }
	 
	 /**
     * 保存活动参与记录（微信端）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "addActivityRecord", method = RequestMethod.POST)
    public ResponseData<String> getActivityInfo(String id,String message,String imageUrl) {
    	ShiroUser user = getShiroUser();
    	
		HhrActivityRecord activityRecord = new HhrActivityRecord();
		activityRecord.setActivityId(id);
		activityRecord.setMessage(message);
		activityRecord.setImageUrl(imageUrl);
		activityRecord.setCreateId(Integer.toString(user.getId()));
		activityRecord.setCreator(user.getName());
		activityRecord.setCreateTime(new Date());
		
		int num = activityRecordMapper.insert(activityRecord);
		if(num > 0) {
			return ResponseData.success("提交成功！");
		}

		return ResponseData.error("提交失败！");
    }
	
}
