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.bind.annotation.RequestParam;
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, false);
        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, Boolean complexSort) {
		LambdaQueryWrapper<AdMedia> queryWrapper = new LambdaQueryWrapper<AdMedia>();
        if (rank != null) {
			queryWrapper.eq(AdMedia::getRank, rank);
		}
        if (StringUtils.isNotBlank(name)) {
        	name = name.trim();
			queryWrapper.like(AdMedia::getName, name);
		}
		queryWrapper.orderByDesc(AdMedia::getCrtTime);
		IPage<AdMedia> iPage = adMediaService.page(new Page<AdMedia>(pageNo, pageSize), queryWrapper);
		// 复杂排序规则，单独获取 list
		if (complexSort != null && complexSort){
			iPage.setRecords(adMediaService.getListByPage(name, rank, pageSize, pageNo));
		}
		return iPage;
	}
	
	@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, false).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();
				if(adMedia.getRank() != null) {
					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", "操作成功");
        try {
        	String error = adMediaService.deleteById(id);
        	if (error != null) {
        		result.put("code", Constants.CODE_FAIL);
        		result.put("msg", error);
        	}
        }catch (Exception e) {
        	log.error("del_for_adMedia.do error:" + e.getMessage(), e);
    	    result.put("code", Constants.CODE_FAIL);
            result.put("msg", "服务器异常");
		}
        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", "操作成功");
        try {
	        String[] idArray = ids.split(",");
	        for (String id : idArray) {
				String error = adMediaService.deleteById(Integer.parseInt(id));
				if (error != null) {
					result.put("code", Constants.CODE_FAIL);
					result.put("msg", error);
					break;
				}
			}
        }catch (Exception e) {
        	log.error("batch_del_for_adMedia.do error:" + e.getMessage(), e);
        	result.put("code", Constants.CODE_FAIL);
            result.put("msg", "服务器异常");
		}
        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;
			}
	        adMediaService.updateByForm(adMediaForm);

        } 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 {
    		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";
    		}
        	BaseExcelListener<AdMediaImportDTO> listener = new BaseExcelListener<>();
            EasyExcel.read(excelfile.getInputStream(), AdMediaImportDTO.class,listener).sheet(1).doRead();
            List<AdMediaImportDTO> 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(AdMediaImportDTO dto: dtos) {
            	index ++;
            	if (StringUtils.isNotBlank(dto.getMsg())){
                    request.setAttribute("code", Constants.CODE_FAIL);
                    request.setAttribute("msg", "第"+ index + "行" + dto.getMsg());
                    return "common/import_callback";
                }
            }
            msg =  adMediaService.importBatch(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_advertise.do error:" + e.getMessage(), e);
            if(e.getMessage().contains("重复")) {
            	msg = e.getMessage();
            }
        }
        // 返回结果
        request.setAttribute("code", code);
        request.setAttribute("msg", msg);
        return returnStr;
    }
	
	/**
	 * 播出媒体下拉分类菜单列表(用于select控件)
	 * @param
	 */
    @RequestMapping(value = "/select/list.do")
    public void getSelectList(String name , @RequestParam(defaultValue="10") Integer pageSize, @RequestParam(defaultValue="1") 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, true);
    		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);
    }
}
