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.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.AdSelectType;
import com.ylcm.sys.domain.AdTv;
import com.ylcm.sys.enums.AdSelectTypeEnum;
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 = "/detailByName.do")
    public void detailByName(@RequestParam String name, HttpServletRequest request, HttpServletResponse response) {
        JSONObject result = new JSONObject();
        result.put("data", adTvService.getByName(name));
        result.put("code", Constants.CODE_SUCCESS);
        result.put("msg", "操作成功");
        returnResult(request, response, result);
    }
	
	@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 =  adTvService.deleteById(id);
	        if(error != null) {
	            result.put("code", Constants.CODE_FAIL);
	            result.put("msg", error);
	        }
        }catch (Exception 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 =  adTvService.deleteById(Integer.parseInt(id));
	             if(error != null) {
                     result.put("code", Constants.CODE_FAIL);
	                 result.put("msg", error);
	                 break;
	             }
			}
        }catch (Exception e) {
        	result.put("code", Constants.CODE_FAIL);
            result.put("msg", "服务器异常");
		}
        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;
			}
	        adTvService.updateByForm(adTvForm);
	        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 {
        	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<AdTvImportDTO> listener = new BaseExcelListener<>();
            EasyExcel.read(excelfile.getInputStream(), AdTvImportDTO.class,listener).sheet(1).doRead();
            List<AdTvImportDTO> 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(AdTvImportDTO dto: dtos) {
            	index ++;
            	if (StringUtils.isNotBlank(dto.getMsg())){
                    request.setAttribute("code", Constants.CODE_FAIL);
                    request.setAttribute("msg", "第"+ index + "行" + dto.getMsg());
                    return "common/import_callback";
                }
                // 验证体裁
            	AdSelectType adSelectType = adSelectTypeService.getAdSelectTypeByName(dto.getFirstTheme(), AdSelectTypeEnum.TV_PLAY_MANAGE.getCode());
            	if(adSelectType == null) {
            		request.setAttribute("code", Constants.CODE_FAIL);
                    request.setAttribute("msg", "第"+ index + "行" + "体裁不存在，请核实！");
                    return "common/import_callback";
            	}
            	// 验证细分体裁
             	AdSelectType adSecondSelectType = adSelectTypeService.getAdSecondSelectTypeByName(dto.getSecondTheme() ,adSelectType.getId(), AdSelectTypeEnum.TV_PLAY_MANAGE.getCode());
            	if(adSecondSelectType == null) {
            		request.setAttribute("code", Constants.CODE_FAIL);
                    request.setAttribute("msg", "第"+ index + "行" + "细分体裁与所选体裁不符，请核实！");
                    return "common/import_callback";
            	}
            }
            msg = adTvService.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("ad-platform_import_excel.do error:" + e.getMessage(), e);
            if(e.getMessage().contains("重复")) {
            	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.getSelectTotalByName(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);
    }

	/**
	 * 电视剧下拉分类菜单列表(用于select控件) <br/>
	 * 有 id
	 */
	@RequestMapping(value = "/select/list2.do")
	public void getSelectList2(AdTvListForm form, HttpServletRequest request, HttpServletResponse response){
		JSONArray results = new JSONArray();
		JSONObject vo = new JSONObject();
		int count = adTvService.getSelectTotalByName(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.getId());
				obj.put("text", select.getName());
				results.add(obj);
			}
		}
		vo.put("results", results);
		vo.put("total", count);
		returnResult(request, response, vo);
	}
	
}
