package com.house365.web.controller;

import com.house365.beans.entity.CmUserEntity;
import com.house365.beans.entity.ExportLogEntity;
import com.house365.beans.system.Page;
import com.house365.rest.context.CmConstant;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.ExcelUtil;
import com.house365.ws.beans.request.CmUserListRequest;
import com.house365.ws.beans.response.CmUserListResponse;
import com.house365.ws.interfaces.server.ICmUser;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springside.modules.web.Servlets;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 邀请记录报表Controller
 *
 * @author Created by Administrator on 2019/12/10.
 */
@Controller
@RequestMapping("/invitereport")
public class InviteReportController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(InviteReportController.class);

    @Autowired
    private ICmUser cmUser;

    /**
     * 邀请记录报表list
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Integer number, Model model, HttpServletRequest request) {
        try {
            // 获取查询条件
            Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
            String startTime = request.getParameter("startTime");
            String endTime = request.getParameter("endTime");
            String phone = request.getParameter("phone");
            model.addAttribute("startTime", startTime);
            model.addAttribute("endTime", endTime);
            if (StringUtils.isNotBlank(phone)) {
                String phones = "[" + phone + "]";
                model.addAttribute("phone", phones);
                model.addAttribute("hasPhone", 1);
            } else {
                model.addAttribute("hasPhone", 0);
                model.addAttribute("phone", "100");
            }
            Page page = new Page(20);
            if (null != number) {
                page.setCurrentPage(number);
            }
            CmUserListRequest listRequest = new CmUserListRequest();
            listRequest.setPaging(page);
            listRequest.setSearchParams(searchParams);
            CmUserListResponse response = cmUser.list(listRequest, startTime, endTime, phone);
            model.addAttribute("page", response.getPaging());
            model.addAttribute("dataList", response.getObjectList());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询邀请记录报表失败", e);
        }
        return getAutoUrl();
    }

    /**
     * 邀请记录报表list
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "/stepList/{inviteCode}", method = RequestMethod.GET)
    public String stepList(Integer number, Model model, HttpServletRequest request, @PathVariable int inviteCode) {
        try {
            // 获取查询条件
            Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
            String startTime = request.getParameter("startTime");
            String endTime = request.getParameter("endTime");
            model.addAttribute("startTime", startTime);
            model.addAttribute("endTime", endTime);
            Page page = new Page(20);
            if (null != number) {
                page.setCurrentPage(number);
            }
            CmUserListRequest listRequest = new CmUserListRequest();
            listRequest.setPaging(page);
            listRequest.setSearchParams(searchParams);
            CmUserListResponse response = cmUser.stepList(listRequest, inviteCode,startTime,endTime);
            String city = searchParams.get("EQ_cityKey").toString();
            model.addAttribute("city", city);
            model.addAttribute("inviteCode", inviteCode);
            model.addAttribute("page", response.getPaging());
            model.addAttribute("dataList", response.getObjectList());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询邀请记录二级菜单失败", e);
        }
        return getAutoUrl();
    }

    @RequestMapping(value = "/exportList", method = RequestMethod.GET)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        try {
            final String[] excelTitles = {"编号", "邀请人手机号", "邀请码", "邀请人数"};
            // 获取查询条件
            Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
            String userName = String.valueOf(request.getSession().getAttribute(CmConstant.USER_NAME));
            String startTime = request.getParameter("startTime");
            String endTime = request.getParameter("endTime");
            String phone = request.getParameter("phone");
            String city = searchParams.get("EQ_cityKey").toString();
            Map<String, Object> map = new HashMap<>(10);
            map.put("city", city);
            map.put("startTime", startTime);
            map.put("endTime", endTime);
            map.put("phone", phone);
            map.put("order", 1);

            List<Map<String, Object>> list = cmUser.queryList(map);
            List<List<Object>> cmList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(list)) {
                for (Map<String, Object> m : list) {
                    List<Object> cmUser = new ArrayList<>();
                    cmUser.add(m.get("id"));
                    cmUser.add(m.get("phoneNumber"));
                    cmUser.add(m.get("inviteCode"));
                    cmUser.add(m.get("inviteCount"));
                    cmList.add(cmUser);
                }
            }
            ExcelUtil.exportExcel("邀请记录一级菜单.xlsx", "邀请记录一级菜单", excelTitles, cmList, response);
            ExportLogEntity logEntity = new ExportLogEntity();
            logEntity.setType(0);
            logEntity.setPhone(phone);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (StringUtils.isNotBlank(startTime)) {
                Date startDate = formatter.parse(startTime);
                logEntity.setStartTime(startDate);
            } else {
                logEntity.setStartTime(formatter.parse("1900-01-01 00:00:00"));
            }
            if (StringUtils.isNotBlank(endTime)) {
                Date endDate = formatter.parse(endTime);
                logEntity.setEndTime(endDate);
            } else {
                logEntity.setEndTime(formatter.parse("1900-01-01 00:00:00"));
            }
            logEntity.setCreateName(userName);
            logEntity.setCreateTime(new Date());
            cmUser.save(logEntity);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("导出一级邀请记录报表失败", e);
        }
    }

    @RequestMapping(value = "/exportStepList", method = RequestMethod.GET)
    public void exportStepList(HttpServletRequest request, HttpServletResponse response) {
        try {
            final String[] excelTitles = {"编号", "手机号", "邀请时间"};
            String userName = String.valueOf(request.getSession().getAttribute(CmConstant.USER_NAME));
            // 获取查询条件
            String startTime = request.getParameter("startTime");
            String endTime = request.getParameter("endTime");
            String inviteCode = request.getParameter("inviteCode");
            String city = request.getParameter("city");
            Map<String, Object> map = new HashMap<>(10);
            map.put("city", city);
            map.put("inviteCode", inviteCode);
            map.put("startTime", startTime);
            map.put("endTime", endTime);
            List<CmUserEntity> list = cmUser.exportStepList(map);
            List<List<Object>> cmList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(list)) {
                for (CmUserEntity c : list) {
                    List<Object> cmUser = new ArrayList<>();
                    cmUser.add(c.getId());
                    cmUser.add(c.getPhoneNumber());
                    cmUser.add(c.getCreateTime());
                    cmList.add(cmUser);
                }
            }
            ExcelUtil.exportExcel("邀请记录二级菜单.xlsx", "邀请记录二级菜单", excelTitles, cmList, response);
            ExportLogEntity logEntity = new ExportLogEntity();
            logEntity.setType(1);
            logEntity.setPhone(inviteCode);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            logEntity.setStartTime(formatter.parse("1900-01-01 00:00:00"));
            logEntity.setEndTime(formatter.parse("1900-01-01 00:00:00"));
            logEntity.setCreateName(userName);
            logEntity.setCreateTime(new Date());
            cmUser.save(logEntity);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("导出二级邀请记录报表失败", e);
        }
    }

}
