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.JSONArray;
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.AdPlatform;
import com.ylcm.sys.excel.listener.BaseExcelListener;
import com.ylcm.sys.excel.model.AdPlatformExportDTO;
import com.ylcm.sys.excel.model.AdPlatformImportDTO;
import com.ylcm.sys.form.AdPlatformForm;
import com.ylcm.sys.form.AdPlatformListForm;
import com.ylcm.sys.service.AdPlatformService;
import com.ylcm.sys.service.AdSelectTypeService;
import com.ylcm.sys.vo.AdPlatformVO;

import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 栏目管理表 前端控制器
 * </p>
 *
 * @author admin
 * @since 2020-07-01
 */
@Controller
@RequestMapping("/ad-platform")
@Slf4j
public class AdPlatformController extends BaseController{

    @Resource
    private AdPlatformService adPlatformService;
    @Resource
    private AdSelectTypeService adSelectTypeService;
    
    /**
     * to 栏目管理
     * */
    @RequestMapping(value = "/index.do")
    public String index(ModelMap model) {
        // 菜单选中，和权限对应
    	model.put("menu", "platform_mng");
        model.put("parentMenu", "ad_placement");
        return "adplatform/index";
    }
    
    @RequestMapping(value = "/ajax_list.do")
    public void mediaList(AdPlatformListForm form, 
            HttpServletRequest request, HttpServletResponse response) {
        JSONObject result = new JSONObject();
        result.put("code", Constants.CODE_SUCCESS);
        result.put("msg", "服务器异常");
       
        IPage<AdPlatform> page = adPlatformService.page(new Page<AdPlatform>(form.getPageNo(), form.getPageSize()), form.toAdPlatformQueryWrapper());        
        IPage<AdPlatformVO> vos = new Page<AdPlatformVO>();
        BeanUtils.copyProperties(page, vos);
        List<AdPlatformVO> voList = new ArrayList<>((int) page.getSize());
        if (CollectionUtils.isNotEmpty(page.getRecords())) {
            for (AdPlatform adPlatform : page.getRecords()) {
                voList.add(AdPlatformVO.form(adPlatform));
            }
            vos.setRecords(voList);
        }
        result.put("list", vos);
        result.put("msg", "操作成功");
        returnResult(request, response, result);
    } 
    
	@RequestMapping(value = "/detail.do")
	public String detail(Integer id, ModelMap model) {
		AdPlatform adPlatform = adPlatformService.getById(id);
        model.put("map", adPlatform);
        return "adplatform/detail";
	}
	
	@RequestMapping(value = "/del.do")
    public void del(Integer id, HttpServletRequest request, HttpServletResponse response) {
		JSONObject result = new JSONObject();
        result.put("code", Constants.CODE_FAIL);
        result.put("msg", "服务器异常");
        boolean flag = adPlatformService.removeById(id);
        if(flag) {
        	result.put("code", Constants.CODE_SUCCESS);
            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", "服务器异常");
        String[] idArray = ids.split(",");
        for (String id : idArray) {
        	adPlatformService.removeById(id);
		}
        returnResult(request, response, result);
    }
	
	@RequestMapping(value = "/save.do")
    public void save(AdPlatformForm adPlatformForm, HttpServletRequest request, HttpServletResponse response) {
		JSONObject result = new JSONObject();
        result.put("code", Constants.CODE_SUCCESS);
        result.put("msg", "服务器异常");
        
        // 更新
        if (adPlatformForm.getId() != null) {
        	AdPlatform adPlatform = adPlatformService.getByName(adPlatformForm.getPlatformName().trim());
	        if (adPlatform != null && !adPlatform.getId().equals(adPlatformForm.getId())) {
	        	result.put("code", Constants.CODE_FAIL);
	        	result.put("msg", "名称重复");
	        	returnResult(request, response, result);
	        	return;
			}
	        AdPlatform upAdPlatform = new AdPlatform();
	        BeanUtils.copyProperties(adPlatformForm, upAdPlatform);
	        adPlatformService.updateById(upAdPlatform);

        } else {
			// 新增
        	AdPlatform adPlatform = adPlatformService.getByName(adPlatformForm.getPlatformName().trim());
	        if (adPlatform != null) {
	        	result.put("code", Constants.CODE_FAIL);
	        	result.put("msg", "名称重复");
	        	returnResult(request, response, result);
	        	return;
			}
	        AdPlatform addAdPlatform = new AdPlatform();
	        BeanUtils.copyProperties(adPlatformForm, addAdPlatform);
	        adPlatformService.save(addAdPlatform);
		}
        returnResult(request, response, result);
    }
	
	@RequestMapping(value = "/export.do")
    public void export(AdPlatformListForm form,HttpServletRequest request, HttpServletResponse response) {

		ExcelUtil.exportExcelToWebsite(response,"栏目列表",new AdPlatformExportDTO(),(currentPage, pageSize) -> {
			return toExport(adPlatformService.page(new Page<AdPlatform>(currentPage, pageSize), form.toAdPlatformQueryWrapper()).getRecords());
		});
    }
	
	private List<AdPlatformExportDTO> toExport(List<AdPlatform> list) {
		List<AdPlatformExportDTO> exportDTOs = new ArrayList<AdPlatformExportDTO>();
		if (CollectionUtils.isNotEmpty(list)) {
			list.stream().forEach(x ->{
				exportDTOs.add(new AdPlatformExportDTO.AdPlatformExportDTOBuilder().adPlatform(x).build());
			});
		}
		return exportDTOs;
	}
	
	@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<AdPlatformImportDTO> listener = new BaseExcelListener<>();
            EasyExcel.read(excelfile.getInputStream(), AdPlatformImportDTO.class,listener).sheet(1).doRead();
            List<AdPlatformImportDTO> dtos = listener.getDataList();
            dtos.stream().forEach(x -> x.check());
            
            for(AdPlatformImportDTO 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 = adPlatformService.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("ad-platform_import_excel.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(AdPlatformListForm form
    		,HttpServletRequest request, HttpServletResponse response
    		){
    	JSONArray results = new JSONArray();
    	JSONObject vo = new JSONObject();
    	int count = adPlatformService.getTotalByName(form.getPlatformName());
    	if(count > 0) {
    		IPage<AdPlatform> page = adPlatformService.page(new Page<AdPlatform>(form.getPageNo(), form.getPageSize()), form.toAdPlatformQueryWrapper());        
    		for (AdPlatform select : page.getRecords()) {
    			JSONObject obj = new JSONObject();
    			obj.put("id", select.getPlatformName());
    			obj.put("text", select.getPlatformName());
    			results.add(obj);
    		}
    	}
		vo.put("results", results);
		vo.put("total", count);
		returnResult(request, response, vo);
    }
}
