package com.ylcm.sys.controller;


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.AdMedia;
import com.ylcm.sys.domain.AdPlatform;
import com.ylcm.sys.domain.AdProduct;
import com.ylcm.sys.domain.AdTheatre;
import com.ylcm.sys.domain.AdTheatreTv;
import com.ylcm.sys.domain.AdTv;
import com.ylcm.sys.excel.listener.BaseExcelListener;
import com.ylcm.sys.excel.model.AdTheatreExcelDTO;
import com.ylcm.sys.form.AdTheatreForm;
import com.ylcm.sys.service.AdMediaService;
import com.ylcm.sys.service.AdPlatformService;
import com.ylcm.sys.service.AdProductService;
import com.ylcm.sys.service.AdTheatreService;
import com.ylcm.sys.service.AdTheatreTvService;
import com.ylcm.sys.service.AdTvService;
import com.ylcm.sys.vo.AdTheatreVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 剧场管理
 *
 * @author liuyu
 */
@Slf4j
@Controller
@RequestMapping("/ad-theatre")
public class AdTheatreController extends BaseController{

	@Resource
	private AdTheatreService adTheatreService;
	@Resource
	private AdTvService adTvService;
	@Resource
	private AdTheatreTvService adTheatreTvService;
	@Resource
	private AdProductService adProductService;
	@Resource
	private AdPlatformService adPlatformService;
	@Resource
	private AdMediaService adMediaService;

	/**
	 * to 列表页面
	 * */
	@RequestMapping(value = "/index.do")
	public String index(ModelMap model) {
		// 菜单选中，和权限对应
		model.put("menu", "ad_theatre");
		model.put("parentMenu", "ad_placement");
		return "adtheatre/index";
	}

	/**
	 * 分页获取列表数据
	 * @param form 参数
	 */
	@RequestMapping(value = "/ajax_list.do")
	public void mediaList(AdTheatreForm form, HttpServletRequest request, HttpServletResponse response) {
		JSONObject result = new JSONObject();
		result.put("code", Constants.CODE_SUCCESS);
	    result.put("msg", "操作成功");

		IPage<AdTheatreVO> vos = adTheatreService.page(new Page<AdTheatre>(form.getPageNo(), form.getPageSize()), form);

		result.put("list", vos);
		returnResult(request, response, result);
	}

	@RequestMapping(value = "/detail.do")
	public String detail(Integer id, ModelMap model) {
		AdTheatre adTheatre = adTheatreService.getById(id);
		model.put("map", adTheatre);
		return "adtheatre/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", "服务器异常");
		String error = adTheatreService.deleteById(id);
		if (error == null) {
			result.put("code", Constants.CODE_SUCCESS);
			result.put("msg", "操作成功");
		} else {
			result.put("msg", error);
		}
		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) {
			adTheatreService.deleteById(Integer.parseInt(id));
		}
		returnResult(request, response, result);
	}

	@RequestMapping(value = "/save.do")
	public void save(AdTheatreVO vo, HttpServletRequest request, HttpServletResponse response) {
		JSONObject result = new JSONObject();
		result.put("code", Constants.CODE_SUCCESS);
		result.put("msg", "服务器异常");

		AdTheatre adTheatre = vo.toAdTheatre();
		if (vo.getId() != null) {
			// 更新
			AdTheatre old = adTheatreService.getUniqu(adTheatre);
			if (old != null && !old.getId().equals(adTheatre.getId())) {
				result.put("code", Constants.CODE_FAIL);
				result.put("msg", "数据重复");
				returnResult(request, response, result);
				return;
			}
			adTheatreService.saveOrUpd(adTheatre);
			result.put("msg", "操作成功");
		} else {
			// 新增
			AdTheatre old = adTheatreService.getUniqu(adTheatre);
			if (old != null) {
				result.put("code", Constants.CODE_FAIL);
				result.put("msg", "数据重复");
				returnResult(request, response, result);
				return;
			}
			adTheatreService.saveOrUpd(adTheatre);
			result.put("msg", "操作成功");
		}
		returnResult(request, response, result);
	}

	@RequestMapping(value = "/export.do")
	public void export(AdTheatreForm form, HttpServletRequest request, HttpServletResponse response) {
		ExcelUtil.exportExcelToWebsite(response,"剧场数据",new AdTheatreExcelDTO(),(currentPage, pageSize) -> {
			return toExport(adTheatreService.page(new Page<AdTheatre>(currentPage, pageSize), form).getRecords());
		});
	}

	private List<AdTheatreExcelDTO> toExport(List<AdTheatreVO> list) {
		if (CollectionUtils.isEmpty(list)){
			return null;
		}
		List<AdTheatreExcelDTO> dtoList = new ArrayList<AdTheatreExcelDTO>();
		list.forEach(x ->{
			// 电视剧收视数据
			AdTheatreTv tv = adTheatreTvService.getByTheatreId(x.getId());
			// 整合
			dtoList.add(new AdTheatreExcelDTO.AdTheatreExcelDTOBuilder().adTheatre(x).adTheatreTv(tv).build());
		});
		return dtoList;
	}

	@RequestMapping(value = "import_excel.do")
	public String importExcel(HttpServletRequest request, HttpServletResponse response, MultipartFile excelfile) {
		Integer code = Constants.CODE_FAIL;
		String msg = "服务器异常";
		String returnHtml = "common/import_callback";
		try {
			BaseExcelListener<AdTheatreExcelDTO> listener = new BaseExcelListener<>();
			EasyExcel.read(excelfile.getInputStream(), AdTheatreExcelDTO.class,listener).sheet(1).doRead();
			List<AdTheatreExcelDTO> dtos = listener.getDataList();
			// 表格实际从第二行开始导入
			int index = 2;
			// 待入库
			List<AdTheatre> list = new ArrayList<>();
			List<AdTheatreTv> tvList = new ArrayList<>();
			for (AdTheatreExcelDTO dto: dtos) {
				index++;

				/*
				 * “待入库”的剧场数据
				 */
				// 基本校验
				String errorMsg = dto.check();
				if (StringUtils.isNotBlank(errorMsg)){
					request.setAttribute("code", Constants.CODE_FAIL);
					request.setAttribute("msg", "第"+ index + "行" + errorMsg);
					return "common/import_callback";
				}
				AdTheatre adTheatre = dto.toAdTheatre();

				// 获取剧的体裁、细分体裁
				AdTv tv = adTvService.getByName(dto.getName());
				if (tv == null){
					request.setAttribute("code", Constants.CODE_FAIL);
					request.setAttribute("msg", "第"+ index + "行的剧不存在，请先到电视剧管理中添加该剧");
					return "common/import_callback";
				}
				adTheatre.setFirstTheme(tv.getFirstTheme());
				adTheatre.setSecondTheme(tv.getSecondTheme());

				// 媒体是否存在
				AdMedia media = adMediaService.getByName(dto.getMediaName());
				if (media == null){
					request.setAttribute("code", Constants.CODE_FAIL);
					request.setAttribute("msg", "第"+ index + "行的媒体不存在，请先到媒体管理中添加");
					return "common/import_callback";
				}

				// 产品or类目是否存在
				if (StringUtils.isBlank(adTheatre.getTypeName())){
					// 产品/类目名称可以为空
				} else if (Integer.valueOf(0).equals(adTheatre.getType())){
					// 产品是否存在
					AdProduct product = adProductService.getByName(adTheatre.getTypeName());
					if (product == null){
						request.setAttribute("msg", "第"+ index + "行产品不存在，请先到产品管理中添加");
						return "common/import_callback";
					}
				} else if (Integer.valueOf(1).equals(adTheatre.getType())){
					// 栏目是否存在
					AdPlatform platform = adPlatformService.getByName(adTheatre.getTypeName());
					if (platform == null){
						request.setAttribute("msg", "第"+ index + "行栏目不存在，请先到栏目管理中添加");
						return "common/import_callback";
					}
				}

				// 状态默认为“正常”
				adTheatre.setStatus(0);
				// 存入“待入库”列表
				list.add(adTheatre);

				/*
				 * “待入库”的电视剧数据
				 */
				tvList.add(dto.toAdTheatreTv());
			}
			// 入库
			msg = adTheatreService.batchAdd(list, tvList);
			// 判断执行结果
			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(e.getMessage(), e);
			if (e.getMessage().contains("数据重复")){
				msg = e.getMessage();
			}
		}
		// 返回结果
		request.setAttribute("code", code);
		request.setAttribute("msg", msg);
		return returnHtml;
	}

}
