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.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.AdProduct;
import com.ylcm.sys.domain.AdSelectType;
import com.ylcm.sys.enums.AdSelectTypeEnum;
import com.ylcm.sys.excel.listener.BaseExcelListener;
import com.ylcm.sys.excel.model.AdProductExportDTO;
import com.ylcm.sys.excel.model.AdProductImportDTO;
import com.ylcm.sys.form.AdProductForm;
import com.ylcm.sys.form.AdProductListForm;
import com.ylcm.sys.service.AdProductService;
import com.ylcm.sys.service.AdSelectTypeService;
import com.ylcm.sys.vo.AdProductVO;

import lombok.extern.slf4j.Slf4j;

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

	@Resource
	private AdProductService adProductService;
    @Resource
    private AdSelectTypeService adSelectTypeService;
	
    /**
     * to 产品管理
     * */
	@RequestMapping(value = "/index.do")
    public String index(ModelMap model) {
        // 菜单选中，和权限对应
        model.put("menu", "product_mng");
        model.put("parentMenu", "ad_placement");
        
        return "adproduct/index";
    }
	
	@RequestMapping(value = "/ajax_list.do")
    public void mediaList(AdProductListForm form, 
    		HttpServletRequest request, HttpServletResponse response) {
		JSONObject result = new JSONObject();
        result.put("code", Constants.CODE_SUCCESS);
        result.put("msg", "操作成功");
 
        IPage<AdProduct> page = adProductService.page(new Page<AdProduct>(form.getPageNo(), form.getPageSize()), form.toAdProductQueryWrapper());
        IPage<AdProductVO> vos = new Page<AdProductVO>();
        BeanUtils.copyProperties(page, vos);
        List<AdProductVO> voList = new ArrayList<>((int) page.getSize());
        if (!CollectionUtils.isEmpty(page.getRecords())) {
            for (AdProduct adProduct:page.getRecords()) {
            	AdProductVO adProductVO = AdProductVO.from(adProduct);
                voList.add(adProductVO);
            }
            vos.setRecords(voList);
        }
        result.put("list", vos);
        returnResult(request, response, result);
    }
	
	@RequestMapping(value = "/detail.do")
	public String detail(Integer id, ModelMap model) {
        AdProduct adProduct = adProductService.getById(id);
        model.put("map", adProduct);
        return "adproduct/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", "操作成功");
        try {
        	String error =  adProductService.deleteById(id);
        	if(error != null) {
        		result.put("code", Constants.CODE_FAIL);
        		result.put("msg", error);
        	}
        }catch (Exception e) {
        	log.error("ad-platform_import_del.do error:" + e.getMessage(), 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 = adProductService.deleteById(Integer.parseInt(id));
	            if(error != null) {
	            	result.put("code", Constants.CODE_FAIL);
	                result.put("msg", error);
	                break;
	            }
			}
        }catch (Exception e) {
        	log.error("ad-platform_batch_del.do error:" + e.getMessage(), e);
        	result.put("code", Constants.CODE_FAIL);
    		result.put("msg", "服务器异常");
		}
        returnResult(request, response, result);
    }
	
	@RequestMapping(value = "/save.do")
    public void save(AdProductForm adProductForm, HttpServletRequest request, HttpServletResponse response) {
		JSONObject result = new JSONObject();
        result.put("code", Constants.CODE_SUCCESS);
        result.put("msg", "服务器异常");
        // 更新
        if (adProductForm.getId() != null) {
        	AdProduct adProduct = adProductService.getByName(adProductForm.getProductName().trim(),adProductForm.getBrandName());
	        if (adProduct != null && !adProduct.getId().equals(adProductForm.getId())) {
	        	result.put("code", Constants.CODE_FAIL);
	        	result.put("msg", "名称重复");
	        	returnResult(request, response, result);
	        	return;
			}
	        adProductService.updateByForm(adProductForm);
	        result.put("msg", "操作成功");
        } else {
			// 新增
        	AdProduct adProduct = adProductService.getByName(adProductForm.getProductName().trim(),adProductForm.getBrandName());
	        if (adProduct != null) {
	        	result.put("code", Constants.CODE_FAIL);
	        	result.put("msg", "名称重复");
	        	returnResult(request, response, result);
	        	return;
			}
	        AdProduct addAdProduct = new AdProduct();
	        BeanUtils.copyProperties(adProductForm, addAdProduct);
	        adProductService.save(addAdProduct);
	        result.put("msg", "操作成功");
		}
        returnResult(request, response, result);
    }
	
	@RequestMapping(value = "/export.do")
    public void export(AdProductListForm form,HttpServletRequest request, HttpServletResponse response) {

		ExcelUtil.exportExcelToWebsite(response,"产品列表",new AdProductExportDTO(),(currentPage, pageSize) -> {
			return toExport(adProductService.page(new Page<AdProduct>(currentPage, pageSize), form.toAdProductQueryWrapper()).getRecords());
		});
    }
	
	private List<AdProductExportDTO> toExport(List<AdProduct> list) {
		List<AdProductExportDTO> exportDTOs = new ArrayList<AdProductExportDTO>();
		if (CollectionUtils.isNotEmpty(list)) {
			list.stream().forEach(x ->{
				exportDTOs.add(new AdProductExportDTO.AdProductExportDTOBuilder().adProduct(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<AdProductImportDTO> listener = new BaseExcelListener<>();
            EasyExcel.read(excelfile.getInputStream(), AdProductImportDTO.class,listener).sheet(1).doRead();
            List<AdProductImportDTO> 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(AdProductImportDTO 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.getFirstInd(), AdSelectTypeEnum.PRODUCT_COLUMN_PLATFORM.getCode());
            	if(adSelectType == null) {
            		request.setAttribute("code", Constants.CODE_FAIL);
                    request.setAttribute("msg", "第"+ index + "行" + "一级行业不存在，请核实！");
                    return "common/import_callback";
            	}
            	// 验证二级行业
             	AdSelectType adSecondSelectType = adSelectTypeService.getAdSecondSelectTypeByName(dto.getSecondInd() ,adSelectType.getId(), AdSelectTypeEnum.PRODUCT_COLUMN_PLATFORM.getCode());
            	if(adSecondSelectType == null) {
            		request.setAttribute("code", Constants.CODE_FAIL);
                    request.setAttribute("msg", "第"+ index + "行" + "二级行业与所选一级行业不符，请核实！");
                    return "common/import_callback";
            	}
            }
            msg = adProductService.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(AdProductListForm form, HttpServletRequest request, HttpServletResponse response){
    	JSONArray results = new JSONArray();
    	JSONObject vo = new JSONObject();
    	int count = adProductService.getSelectProductNameTotal(form.getProductName());
    	if (count > 0) {
    		form.page();
    		List<String> productNameList = adProductService.getSelectProductNameList(form.getProductName(), form.getPageNo(), form.getPageSize());
    		for (String productName : productNameList) {
    			JSONObject obj = new JSONObject();
    			obj.put("id", productName);
    			obj.put("text", productName);
    			results.add(obj);
    		}
    	}
		vo.put("results", results);
		vo.put("total", count);
		returnResult(request, response, vo);
    }
    
    /**
	   根据产品名称获取品牌名
	 * @param
	 */
   @RequestMapping(value = "/brand_name_by_product_name.do")
   public void getBrandNameSelectList(AdProductListForm form
   		,HttpServletRequest request, HttpServletResponse response
   		){
		JSONArray results = new JSONArray();
		JSONObject vo = new JSONObject();
		int count = adProductService.getBrandNameSelectTotalByName(form.getProductName());
	   	if (count > 0) {
    		IPage<AdProduct> page = adProductService.page(new Page<AdProduct>(form.getPageNo(), form.getPageSize()), form.toAdProductQueryBrandNameWrapper());        
    		for (AdProduct select : page.getRecords()) {
    			JSONObject obj = new JSONObject();
    			obj.put("id", select.getBrandName());
    			obj.put("text", select.getBrandName());
    			results.add(obj);
    		}
    	}
		vo.put("results", results);
		vo.put("total", count);
		returnResult(request, response, vo);
   }
   
}
