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.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.AdSpecial;
import com.ylcm.sys.excel.listener.BaseExcelListener;
import com.ylcm.sys.excel.model.AdSpecialExportDTO;
import com.ylcm.sys.excel.model.AdSpecialImportDTO;
import com.ylcm.sys.form.AdSpecialForm;
import com.ylcm.sys.form.AdSpecialQueryForm;
import com.ylcm.sys.service.AdSpecialService;
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;
	
	@RequestMapping(value = "/index.do")
    public String index(ModelMap model, Integer type) {
        // 菜单选中，和权限对应
        model.put("menu", "special_product_mng");
        model.put("parentMenu", "ad_placement");
        model.put("type", 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,"专题广告列表",new AdSpecialExportDTO(),(currentPage, pageSize) -> {
			adSpecialQueryForm.setPageNo(currentPage);
			adSpecialQueryForm.setPageSize(pageSize);
			return toExport(adSpecialService.queryPage(adSpecialQueryForm).getRecords());
		});
    }
	
	private List<AdSpecialExportDTO> toExport(List<AdSpecial> adSpecials) {
		if (CollectionUtils.isEmpty(adSpecials)) {
			return new ArrayList<AdSpecialExportDTO>();
		}
		List<AdSpecialExportDTO> exportDTOs = new ArrayList<AdSpecialExportDTO>();
		for (AdSpecial adSpecial : adSpecials) {
			exportDTOs.add(AdSpecialExportDTO.from(adSpecial));
		}
		return exportDTOs;
	}
	
	@RequestMapping(value = "/detail.do")
	public String detail(Integer id, ModelMap model) {
        AdSpecial adSpecial = adSpecialService.getById(id);
        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.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) {
        	adSpecialService.removeById(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", "服务器异常");
        
        // 更新
        if (form.getId() != null) {
        	AdSpecial domainInDb = adSpecialService.getOneByForm(form);
	        if (domainInDb != null && !domainInDb.getId().equals(domainInDb.getId())) {
	        	result.put("code", Constants.CODE_FAIL);
	        	result.put("msg", "数据重复");
	        	returnResult(request, response, result);
	        	return;
			}
	        
	        AdSpecial domain = form.toSpecial();
	        adSpecialService.updateById(domain);

        } else {
			// 新增
        	AdSpecial domainInDb = adSpecialService.getOneByForm(form);
	        if (domainInDb != null) {
	        	result.put("code", Constants.CODE_FAIL);
	        	result.put("msg", "数据重复");
	        	returnResult(request, response, result);
	        	return;
			}
	        AdSpecial domain = form.toSpecial();
	        adSpecialService.save(domain);
		}
        
        returnResult(request, response, result);
    }
	
	@RequestMapping(value = "import_excel.do")
    public String importExcel(HttpServletRequest request, HttpServletResponse response,Integer type, MultipartFile excelfile) {
        Integer code = Constants.CODE_FAIL;// 执行结果
        String msg = "服务器异常";// 返回信息
        String returnStr = "common/import_callback";//返回视图
        try {
            
        	BaseExcelListener<AdSpecialImportDTO> listener = new BaseExcelListener<>();
            EasyExcel.read(excelfile.getInputStream(), AdSpecialImportDTO.class,listener).sheet(1).doRead();
            List<AdSpecialImportDTO> dtos = listener.getDataList();
            dtos.stream().forEach(x -> x.check());
            
            for(AdSpecialImportDTO 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";
                }
            	dto.setType(type);
            }
            
            adSpecialService.importBatch(dtos);
            // 判断执行结果
            code = "ok".equals(msg) ? Constants.CODE_SUCCESS : Constants.CODE_FAIL;
        } catch (Exception e) {
            log.error("import_excel_for_special.do error:" + e.getMessage(), e);
            if(e.getMessage().equals("重复媒体名称")) {
            	msg = e.getMessage();
            }
        }
        // 返回结果
        request.setAttribute("code", code);
        request.setAttribute("msg", msg);
        return returnStr;
    }
	
}
