package com.huiju.estateagents.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huiju.estateagents.base.BaseController;
import com.huiju.estateagents.base.ResponseBean;
import com.huiju.estateagents.entity.TaChannel;
import com.huiju.estateagents.excel.ActivityStatistics.*;
import com.huiju.estateagents.excel.handler.CustomCellWriteHandler;
import com.huiju.estateagents.mapper.TaChannelMapper;
import com.huiju.estateagents.service.ITaPersonService;
import com.huiju.estateagents.service.TaChannelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;


/**
 * <p>
    *   前端控制器
    * </p>
 *
 * @author jobob
 * @since 2019-09-17
 */
@RestController
@RequestMapping("/api")
@Api(value = "渠道管理", tags = "渠道管理")
public class TaChannelController extends BaseController {

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

    @Autowired
    public TaChannelService taChannelService;

    @Autowired
    public ITaPersonService taPersonService;

    @Autowired
    public TaChannelMapper taChannelMapper;


    /**
     * 渠道管理列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "渠道管理列表", notes = "渠道管理列表")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageNum", paramType = "query",value = "第几页"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageSize", paramType = "query",value = "一页多少行"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "channelId", paramType = "query",value = "渠道Id"),
    })
    @RequestMapping(value="/admin/channel",method= RequestMethod.GET)
    public ResponseBean channelList(@RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                    @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                    @RequestParam(value ="channelId",required = false) Integer channelId,
                                    HttpServletRequest request){
        ResponseBean responseBean = new ResponseBean();
        Integer orgId = getOrgId(request);
        try {
            //使用分页插件
		    IPage<TaChannel> pg = new Page<>(pageNum, pageSize);
            IPage<TaChannel> result = taChannelMapper.pageTaChannel(pg,orgId,channelId);
            List<TaChannel> recommendCount = taChannelMapper.recommendCount(orgId, channelId);

            result.getRecords().stream().forEach(e -> {
                for(TaChannel channel : recommendCount){
                    if (channel.getChannelId().equals(e.getChannelId())){
                        e.setRecommendCount(channel.getRecommendCount());
                    }
                }
            });

            HashMap hashMap  = new HashMap<>();
            hashMap.put("result",result);
            // 下拉列表的数据 all
            List<TaChannel> taChannelList = taChannelMapper.selectChannelList(orgId);
            hashMap.put("channelNmae",taChannelList);
            responseBean.addSuccess(hashMap);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("channelList -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 渠道保存
     * @param channel 实体对象
     * @return
     */
    @ApiOperation(value = "渠道保存", notes = "渠道保存")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = TaChannel.class, name = "channel", paramType = "body",value = "当前对象"),
    })
    @RequestMapping(value="/admin/channel",method= RequestMethod.POST)
    public ResponseBean channelAdd(@RequestBody TaChannel channel ,HttpServletRequest request){
        Integer orgId = getOrgId(request);
        ResponseBean responseBean = new ResponseBean();
        try {
            // 生成6位数的渠道码
            int channelCode= taChannelMapper.channelCode();
            channel.setChannelCode(String.valueOf(channelCode));
            channel.setOrgId(orgId);
            if (taChannelService.save(channel)){
                responseBean.addSuccess(channel);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("channelAdd -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     */
    @ApiOperation(value = "根据渠道ID删除", notes = "根据渠道ID删除")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "id", paramType = "query",value = "渠道id"),
    })
    @ResponseBody
    @RequestMapping(value="/channel/{id}", method= RequestMethod.DELETE)
    public ResponseBean channelDelete(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            if(taChannelService.removeById(id)){
                responseBean.addSuccess("success");
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("channelDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 修改对象
     * @param id  实体ID
     * @param channel 实体对象
     * @return
     */
    @ApiOperation(value = "根据渠道ID修改", notes = "根据渠道ID修改")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "id", paramType = "query",value = "渠道id"),
    })
    @RequestMapping(value="/admin/channel/{id}",method= RequestMethod.PUT)
    public ResponseBean channelUpdate(@PathVariable Integer id,
                                        @RequestBody TaChannel channel){
        ResponseBean responseBean = new ResponseBean();
        try {
            channel.setChannelId(id);
            if (taChannelService.updateById(channel)){
                responseBean.addSuccess(channel);
            }else {
                responseBean.addError("fail");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("channelUpdate -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 根据id查询对象
     * @param id  实体ID
     */
    @ApiOperation(value = "根据渠道ID查询", notes = "根据渠道ID查询")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "id", paramType = "query",value = "渠道id"),
    })
    @RequestMapping(value="/admin/channel/{id}",method= RequestMethod.GET)
    public ResponseBean channelGet(@PathVariable Integer id){
        ResponseBean responseBean = new ResponseBean();
        try {
            responseBean.addSuccess(taChannelService.getById(id));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("channelDelete -=- {}",e.toString());
            responseBean.addError(e.getMessage());
        }
        return responseBean;
    }

    /**
     * 渠道管理下的经纪人
     */
    @ApiOperation(value = "渠道管理下的经纪人", notes = "渠道管理下的经纪人")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = String.class, name = "name", paramType = "query",value = "姓名"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "phone", paramType = "query",value = "电话"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "channelId", paramType = "query",value = "渠道id"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageNum", paramType = "query",value = "多少页"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageSize", paramType = "query",value = "每页多少条"),
    })
    @RequestMapping(value="/admin/channel/broker",method= RequestMethod.GET)
    public  ResponseBean channelBrokerList(@RequestParam(value="name",required = false) String name,
                                           @RequestParam(value="phone",required = false) String phone,
                                           @RequestParam(value="channelId",required = false) Integer channelId,
                                           @RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                           @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                           HttpServletRequest request){
        Integer orgid = getOrgId(request);
        ResponseBean taPerson =  taPersonService.channelBrokerList(name,phone,pageNum,pageSize,orgid,channelId);
        return taPerson;
    }

    /**
     * 渠道邀请经纪人列表
     */
    @ApiOperation(value = "渠道邀请经纪人列表", notes = "渠道邀请经纪人列表")
    @ApiImplicitParams({
            @ApiImplicitParam(dataTypeClass = String.class, name = "id", paramType = "query",value = "姓名"),
            @ApiImplicitParam(dataTypeClass = String.class, name = "phone", paramType = "query",value = "电话"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "channelId", paramType = "query",value = "渠道id"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageNum", paramType = "query",value = "多少页"),
            @ApiImplicitParam(dataTypeClass = Integer.class, name = "pageSize", paramType = "query",value = "每页多少条"),
    })
    @RequestMapping(value="/admin/channel/InviteClientsList",method= RequestMethod.GET)
    public  ResponseBean InviteClientsList(@RequestParam(value="id",required = false) String id,
                                           @RequestParam(value="phone",required = false) String phone,
                                           @RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
                                           @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                           HttpServletRequest request){
        ResponseBean taPerson =  taPersonService.InviteClientsList(id,phone,pageNum,pageSize);
        return taPerson;
    }

    /**
     * 渠道引进客户统计
     * @return
     */
    @GetMapping(value = "/admin/channel/introductionList")
    public ResponseBean getChannelIntroductionList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                     @RequestParam(value = "pageSize", defaultValue = "10")Integer pageSize,
                                                     @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate startDate,
                                                     @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate endDate,
                                                     @RequestParam(value = "targetType", required = false)String targetType,
                                                     @RequestParam(value = "buildingId", required = false)String buildingId,
                                                     @RequestParam(value = "channelId") Integer channelId,
                                                     @RequestParam(value = "sortField", required = false) String sortField,
                                                     @RequestParam(value = "sortOrder", required = false) String sortOrder,
                                                     HttpServletRequest request) {
        return taChannelService.getChannelIntroductionList(pageNum, pageSize, getOrgId(request), startDate, endDate, targetType, buildingId, channelId,sortField,sortOrder, getTaPersonBuildingListByUserId(request));
    }

    /**
     * 渠道注册用户列表
     * @return
     */
    @GetMapping(value = "/admin/channel/introduction/newuserList")
    public ResponseBean getNewuserList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                       @RequestParam(value = "pageSize", defaultValue = "10")Integer pageSize,
                                       @RequestParam(value = "targetId", required = false) String targetId,
                                       @RequestParam(value = "targetType", required = false) String targetType,
                                       @RequestParam(value = "buildingId", required = false) String buildingId,
                                       @RequestParam(value = "channelId", required = false) Integer channelId,
                                       @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate startDate,
                                       @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate endDate,
                                       HttpServletRequest request) {
        return taChannelService.getNewuserList(pageNum, pageSize, getOrgId(request), channelId, targetId, targetType, buildingId,startDate,endDate);
    }

    /**
     * 渠道访问次数列表
     * @return
     */
    @GetMapping(value = "/admin/channel/introduction/visitNumList")
    public ResponseBean getVisitNumList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                       @RequestParam(value = "pageSize", defaultValue = "10")Integer pageSize,
                                       @RequestParam(value = "targetId", required = false) String targetId,
                                       @RequestParam(value = "targetType", required = false) String targetType,
                                       @RequestParam(value = "buildingId", required = false) String buildingId,
                                       @RequestParam(value = "channelId", required = false) Integer channelId,
                                       @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate startDate,
                                       @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate endDate,
                                       HttpServletRequest request) {
        return taChannelService.getVisitNumList(pageNum, pageSize, getOrgId(request), channelId, targetId, targetType, buildingId,startDate,endDate);
    }


    /**
     * 渠道访问人数列表
     * @return
     */
    @GetMapping(value = "/admin/channel/introduction/personNumList")
    public ResponseBean getPersonNumList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                        @RequestParam(value = "pageSize", defaultValue = "10")Integer pageSize,
                                        @RequestParam(value = "targetId", required = false) String targetId,
                                        @RequestParam(value = "targetType", required = false) String targetType,
                                        @RequestParam(value = "buildingId", required = false) String buildingId,
                                        @RequestParam(value = "channelId", required = false) Integer channelId,
                                         @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate startDate,
                                         @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate endDate,
                                        HttpServletRequest request) {
        return taChannelService.getPersonNumList(pageNum, pageSize, getOrgId(request), channelId, targetId, targetType, buildingId,startDate,endDate);
    }

    /**
     * 渠道引进客户统计导出
     * @return
     */
    @GetMapping(value = "/admin/channel/introductionListExport")
    public void getChannelIntroductionListExport(@RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate startDate,
                                                         @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate endDate,
                                                         @RequestParam(value = "targetType", required = false)String targetType,
                                                         @RequestParam(value = "buildingId", required = false)String buildingId,
                                                         @RequestParam(value = "channelId") Integer channelId,
                                                         HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=引进注册用户.xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), TsChannelDaily.class).registerWriteHandler(new CustomCellWriteHandler()).build();
        // 设置 sheet, 同一个sheet只需要设置一次
        WriteSheet writeSheet = EasyExcel.writerSheet("引进注册用户").build();
        List<TsChannelDaily> data = taChannelService.getChannelIntroductionListExport(getOrgId(request), startDate, endDate, targetType, buildingId, channelId, getTaPersonBuildingListByUserId(request));
        excelWriter.write(data, writeSheet);
        // finish 会帮忙关闭流
        excelWriter.finish();
    }

    /**
     * 渠道注册用户列表导出
     * @return
     */
    @GetMapping(value = "/admin/channel/introduction/newuserListExport")
    public void getNewuserListExport(@RequestParam(value = "targetId", required = false) String targetId,
                                       @RequestParam(value = "targetType", required = false) String targetType,
                                       @RequestParam(value = "buildingId", required = false) String buildingId,
                                       @RequestParam(value = "channelId", required = false) Integer channelId,
                                     @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate startDate,
                                     @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate endDate,
                                       HttpServletRequest request,HttpServletResponse response) throws IOException {
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=注册用户.xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), ChannelAddRegistNum.class).registerWriteHandler(new CustomCellWriteHandler()).build();
        // 设置 sheet, 同一个sheet只需要设置一次
        WriteSheet writeSheet = EasyExcel.writerSheet("注册用户").build();
        List<ChannelAddRegistNum> data =  taChannelService.getNewuserListExport(getOrgId(request), channelId, targetId, targetType, buildingId,startDate,endDate);
        excelWriter.write(data, writeSheet);
        // finish 会帮忙关闭流
        excelWriter.finish();
    }

    /**
     * 渠道访问次数列表导出
     * @return
     */
    @GetMapping(value = "/admin/channel/introduction/visitNumListExport")
    public void getVisitNumListExport(@RequestParam(value = "targetId", required = false) String targetId,
                                        @RequestParam(value = "targetType", required = false) String targetType,
                                        @RequestParam(value = "buildingId", required = false) String buildingId,
                                        @RequestParam(value = "channelId", required = false) Integer channelId,
                                      @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate startDate,
                                      @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate endDate,
                                        HttpServletRequest request,HttpServletResponse response) throws IOException {
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=访问次数.xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), ChannelVisitNum.class).registerWriteHandler(new CustomCellWriteHandler()).build();
        // 设置 sheet, 同一个sheet只需要设置一次
        WriteSheet writeSheet = EasyExcel.writerSheet("访问次数").build();
        List<ChannelVisitNum> data = taChannelService.getVisitNumListExport(getOrgId(request), channelId, targetId, targetType, buildingId,startDate,endDate);
        excelWriter.write(data, writeSheet);
        // finish 会帮忙关闭流
        excelWriter.finish();
    }


    /**
     * 渠道访问人数列表导出
     * @return
     */
    @GetMapping(value = "/admin/channel/introduction/personNumListExport")
    public void getPersonNumListExport(@RequestParam(value = "targetId", required = false) String targetId,
                                         @RequestParam(value = "targetType", required = false) String targetType,
                                         @RequestParam(value = "buildingId", required = false) String buildingId,
                                         @RequestParam(value = "channelId", required = false) Integer channelId,
                                       @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate startDate,
                                       @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDate endDate,
                                         HttpServletRequest request,HttpServletResponse response) throws IOException {
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=访问人数.xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), ChannelVisitPersonNum.class).registerWriteHandler(new CustomCellWriteHandler()).build();
        // 设置 sheet, 同一个sheet只需要设置一次
        WriteSheet writeSheet = EasyExcel.writerSheet("访问人数").build();
        List<ChannelVisitPersonNum> data = taChannelService.getPersonNumListExport(getOrgId(request), channelId, targetId, targetType, buildingId,startDate,endDate);
        excelWriter.write(data, writeSheet);
        // finish 会帮忙关闭流
        excelWriter.finish();
    }
}
