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.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("msg", "操作成功");
        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", "服务器异常");
        boolean flag =  adProductService.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) {
        	adProductService.removeById(id);
		}
        
        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());
	        if (adProduct != null && !adProduct.getId().equals(adProductForm.getId())) {
	        	result.put("code", Constants.CODE_FAIL);
	        	result.put("msg", "名称重复");
	        	returnResult(request, response, result);
	        	return;
			}
	        AdProduct upAdProduct = new AdProduct();
	        BeanUtils.copyProperties(adProductForm, upAdProduct);
	        adProductService.updateById(upAdProduct);
	        result.put("msg", "操作成功");
        } else {
			// 新增
        	AdProduct adProduct = adProductService.getByName(adProductForm.getProductName().trim());
	        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 {
        	BaseExcelListener<AdProductImportDTO> listener = new BaseExcelListener<>();
            EasyExcel.read(excelfile.getInputStream(), AdProductImportDTO.class,listener).sheet(1).doRead();
            List<AdProductImportDTO> dtos = listener.getDataList();
            dtos.stream().forEach(x -> x.check());
            
            for(AdProductImportDTO 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 = adProductService.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(AdProductListForm form
    		,HttpServletRequest request, HttpServletResponse response
    		){
    	JSONArray results = new JSONArray();
    	JSONObject vo = new JSONObject();
    	int count = adProductService.getTotalByName(form.getProductName());
    	if(count > 0) {
    		IPage<AdProduct> page = adProductService.page(new Page<AdProduct>(form.getPageNo(), form.getPageSize()), form.toAdProductQueryWrapper());        
    		for (AdProduct select : page.getRecords()) {
    			JSONObject obj = new JSONObject();
    			obj.put("id", select.getProductName());
    			obj.put("text", select.getProductName());
    			results.add(obj);
    		}
    	}
		vo.put("results", results);
		vo.put("total", count);
		returnResult(request, response, vo);
    }
    
    /**
	   *     根据产品名称获取品牌名
	 * @param form 
	 */
   @RequestMapping(value = "/brand_name_by_product_name.do")
   public void getSelectList(String name
   		,HttpServletRequest request, HttpServletResponse response
   		){
		JSONObject vo = new JSONObject();
        String brandName = "";
		if(StringUtils.isNotBlank(name)) {
			try {
				AdProduct adProduct = adProductService.getByName(name);
	        	brandName =  adProduct != null && StringUtils.isNotBlank(adProduct.getBrandName()) ? adProduct.getBrandName() : "" ;
			} catch (Exception e) {
				log.error("ad-product/brand_name_by_product_name.do error",e.getMessage(),e);
			}
        } 
        vo.put("brandName", brandName);
		returnResult(request, response, vo);
   }
}
