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.AdTv;
import com.ylcm.sys.excel.listener.BaseExcelListener;
import com.ylcm.sys.excel.model.AdTvExportDTO;
import com.ylcm.sys.excel.model.AdTvImportDTO;
import com.ylcm.sys.form.AdTvForm;
import com.ylcm.sys.form.AdTvListForm;
import com.ylcm.sys.service.AdSelectTypeService;
import com.ylcm.sys.service.AdTvService;
import com.ylcm.sys.vo.AdTvVO;

import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 电视剧管理表 前端控制器
 * </p>
 *
 * @author admin
 * @since 2020-07-01
 */
@Controller
@RequestMapping("/ad-tv")
@Slf4j
public class AdTvController extends BaseController{
	
	@Resource
	private AdTvService adTvService;
    @Resource
    private AdSelectTypeService adSelectTypeService;

    /**
     * to 电商剧管理
     * */
	@RequestMapping(value = "/index.do")
    public String index(ModelMap model) {
        // 菜单选中，和权限对应
		model.put("menu", "tv_mng");
	    model.put("parentMenu", "ad_placement");
        return "adtv/index";
    }
	
	@RequestMapping(value = "/ajax_list.do")
    public void mediaList(AdTvListForm form, 
    		HttpServletRequest request, HttpServletResponse response) {
		JSONObject result = new JSONObject();
        result.put("code", Constants.CODE_SUCCESS);
        result.put("msg", "服务器异常");

        IPage<AdTv> page = adTvService.page(new Page<AdTv>(form.getPageNo(), form.getPageSize()), form.toAdTvQueryWrapper());
        IPage<AdTvVO> vos = new Page<AdTvVO>();
        BeanUtils.copyProperties(page, vos);
        List<AdTvVO> voList = new ArrayList<>((int) page.getSize());
        if (!CollectionUtils.isEmpty(page.getRecords())) {
            for (AdTv adTv: page.getRecords()) {
            	AdTvVO adTvVO = AdTvVO.from(adTv);
                voList.add(adTvVO);
            }
            vos.setRecords(voList);
        }
        result.put("msg", "操作成功");
        result.put("list", vos);
        returnResult(request, response, result);
    }
	
	@RequestMapping(value = "/detail.do")
	public String detail(Integer id, ModelMap model) {
        AdTv adTv = adTvService.getById(id);
        model.put("map", adTv);
        return "adtv/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", "服务器异常");
        boolean flag =  adTvService.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) {
        	adTvService.removeById(id);
		}
        returnResult(request, response, result);
    }
	
	@RequestMapping(value = "/save.do")
    public void save(AdTvForm adTvForm, HttpServletRequest request, HttpServletResponse response) {
		JSONObject result = new JSONObject();
        result.put("code", Constants.CODE_SUCCESS);
        result.put("msg", "服务器异常");
        // 更新
        if (adTvForm.getId() != null) {
        	AdTv adTv = adTvService.getByName(adTvForm.getName().trim());
	        if (adTv != null && !adTv.getId().equals(adTvForm.getId())) {
	        	result.put("code", Constants.CODE_FAIL);
	        	result.put("msg", "名称重复");
	        	returnResult(request, response, result);
	        	return;
			}
	        AdTv upAdTv = new AdTv();
	        BeanUtils.copyProperties(adTvForm, upAdTv);
	        adTvService.updateById(upAdTv);
	        result.put("msg", "操作成功");
        } else {
			// 新增
        	AdTv adTv = adTvService.getByName(adTvForm.getName().trim());
	        if (adTv != null) {
	        	result.put("code", Constants.CODE_FAIL);
	        	result.put("msg", "名称重复");
	        	returnResult(request, response, result);
	        	return;
			}
	        AdTv addAdTv = new AdTv();
	        BeanUtils.copyProperties(adTvForm, addAdTv);
	        adTvService.save(addAdTv);
	        result.put("msg", "操作成功");
		}
        returnResult(request, response, result);
    }
	
	@RequestMapping(value = "/export.do")
    public void export(AdTvListForm form,HttpServletRequest request, HttpServletResponse response) {

		ExcelUtil.exportExcelToWebsite(response,"电视剧列表",new AdTvExportDTO(),(currentPage, pageSize) -> {
			return toExport(adTvService.page(new Page<AdTv>(currentPage, pageSize), form.toAdTvQueryWrapper()).getRecords());
		});
    }
	
	private List<AdTvExportDTO> toExport(List<AdTv> list) {
		List<AdTvExportDTO> exportDTOs = new ArrayList<AdTvExportDTO>();
		if (CollectionUtils.isNotEmpty(list)) {
			list.stream().forEach(x ->{
				exportDTOs.add(new AdTvExportDTO.AdTvExportDTOBuilder().adTv(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<AdTvImportDTO> listener = new BaseExcelListener<>();
            EasyExcel.read(excelfile.getInputStream(), AdTvImportDTO.class,listener).sheet(1).doRead();
            List<AdTvImportDTO> dtos = listener.getDataList();
            dtos.stream().forEach(x -> x.check());
            
            for(AdTvImportDTO 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 = adTvService.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(AdTvListForm form
    		,HttpServletRequest request, HttpServletResponse response
    		){
    	JSONArray results = new JSONArray();
    	JSONObject vo = new JSONObject();
    	int count = adTvService.getTotalByName(form.getName());
    	if(count > 0) {
    		IPage<AdTv> page = adTvService.page(new Page<AdTv>(form.getPageNo(), form.getPageSize()), form.toAdTvQueryWrapper());        
    		for (AdTv 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);
    }
	
}
