package com.ylcm.sys.controller;


import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ylcm.sys.common.Constants;
import com.ylcm.sys.common.ExcelUtil;
import com.ylcm.sys.domain.AdMedia;
import com.ylcm.sys.domain.AdPlatform;
import com.ylcm.sys.domain.AdProduct;
import com.ylcm.sys.domain.AdSpecial;
import com.ylcm.sys.domain.AdTv;
import com.ylcm.sys.enums.AdSpecialTypeEnum;
import com.ylcm.sys.excel.listener.BaseExcelListener;
import com.ylcm.sys.excel.model.AdSpecialPlatformExportDTO;
import com.ylcm.sys.excel.model.AdSpecialPlatformImportDTO;
import com.ylcm.sys.excel.model.AdSpecialProductExportDTO;
import com.ylcm.sys.excel.model.AdSpecialProductImportDTO;
import com.ylcm.sys.form.AdSpecialForm;
import com.ylcm.sys.form.AdSpecialQueryForm;
import com.ylcm.sys.service.AdMediaService;
import com.ylcm.sys.service.AdPlatformService;
import com.ylcm.sys.service.AdProductService;
import com.ylcm.sys.service.AdSpecialService;
import com.ylcm.sys.service.AdTvService;
import com.ylcm.sys.vo.AdSpecialVO;

import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 专题管理 前端控制器
 * </p>
 *
 * @author admin
 * @since 2020-07-01
 */
@Controller
@Slf4j
@RequestMapping("/ad-special")
public class AdSpecialController extends BaseController{
	
	@Resource
	private AdSpecialService adSpecialService;
	@Resource
	private AdProductService adProductService;
	@Resource
    private AdMediaService adMediaService;
	@Resource
    private AdTvService adTvService;
	@Resource
	private AdPlatformService adPlatformService;
	
	@RequestMapping(value = "/index.do")
    public String index(ModelMap model, Integer type) {
        // 菜单选中，和权限对应
        model.put("parentMenu", "ad_placement");   
        if(AdSpecialTypeEnum.PLATFORM.getCode().equals(type)) {
        	model.put("menu", "special_platform_mng");
        	model.put("type", type);
        }else {
        	model.put("menu", "special_product_mng");
        	model.put("type", type == null ? AdSpecialTypeEnum.PRODUCT.getCode() : type);
        } 
        return "adspecial/index";
    }
	
	@RequestMapping(value = "/ajax_list.do")
    public void ajaxList(AdSpecialQueryForm adSpecialQueryForm, 
    		HttpServletRequest request, HttpServletResponse response) {
		JSONObject result = new JSONObject();
        result.put("code", Constants.CODE_SUCCESS);
        result.put("msg", "操作成功");
        
        IPage<AdSpecial> page = adSpecialService.queryPage(adSpecialQueryForm);
        IPage<AdSpecialVO> vos = new Page<AdSpecialVO>();
        BeanUtils.copyProperties(page, vos);
        List<AdSpecialVO> voList = new ArrayList<>((int) page.getSize());
        if (!CollectionUtils.isEmpty(page.getRecords())) {
            for (AdSpecial adSpecial:page.getRecords()) {
                AdSpecialVO adSpecialVO= AdSpecialVO.from(adSpecial);
                voList.add(adSpecialVO);
            }
            vos.setRecords(voList);
        }

        result.put("list", vos);
        returnResult(request, response, result);
    }
	
	@RequestMapping(value = "/export.do")
    public void export(AdSpecialQueryForm adSpecialQueryForm,
    		HttpServletRequest request, HttpServletResponse response) {
		
		ExcelUtil.exportExcelToWebsite(response, AdSpecialTypeEnum.PRODUCT.getCode().equals(adSpecialQueryForm.getType()) ? "专题产品列表" : "专题栏目列表",
				AdSpecialTypeEnum.PRODUCT.getCode().equals(adSpecialQueryForm.getType()) ? new AdSpecialProductExportDTO() : new AdSpecialPlatformExportDTO(),
				(currentPage, pageSize) -> {
			adSpecialQueryForm.setPageNo(currentPage);
			adSpecialQueryForm.setPageSize(pageSize);
			if(AdSpecialTypeEnum.PRODUCT.getCode().equals(adSpecialQueryForm.getType())) {
				return toProductExport(adSpecialService.queryPage(adSpecialQueryForm).getRecords());
			}else {
				return toPlatformExport(adSpecialService.queryPage(adSpecialQueryForm).getRecords());
			}
		});
    }
	
	private List<AdSpecialProductExportDTO> toProductExport(List<AdSpecial> adSpecials) {
		if (CollectionUtils.isEmpty(adSpecials)) {
			return new ArrayList<AdSpecialProductExportDTO>();
		}
		List<AdSpecialProductExportDTO> exportDTOs = new ArrayList<AdSpecialProductExportDTO>();
		for (AdSpecial adSpecial : adSpecials) {
			exportDTOs.add(AdSpecialProductExportDTO.from(adSpecial));
		}
		return exportDTOs;
	}
	
	private List<AdSpecialPlatformExportDTO> toPlatformExport(List<AdSpecial> adSpecials) {
		if (CollectionUtils.isEmpty(adSpecials)) {
			return new ArrayList<AdSpecialPlatformExportDTO>();
		}
		List<AdSpecialPlatformExportDTO> exportDTOs = new ArrayList<AdSpecialPlatformExportDTO>();
		for (AdSpecial adSpecial : adSpecials) {
			exportDTOs.add(AdSpecialPlatformExportDTO.from(adSpecial));
		}
		return exportDTOs;
	}
	
	@RequestMapping(value = "/detail.do")
	public String detail(Integer id, Integer type , ModelMap model) {
		AdSpecial adSpecial = new AdSpecial();
		if(id != null) {
        	adSpecial = adSpecialService.getById(id);
        }else {
        	adSpecial.setType(type);
        }
        model.put("map", adSpecial);
        return "adspecial/detail";
	}
	
	@RequestMapping(value = "/del.do")
    public void del(Integer id, 
    		HttpServletRequest request, HttpServletResponse response) {
		JSONObject result = new JSONObject();
        result.put("code", Constants.CODE_SUCCESS);
        result.put("msg", "操作成功");
        adSpecialService.delete(id);

        returnResult(request, response, result);
    }
	
	@RequestMapping(value = "/batch_del.do")
    public void batchDel(String ids, 
    		HttpServletRequest request, HttpServletResponse response) {
		JSONObject result = new JSONObject();
        result.put("code", Constants.CODE_SUCCESS);
        result.put("msg", "操作成功");
        String[] idArray = ids.split(",");
        for (String id : idArray) {
        	adSpecialService.delete(Integer.parseInt(id));
		}
        
        returnResult(request, response, result);
    }
	
	@RequestMapping(value = "/save.do")
    public void save(AdSpecialForm form, HttpServletRequest request, HttpServletResponse response) {
		JSONObject result = new JSONObject();
        result.put("code", Constants.CODE_SUCCESS);
        result.put("msg", "操作成功");
        try {
        	String error = adSpecialService.saveOrUpd(form);
        	if (error != null) {
        		result.put("code", Constants.CODE_FAIL);
        		result.put("msg", error);
        	}
        }catch (Exception e) {
        	log.error("ad-special/save.do error error:" + e.getMessage(), e);
	    	result.put("code", Constants.CODE_FAIL);
	        result.put("msg", "服务器错误");
		}
        returnResult(request, response, result);
    }
	
	@RequestMapping(value = "import_excel.do")
    public String importExcel(HttpServletRequest request, HttpServletResponse response,Integer type, MultipartFile excelfile) throws Exception {
        Integer code = Constants.CODE_FAIL;// 执行结果
        String msg = "服务器异常";// 返回信息
        String returnStr = "common/import_callback";//返回视图
        try {
       		String fileType = excelfile.getContentType();
    		if (fileType == null) {
    			request.setAttribute("code", Constants.CODE_FAIL);
    			request.setAttribute("msg", "excel文件错误，请确认文件是否损坏！");
    			return "common/import_callback";
    		}
    		String fileName = excelfile.getOriginalFilename();
    		// 判断是否是excel文件
    		if (!fileName.endsWith("xls") && !fileName.endsWith("xlsx")) {
    			request.setAttribute("code", Constants.CODE_FAIL);
    			request.setAttribute("msg", "请上传正确的Excel文件");
    			return "common/import_callback";
    		}
        	//产品导入
            if(AdSpecialTypeEnum.PRODUCT.getCode().equals(type)) {
            	BaseExcelListener<AdSpecialProductImportDTO> listener = new BaseExcelListener<>();
            	EasyExcel.read(excelfile.getInputStream(), AdSpecialProductImportDTO.class,listener).sheet(1).doRead();
            	List<AdSpecialProductImportDTO> dtos = listener.getDataList();
                if(CollectionUtils.isEmpty(dtos)) {
                  	request.setAttribute("code", Constants.CODE_FAIL);
                    request.setAttribute("msg", "表格数据为空！");
                    return "common/import_callback";
                }
            	dtos.stream().forEach(x -> x.check());
            	int index = 2; //表格从第二行开始
            	for(AdSpecialProductImportDTO dto: dtos) {
            		index ++;
            		if (StringUtils.isNotBlank(dto.getMsg())){
            			request.setAttribute("code", Constants.CODE_FAIL);
            			request.setAttribute("msg", "第"+ index + "行" + dto.getMsg());
            			return "common/import_callback";
            		}
            		AdProduct adProduct = adProductService.getByName(dto.getProductName(), dto.getBrandName());
            		if(adProduct == null) {
            			request.setAttribute("code", Constants.CODE_FAIL);
            			request.setAttribute("msg", "第"+ index + "行" + "产品名称不存在或者产品品牌不正确，请核实！");
            			return "common/import_callback";
            		}
            		AdMedia adMedia = adMediaService.getByName(dto.getMediaName()); 
            		if(adMedia == null) {
            			request.setAttribute("code", Constants.CODE_FAIL);
            			request.setAttribute("msg", "第"+ index + "行" + "媒体名称不存在，请核实！");
            			return "common/import_callback";
            		}
            		if(dto.getShowEnv().contains("电视剧")) {
            			AdTv adTv = adTvService.getByName(dto.getTvName()); 
            			if(adTv == null) {
            				request.setAttribute("code", Constants.CODE_FAIL);
            				request.setAttribute("msg", "第"+ index + "行" + "播出节目不存在，请核实！");
            				return "common/import_callback";
            			}
            		}
            		// 产品导入时，自动填充品牌
            		dto.setBrandName(adProduct != null && StringUtils.isNotBlank(adProduct.getBrandName()) ? adProduct.getBrandName() : "" );
            		dto.setType(type);
            	}
            	msg = adSpecialService.importProductBatch(dtos);
            }else if(AdSpecialTypeEnum.PLATFORM.getCode().equals(type)) { 
            	// 栏目导入
            	BaseExcelListener<AdSpecialPlatformImportDTO> listener = new BaseExcelListener<>();
            	EasyExcel.read(excelfile.getInputStream(), AdSpecialPlatformImportDTO.class,listener).sheet(1).doRead();
            	List<AdSpecialPlatformImportDTO> dtos = listener.getDataList();
                if(CollectionUtils.isEmpty(dtos)) {
                  	request.setAttribute("code", Constants.CODE_FAIL);
                    request.setAttribute("msg", "表格数据为空！");
                    return "common/import_callback";
                }
            	dtos.stream().forEach(x -> x.check());
            	int index = 2; //表格从第二行开始
            	for(AdSpecialPlatformImportDTO dto: dtos) {
            		index ++;
            		if (StringUtils.isNotBlank(dto.getMsg())){
            			request.setAttribute("code", Constants.CODE_FAIL);
            			request.setAttribute("msg", "第"+ index + "行" + dto.getMsg());
            			return "common/import_callback";
            		}
            		AdPlatform adPlatform = adPlatformService.getByName(dto.getProductName(),dto.getBrandName());
            		if(adPlatform == null) {
            			request.setAttribute("code", Constants.CODE_FAIL);
            			request.setAttribute("msg", "第"+ index + "行" + "栏目名称不存在或者栏目内容不正确，请核实！");
            			return "common/import_callback";
            		}
            		AdMedia adMedia = adMediaService.getByName(dto.getMediaName()); 
            		if(adMedia == null) {
            			request.setAttribute("code", Constants.CODE_FAIL);
            			request.setAttribute("msg", "第"+ index + "行" + "媒体名称不存在，请核实！");
            			return "common/import_callback";
            		}
            		if(dto.getShowEnv().contains("电视剧")) {
	            		AdTv adTv = adTvService.getByName(dto.getTvName()); 
	            		if(adTv == null) {
	            			request.setAttribute("code", Constants.CODE_FAIL);
	            			request.setAttribute("msg", "第"+ index + "行" + "播出节目不存在，请核实！");
	            			return "common/import_callback";
	            		}
            		}
            		// 栏目导入时，自动填充内容
            		dto.setBrandName(adPlatform != null && StringUtils.isNotBlank(adPlatform.getBrandName()) ? adPlatform.getBrandName() : "" );
            		dto.setType(type);
            	}
            	msg = adSpecialService.importPlatformBatch(dtos);
            }
            // 判断执行结果
            if("ok".equals(msg)) {
                request.setAttribute("code", Constants.CODE_SUCCESS);
                request.setAttribute("msg", msg);
                return "common/import_callback";
            }
        } catch (Exception e) {
            log.error("import_excel_for_special.do error:" + e.getMessage(), e);
            if(e.getMessage().contains("重复")) {
            	msg = e.getMessage();
            }
        }
        // 返回结果
        request.setAttribute("code", code);
        request.setAttribute("msg", msg);
        return returnStr;
    }

}
