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.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.EnumHelperUtil;
import com.ylcm.sys.common.ExcelUtil;
import com.ylcm.sys.domain.AdMedia;
import com.ylcm.sys.enums.MediaRankEnum;
import com.ylcm.sys.excel.listener.BaseExcelListener;
import com.ylcm.sys.excel.model.AdMediaExportDTO;
import com.ylcm.sys.excel.model.AdMediaImportDTO;
import com.ylcm.sys.form.AdMediaForm;
import com.ylcm.sys.service.AdMediaService;
import com.ylcm.sys.vo.AdMediaVO;

import lombok.extern.slf4j.Slf4j;


/**
 * <p>
 * 媒体管理表 前端控制器
 * </p>
 *
 * @author admin
 * @since 2020-07-01
 */
@Controller
@Slf4j
@RequestMapping("/ad-media")
public class AdMediaController extends BaseController{
	
	@Resource
	private AdMediaService adMediaService;

    /**
     * to 品牌型号管理
     * */
	@RequestMapping(value = "/index.do")
    public String index(ModelMap model) {
        // 菜单选中，和权限对应
        model.put("menu", "media_mng");
        model.put("parentMenu", "ad_placement");
        
        return "admedia/index";
    }
	
	@RequestMapping(value = "/ajax_list.do")
    public void ajaxList(String name, Integer rank, Integer pageSize, Integer pageNo, 
    		HttpServletRequest request, HttpServletResponse response) {
		JSONObject result = new JSONObject();
        result.put("code", Constants.CODE_SUCCESS);
        result.put("msg", "服务器异常");
        
        IPage<AdMedia> page = getAdMedia(name, rank, pageSize, pageNo);
        IPage<AdMediaVO> vos = new Page<AdMediaVO>();
        BeanUtils.copyProperties(page, vos);
        List<AdMediaVO> voList = new ArrayList<>((int) page.getSize());
        if (!CollectionUtils.isEmpty(page.getRecords())) {
            for (AdMedia adMedia:page.getRecords()) {
                AdMediaVO adMediaVO = AdMediaVO.from(adMedia);
                voList.add(adMediaVO);
            }
            vos.setRecords(voList);
        }

        result.put("list", vos);
        returnResult(request, response, result);
    }
	
	private IPage<AdMedia> getAdMedia(String name, Integer rank, Integer pageSize, Integer pageNo) {
		LambdaQueryWrapper<AdMedia> queryWrapper = new LambdaQueryWrapper<AdMedia>();
        if (rank != null) {
			queryWrapper.eq(AdMedia::getRank, rank);
		}
        if (StringUtils.isNotBlank(name)) {
			queryWrapper.like(AdMedia::getName, name);
		}
        queryWrapper.orderByDesc(AdMedia::getId);
        
        IPage<AdMedia> page = adMediaService.page(new Page<AdMedia>(pageNo, pageSize), queryWrapper);
        return page;
	}
	
	@RequestMapping(value = "/export.do")
    public void export(String name, Integer rank, 
    		HttpServletRequest request, HttpServletResponse response) {
		ExcelUtil.exportExcelToWebsite(response,"媒体列表",new AdMediaExportDTO(),(currentPage, pageSize) -> {
			return toExport(getAdMedia(name, rank, pageSize, currentPage).getRecords());
		});
    }
	
	private List<AdMediaExportDTO> toExport(List<AdMedia> list) {
		List<AdMediaExportDTO> exportDTOs = new ArrayList<AdMediaExportDTO>();
		
		if (CollectionUtils.isNotEmpty(list)) {
			for (AdMedia adMedia : list) {
				AdMediaExportDTO exportDTO = new AdMediaExportDTO();
				exportDTO.setRankName(EnumHelperUtil.getOneByCode(MediaRankEnum.class, adMedia.getRank() + "").getName());
				
				BeanUtils.copyProperties(adMedia, exportDTO);
				
				exportDTOs.add(exportDTO);
			}
		}
		
		return exportDTOs;
	}
	
	@RequestMapping(value = "/detail.do")
	public String detail(Integer id, ModelMap model) {
        AdMedia adMedia = adMediaService.getById(id);
        model.put("map", adMedia);
        
        return "admedia/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", "服务器异常");
        adMediaService.removeById(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) {
            adMediaService.removeById(id);
		}
        
        returnResult(request, response, result);
    }
	
	@RequestMapping(value = "/save.do")
    public void save(AdMediaForm adMediaForm, HttpServletRequest request, HttpServletResponse response) {
		JSONObject result = new JSONObject();
        result.put("code", Constants.CODE_SUCCESS);
        result.put("msg", "服务器异常");
        
        // 更新
        if (adMediaForm.getId() != null) {
        	AdMedia adMediaInDb = adMediaService.getByName(adMediaForm.getName().trim());
	        if (adMediaInDb != null && !adMediaInDb.getId().equals(adMediaForm.getId())) {
	        	result.put("code", Constants.CODE_FAIL);
	        	result.put("msg", "名称重复");
	        	returnResult(request, response, result);
	        	return;
			}
	        
	        AdMedia adMedia = new AdMedia();
	        BeanUtils.copyProperties(adMediaForm, adMedia);
	        adMediaService.updateById(adMedia);

        } else {
			// 新增
	        AdMedia adMediaInDb = adMediaService.getByName(adMediaForm.getName().trim());
	        if (adMediaInDb != null) {
	        	result.put("code", Constants.CODE_FAIL);
	        	result.put("msg", "名称重复");
	        	returnResult(request, response, result);
	        	return;
			}
	        AdMedia adMedia = new AdMedia();
	        BeanUtils.copyProperties(adMediaForm, adMedia);
	        adMediaService.save(adMedia);
		}
        
        
        returnResult(request, response, result);
    }
	
	@RequestMapping(value = "import_excel.do")
    public String importExcel(HttpServletRequest request, HttpServletResponse response, MultipartFile excelfile) {
        Integer code = Constants.CODE_FAIL;// 执行结果
        String msg = "服务器异常";// 返回信息
        String returnStr = "common/import_callback";//返回视图
        try {
            
        	BaseExcelListener<AdMediaImportDTO> listener = new BaseExcelListener<>();
            EasyExcel.read(excelfile.getInputStream(), AdMediaImportDTO.class,listener).sheet(1).doRead();
            List<AdMediaImportDTO> dtos = listener.getDataList();
            dtos.stream().forEach(x -> x.check());
            
            for(AdMediaImportDTO dto: dtos) {
            	if (dto.getMsg() != null && dto.getMsg().contains("重复")){
                    request.setAttribute("repeat", 1);
                    request.setAttribute("code", Constants.CODE_FAIL);
                    request.setAttribute("msg", msg);
                    return "common/import_callback";
                }
            }
            
            msg =  adMediaService.importBatch(dtos);
            // 判断执行结果
            if("ok".equals(msg)) {
	        	request.setAttribute("repeat", 0);
	            request.setAttribute("code", Constants.CODE_SUCCESS);
	            request.setAttribute("msg", msg);
	            return "common/import_callback";
            }		
        } catch (Exception e) {
            log.error("import_excel_for_advertise.do error:" + e.getMessage(), e);
            if(e.getMessage().equals("重复媒体名称")) {
            	msg = e.getMessage();
            }
        }
        // 返回结果
        request.setAttribute("code", code);
        request.setAttribute("msg", msg);
        return returnStr;
    }
	
	/**
	 *    播出媒体下拉分类菜单列表(用于select控件)
	 * @param form 
	 */
    @RequestMapping(value = "/select/list.do")
    public void getSelectList(String name , Integer pageSize, Integer pageNo
    		,HttpServletRequest request, HttpServletResponse response
    		){
    	JSONArray results = new JSONArray();
    	JSONObject vo = new JSONObject();
    	int count = adMediaService.getTotalByName(name);
    	if(count > 0) {
    		IPage<AdMedia> page = getAdMedia(name, null , pageSize, pageNo);
    		for (AdMedia select : page.getRecords()) {
    			JSONObject obj = new JSONObject();
    			obj.put("id", select.getName());
    			obj.put("text", select.getName());
    			results.add(obj);
    		}
    	}
		vo.put("results", results);
		vo.put("total", count);
		returnResult(request, response, vo);
    }
}
