/**
 * Description: CmCreditGoods控制器
 * Copyright:   Copyright (c)2015
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2015-08-10 下午 17:06:09
 * <p/>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2015-08-10   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.web.controller;

import com.beust.jcommander.internal.Lists;
import com.google.common.base.Strings;
import com.house365.beans.entity.*;
import com.house365.beans.po.UploadExcelPo;
import com.house365.beans.system.Page;
import com.house365.beans.vo.CmCreditGoodsVo;
import com.house365.beans.vo.CodeMessageVo;
import com.house365.beans.vo.CreditGoodsParamsVo;
import com.house365.rest.context.CmConstant;
import com.house365.web.cached.RedisUtilsInterface;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.*;
import com.house365.ws.beans.request.*;
import com.house365.ws.beans.response.*;
import com.house365.ws.beans.response.CmCreditGoodsResponse.ConsultantBatchResult;
import com.house365.ws.interfaces.server.*;
import com.house365.ws.system.ReturnResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * CmCreditGoods控制器<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2015-08-10
 * @see
 * @since 1.0
 */
@Controller
@RequestMapping("/cmcreditgoods")
public class CmCreditGoodsController extends BaseController {
    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 自动注入CmCreditGoodsWS实现
     */
    @Autowired
    private ICmCreditGoods cmCreditGoods;
    @Autowired
    private ICmOrder cmOrder;
    @Autowired
    private ICmExchangeCode cmExchangeCode;
    @Autowired
    private ICmExchangeCodeBatch cmExchangeCodeBatch;
    @Autowired
    private IAttachmentInterface attachmentInterface;

    @Autowired
    private ICmSeckillBooked cmSeckillBooked;

    @Autowired
    RedisUtilsInterface redisUtils;

    @Autowired
    private ICmProductStat cmProductStatService;

    @Autowired
    private ICmPromotion cmPromotion;

    @Autowired
    private ICmPromotionConfig cmPromotionConfig;
    @Autowired
    private ICmPromotionProduct promotionProduct;

    /**
     * Excel表字段名称
     */
    private final static String[] excelTitles = {"兑换码"};

    private String fileName = null;

    /**
     * 去新增CmCreditGoods
     *
     * @return 结果视图
     */
    @RequestMapping(value = "", params = "action=create")
    public String createForm(Model model) {
        // 去新增时，清楚附件表中resourceId=0的数据
        Integer id = 0;
        attachmentInterface.deleteByResourceId(id);
        model.addAttribute("action", "create");
        model.addAttribute("uniquePageKey", System.currentTimeMillis());

        CmCreditGoodsEntity good = new CmCreditGoodsEntity();
        good.setId(0);
        model.addAttribute("entity", good);
        setPromotions(model);

        return getAutoUrl("form");
    }

    private Map<String, List> setPromotions(Model model) {
        Map<String, List> result = new HashMap<>(10);

        Map<String, Object> queryMap = new HashMap<>(10);
        queryMap.put("EQ_status", "1");
        CmPromotionListRequest promotionListRequest = new CmPromotionListRequest();
        promotionListRequest.setSearchParams(queryMap);
        CmPromotionListResponse promotionList = cmPromotion.getCmPromotionList(promotionListRequest);
        if (promotionList.getObjectList() != null && !promotionList.getObjectList().isEmpty()) {
            model.addAttribute("promotionList", promotionList.getObjectList());
            result.put("promotionList", promotionList.getObjectList());
        }

        Map<String, Object> configQueryMap = new HashMap<>(10);
        configQueryMap.put("EQ_status", "1");
        CmPromotionConfigListRequest promotionConfigListRequest = new CmPromotionConfigListRequest();
        promotionConfigListRequest.setSearchParams(configQueryMap);
        CmPromotionConfigListResponse promotionConfigList = cmPromotionConfig.getCmPromotionConfigList(
                promotionConfigListRequest);
        if (promotionConfigList.getObjectList() != null && !promotionConfigList.getObjectList().isEmpty()) {
            model.addAttribute("promotionConfigList", promotionConfigList.getObjectList());
            result.put("promotionConfigList", promotionConfigList.getObjectList());
        }

        return result;
    }

    /**
     * 新增CmCreditGoods
     *
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> createCmCreditGoods(
            @Valid CmCreditGoodsVo vo, BindingResult result, RedirectAttributes redirectAttributes, Model model,
            HttpServletRequest req, HttpSession session
    ) {
        Map<String, List> promotionsMap = setPromotions(model);
        String[] promotions = req.getParameterValues("promotions");

        List<CmPromotionProductEntity> promotionProductEntities = new ArrayList<>();
        Map<String, Object> resultMap = new HashMap<>(10);
        //校验促销配置参数是否完整,根据页面选中的促销ID获取促销配置项列表,根据促销name和配置项name拼接字符串校验页面参数
        if (promotions != null && promotions.length > 0) {
            List<CmPromotionEntity> promotionList = promotionsMap.get("promotionList");
            List<CmPromotionConfigEntity> promotionConfigList = promotionsMap.get("promotionConfigList");
            for (String pn : promotions) {
                for (CmPromotionEntity promotionEntity : promotionList) {
                    if (promotionEntity.getName().equalsIgnoreCase(pn)) {
                        for (CmPromotionConfigEntity promotionConfigEntity : promotionConfigList) {
                            String key = pn + "_" + promotionConfigEntity.getConfigName();
                            if (Strings.isNullOrEmpty(req.getParameter(key))) {
                                addErrorMessage(model, promotionConfigEntity.getConfigName() + "参数没有配置");
                                model.addAttribute("action", "create");
                                resultMap.put("error", true);
                                resultMap.put("errorMessage",
                                        "促销" + promotionEntity.getDescription() + ":" + promotionConfigEntity.getDescription() + "参数没有配置");
                                return resultMap;
                            } else {
                                CmPromotionProductEntity promotionProductEntity = new CmPromotionProductEntity();
                                promotionProductEntity.setPromotionId(promotionEntity.getId());
                                promotionProductEntity.setConfigKey(promotionConfigEntity.getConfigName());
                                promotionProductEntity.setConfigValue(req.getParameter(key));
                                promotionProductEntity.setStatus(1);
                                promotionProductEntity.setCreateTime(new Date());
                                promotionProductEntities.add(promotionProductEntity);
                            }
                        }
                    }
                }
            }
        }

        // 获取jedis链接
        String cityKey = (String) req.getSession().getAttribute(CmConstant.CITY_KEY);
        String cityName = (String) req.getSession().getAttribute(CmConstant.CITY_NAME);
        String userName = (String) req.getSession().getAttribute(CmConstant.USER_NAME);
        String userRole = String.valueOf(req.getSession().getAttribute(CmConstant.USER_ROLE));

        String isSeckill = req.getParameter("entity.isSeckill");
        if (isSeckill == null || (!isSeckill.equals("1"))) {
            vo.getEntity().setIsSeckill(0);
        }

        try {
            String startTime = req.getParameter("entity.startTime");
            if (startTime != null && startTime.length() >= 10) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                vo.getEntity().setStartTime(dateFormat.parse(startTime));
            }

            String endTime = req.getParameter("entity.endTime");
            if (endTime != null && endTime.length() >= 10) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                vo.getEntity().setEndTime(dateFormat.parse(endTime));
            }

            // 转换两个
            String seckillStartTime = req.getParameter("entity.seckillStartTime");
            if (seckillStartTime != null && seckillStartTime.length() > 10) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                vo.getEntity().setSeckillStartTime(dateFormat.parse(seckillStartTime));
            }
            // 转换两个
            String seckillEndTime = req.getParameter("entity.seckillEndTime");
            if (seckillEndTime != null && seckillEndTime.length() > 10) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                vo.getEntity().setSeckillEndTime(dateFormat.parse(seckillEndTime));
            }
        } catch (ParseException ex) {
            logger.error(ex.getMessage(), ex);
            addErrorMessage(model, ex.getMessage());
            model.addAttribute("action", "create");
            resultMap.put("error", true);
            resultMap.put("errorMessage", ex.getMessage());// 未上传文件
            return resultMap;
        }

        // String userId = (String)
        // req.getSession().getAttribute(CmConstant.USER_ID);
        String sign = req.getParameter("sign");
        CmCreditGoodsRequest request = new CmCreditGoodsRequest();
        CmCreditGoodsResponse response = new CmCreditGoodsResponse();

        CreditGoodsParamsVo creditGoodsParamsVo = new CreditGoodsParamsVo();
        creditGoodsParamsVo.setUserName(userName);
        // creditGoodsParamsVo.setUserId(Integer.parseInt(userId));
        request.setParamsVo(creditGoodsParamsVo);
        // 标注上传excel批次，uuid
        String uuidBatchId = UUID.randomUUID().toString();

        CmCreditGoodsEntity entity = vo.getEntity();

        if ("on".equalsIgnoreCase(req.getParameter("isBuyLimit"))) {
            entity.setIsBuyLimit(0);
        } else {
            entity.setIsBuyLimit(1);
        }

        if ("up".equals(sign)) {
            if (entity.getId() != null) {
                // 清除当前秒杀活动兑换量
                redisUtils.addKeyVal(CmConstant.ORDER_COUNT + entity.getId(), "0");
                String des = entity.getDescription();
                entity.setDescription(
                        DateTimeUtils.getDateString(new Date(), DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT));
                cmProductStatService.saveOrUpdate(entity);
                entity.setDescription(des);
            }
            entity.setStatus(0);
        } else {
            entity.setStatus(1);

            if (entity.getId() != null) {
                // 清除当前秒杀活动兑换量
                redisUtils.addKeyVal(CmConstant.ORDER_COUNT + entity.getId(), "0");
            }
        }
        // 增加默认值
        if (userRole != null && userRole.trim().equals(CmConstant.ROLE_ADMIN)) {
            entity.setCityKey(CmConstant.ShiYeBu);
            entity.setCityName(CmConstant.ShiYeBuStr);
        } else {
            entity.setCityKey(cityKey);
            KlfCityEntity cityMap = CityUtil.getCityByCityKey(cityKey);
            //todo 获取城市map修改(暂不修改)
//            KlfCityEntity cityMap = CityUtil.getCityByCityKeyNew(cityKey);
            if (cityMap != null) {
                entity.setCityName(cityMap.getName());
            }
        }
        entity.setUpdateTime(new Date());
        entity.setCreateTime(new Date());
        entity.setIsDeleted(0);
        try {
            if ("0".equals(entity.getGoodsType()) || "2".equalsIgnoreCase(entity.getGoodsType())) {

                if (entity.getAutoSoldoutDate() != null && entity.getAutoSoldoutDate().before(new Date())) {
                    resultMap.put("error", true);
                    resultMap.put("errorMessage", "自动下架日期不能早于当天");// 未上传文件
                    return resultMap;
                }

                // 设置添加实物商品默认字段
                entity.setLatestBatch(uuidBatchId);
                request.setEntity(entity);
                model.addAttribute("entity", entity);
                response = cmCreditGoods.addCmCreditGoods(request);
                resultMap.put("id", response.getEntity().getId());
                resultMap.put("goodsType", entity.getGoodsType());
            } else if ("1".equals(entity.getGoodsType())) {
                // 设置添加虚拟商品默认字段
                entity.setLatestBatch(uuidBatchId);
                entity.setLatestBatchName(fileName);
                request.setEntity(entity);
                model.addAttribute("entity", entity);
                List<CmExchangeCodeEntity> entityList = new LinkedList<CmExchangeCodeEntity>();
                CmExchangeCodeEntity exchangeCodeEntity = null;
                @SuppressWarnings("unchecked")
                // 判断兑换码文件是否存在
                        UploadExcelPo uploadPo = (UploadExcelPo) req.getSession().getAttribute("uploadFilePo");
                // 判断是否是同一个
                Long uniquePageKey = Long.parseLong(req.getParameter("uniquePageKey").toString());
                if (null == uploadPo || (!uploadPo.getUniquePageKey().equals(uniquePageKey))) {
                    resultMap.put("error", true);
                    resultMap.put("errorMessage", "noUploadFile");// 未上传文件
                    return resultMap;
                }
                List<List<Object>> uploadFile = uploadPo.getExchangeCodeInList();
                List<Object> list = null;
                for (int i = 1; i < uploadFile.size() && i <= uploadFile.size(); i++) {
                    exchangeCodeEntity = new CmExchangeCodeEntity();
                    exchangeCodeEntity.setGoodId(entity.getId());
                    exchangeCodeEntity.setStatus(0);// 默认：未兑换
                    exchangeCodeEntity.setStartTime(entity.getStartTime());
                    exchangeCodeEntity.setEndTime(entity.getEndTime());
                    // 设置公共字段，创建时间等
                    exchangeCodeEntity.setCreateTime(entity.getCreateTime());
                    exchangeCodeEntity.setCityId(entity.getCityId());
                    exchangeCodeEntity.setCityName(entity.getCityName());
                    exchangeCodeEntity.setIsDeleted(0);// 0:正常，1：已删除
                    // 此处，所属批次未加
                    exchangeCodeEntity.setBatch(uuidBatchId);
                    list = uploadFile.get(i);
                    for (int j = 0; j < list.size(); j++) {
                        if (j == 0) {
                            exchangeCodeEntity.setExchangeCode(list.get(j).toString());
                        }
                    }
                    // 将设置好的公共字段，和uploadFile中迭代出来的数据添加至list中
                    entityList.add(exchangeCodeEntity);
                }
                request.setExchangeCodeEntityList(entityList);
                response = cmCreditGoods.addCmCreditGoodsAndExchangeCode(request);

                if (null == response.getBatchResults()) {
                    List<ConsultantBatchResult> batchResults = new ArrayList<>();
                    response.setBatchResults(batchResults);
                    model.addAttribute("batchResult", response);
                } else {
                    model.addAttribute("batchResult", response);
                }
                req.getSession().removeAttribute("uploadFile");
                resultMap.put("error", false);
                resultMap.put("successNum", response.getSuccessNum());
                resultMap.put("failedNum", response.getFailedNum());
                resultMap.put("batchResults", response.getBatchResults());
                resultMap.put("goodsType", "1");
            }
            if (null != response.getEntity()) {
                // 如果是秒杀商品，则需要加入缓存，否则清空缓存
                refreshRedisStock(response.getEntity());

                if (null != response.getEntity().getId()) {
                    resultMap.put("id", response.getEntity().getId());
                    // 新增数据时的上传图片，数据id绑定上传图片
                    Integer id = response.getEntity().getId();
                    attachmentInterface.updateAttachmentResourceId(id);
                    //更新排序
                    cmCreditGoods.updateSortList();

                    if (!promotionProductEntities.isEmpty()) {
                        //配置促销项
                        for (CmPromotionProductEntity promotionProductEntity : promotionProductEntities) {
                            promotionProductEntity.setProductId(id);
                            CmPromotionProductRequest promotionProductRequest = new CmPromotionProductRequest();
                            promotionProductRequest.setEntity(promotionProductEntity);
                            promotionProduct.addCmPromotionProduct(promotionProductRequest);

                        }
                    }
                }
            }
            return resultMap;
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            addErrorMessage(model, ex.getMessage());
            model.addAttribute("action", "create");
            return resultMap;
        }

    }

    /**
     * 删除CmCreditGoods
     *
     * @param id CmCreditGoods页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.DELETE})
    @ResponseStatus(HttpStatus.OK)
    public void delete(@PathVariable String id) {
        if (!StringUtils.isEmpty(id)) {
            List<String> idList = new ArrayList<>();
            if (id.contains(",")) {
                String[] ids = id.split(",");
                idList.addAll(Arrays.asList(ids));
                for (int i = 0; i < ids.length; i++) {
                    cmCreditGoods.deleteCmCreditGoodsById(Integer.valueOf(ids[i]));
                }
            } else {
                idList.add(id);
                cmCreditGoods.deleteCmCreditGoodsById(Integer.valueOf(id));
            }

            if (!idList.isEmpty()) {
                //disable promotions
                promotionProduct.updateStatus(idList, 0);
            }
        }
    }

    /**
     * 去查看CmCreditGoods
     *
     * @param id CmCreditGoods页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public String showForm(@PathVariable(value = "id") Integer id, Model model) {
        CmCreditGoodsResponse response = cmCreditGoods.getCmCreditGoodsById(id);
        setPromotions(model);

        Map<String, Object> queryMap = new HashMap<>(10);
        queryMap.put("EQ_productId", id);
        queryMap.put("EQ_status", 1);
        CmPromotionProductListRequest promotionProductListRequest = new CmPromotionProductListRequest();
        promotionProductListRequest.setSearchParams(queryMap);
        CmPromotionProductListResponse promotionProductListResponse = promotionProduct.getCmPromotionProductList(
                promotionProductListRequest);
        List<CmPromotionProductEntity> entities = promotionProductListResponse.getObjectList();


        // 获取上传批次列表
        CmExchangeCodeBatchListRequest listReq = new CmExchangeCodeBatchListRequest();
        Map<String, Object> map = new HashMap<>(10);
        map.put("EQ_goodId", response.getEntity().getId());
        map.put("EQ_isDeleted", 0);
        Page page = new Page();
        page.setCurrentPage(1);
        page.setPageSize(10000);
        listReq.setPaging(page);
        listReq.setSearchParams(map);
        listReq.setOrderColumn("create_time");
        CmExchangeCodeBatchListResponse resp = cmExchangeCodeBatch.getCmExchangeCodeBatchList(listReq);

        model.addAttribute("batchList", resp.getObjectList());
        model.addAttribute("entity", response.getEntity());
        model.addAttribute("promotions", entities);

        return getAutoUrl("form");
    }

    /**
     * 去修改CmCreditGoods
     *
     * @param id CmCreditGoods页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET}, params = "action=edit")
    public String updateForm(@PathVariable(value = "id") Integer id, Model model) {
        CmCreditGoodsResponse response = cmCreditGoods.getCmCreditGoodsById(id);

        setPromotions(model);

        Map<String, Object> queryMap = new HashMap<>(10);
        queryMap.put("EQ_productId", id);
        queryMap.put("EQ_status", 1);
        CmPromotionProductListRequest promotionProductListRequest = new CmPromotionProductListRequest();
        promotionProductListRequest.setSearchParams(queryMap);
        CmPromotionProductListResponse promotionProductListResponse = promotionProduct.getCmPromotionProductList(
                promotionProductListRequest);
        List<CmPromotionProductEntity> entities = promotionProductListResponse.getObjectList();
        model.addAttribute("promotions", entities);

        // 获取上传批次列表
        CmExchangeCodeBatchListRequest listReq = new CmExchangeCodeBatchListRequest();
        Map<String, Object> map = new HashMap<>(10);
        map.put("EQ_goodId", response.getEntity().getId());
        map.put("EQ_isDeleted", 0);
        Page page = new Page();
        page.setCurrentPage(1);
        page.setPageSize(10000);
        listReq.setPaging(page);
        listReq.setSearchParams(map);
        listReq.setOrderColumn("create_time");
        CmExchangeCodeBatchListResponse resp = cmExchangeCodeBatch.getCmExchangeCodeBatchList(listReq);
        model.addAttribute("batchList", resp.getObjectList());
        model.addAttribute("uniquePageKey", System.currentTimeMillis());
        model.addAttribute("entity", response.getEntity());
        model.addAttribute("action", "edit");
        return getAutoUrl("form");
    }

    /**
     * 修改CmCreditGoods
     *
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.POST}, params = "!seckillStartTime")
    @ResponseBody
    public Map<String, Object> updateCmCreditGoods(
            @Valid CmCreditGoodsVo vo, BindingResult result, @PathVariable Integer id,
            RedirectAttributes redirectAttributes, HttpServletRequest req, Model model
    ) {
        String cityKey = (String) req.getSession().getAttribute(CmConstant.CITY_KEY);
        String cityName = (String) req.getSession().getAttribute(CmConstant.CITY_NAME);
        String userName = (String) req.getSession().getAttribute(CmConstant.USER_NAME);

        Map<String, Object> resultMap = new HashMap<>(10);
        try {
            Map<String, List> promotionsMap = setPromotions(model);
            String[] promotions = req.getParameterValues("promotions");

            List<CmPromotionProductEntity> promotionProductEntities = new ArrayList<>();
            //校验促销配置参数是否完整,根据页面选中的促销ID获取促销配置项列表,根据促销name和配置项name拼接字符串校验页面参数
            if (promotions != null && promotions.length > 0) {
                List<CmPromotionEntity> promotionList = promotionsMap.get("promotionList");
                List<CmPromotionConfigEntity> promotionConfigList = promotionsMap.get("promotionConfigList");
                for (String pn : promotions) {
                    for (CmPromotionEntity promotionEntity : promotionList) {
                        if (promotionEntity.getName().equalsIgnoreCase(pn)) {
                            for (CmPromotionConfigEntity promotionConfigEntity : promotionConfigList) {
                                String key = pn + "_" + promotionConfigEntity.getConfigName();
                                if (Strings.isNullOrEmpty(req.getParameter(key))) {
                                    addErrorMessage(model, promotionConfigEntity.getConfigName() + "参数没有配置");
                                    model.addAttribute("action", "create");
                                    resultMap.put("error", true);
                                    resultMap.put("errorMessage",
                                            "促销" + promotionEntity.getDescription() + ":" + promotionConfigEntity.getDescription() + "参数没有配置");
                                    return resultMap;
                                } else {
                                    CmPromotionProductEntity promotionProductEntity = new CmPromotionProductEntity();
                                    promotionProductEntity.setPromotionId(promotionEntity.getId());
                                    promotionProductEntity.setConfigKey(promotionConfigEntity.getConfigName());
                                    promotionProductEntity.setConfigValue(req.getParameter(key));
                                    promotionProductEntity.setStatus(1);
                                    promotionProductEntity.setCreateTime(new Date());
                                    promotionProductEntity.setProductId(id);
                                    promotionProductEntities.add(promotionProductEntity);
                                }
                            }
                        }
                    }
                }
            }

            //关闭所有促销配置,重新设置
            promotionProduct.updateStatus(Lists.newArrayList("" + id), 0);

            //处理促销 update or add
            for (CmPromotionProductEntity promotionProductEntity : promotionProductEntities) {
                CmPromotionProductListRequest ppListRequest = new CmPromotionProductListRequest();
                Map<String, Object> ppQueryMap = new HashMap<>(10);
                ppQueryMap.put("EQ_productId", id);
                ppQueryMap.put("EQ_promotionId", promotionProductEntity.getPromotionId());
                ppListRequest.setSearchParams(ppQueryMap);
                CmPromotionProductListResponse ppListResponse = promotionProduct.getCmPromotionProductList(
                        ppListRequest);

                if (ppListResponse.getObjectList() != null && !ppListResponse.getObjectList().isEmpty()) {
                    CmPromotionProductRequest promotionProductRequest = new CmPromotionProductRequest();
                    CmPromotionProductEntity ppe = ppListResponse.getObjectList().get(0);
                    promotionProductEntity.setId(ppe.getId());
                    promotionProductRequest.setEntity(promotionProductEntity);
                    promotionProduct.updateCmPromotionProduct(promotionProductRequest);
                } else {
                    promotionProductEntity.setProductId(id);
                    CmPromotionProductRequest promotionProductRequest = new CmPromotionProductRequest();
                    promotionProductRequest.setEntity(promotionProductEntity);
                    promotionProduct.addCmPromotionProduct(promotionProductRequest);
                }

            }

            String startTime = req.getParameter("entity.startTime");
            if (startTime != null && startTime.length() >= 10) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                vo.getEntity().setStartTime(dateFormat.parse(startTime));
            }

            String endTime = req.getParameter("entity.endTime");
            if (endTime != null && endTime.length() >= 10) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                vo.getEntity().setEndTime(dateFormat.parse(endTime));
            }

            // 转换秒杀开始时间
            String seckillStartTime = req.getParameter("entity.seckillStartTime");
            if (seckillStartTime != null && seckillStartTime.length() > 10) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                vo.getEntity().setSeckillStartTime(dateFormat.parse(seckillStartTime));
            }
            // 转换秒杀结束时间
            String seckillEndTime = req.getParameter("entity.seckillEndTime");
            if (seckillEndTime != null && seckillEndTime.length() > 10) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                vo.getEntity().setSeckillEndTime(dateFormat.parse(seckillEndTime));
            }

            String sign = req.getParameter("sign");
            CmCreditGoodsRequest request = new CmCreditGoodsRequest();

            // 标注上传excel批次，uuid
            String uuidBatchId = UUID.randomUUID().toString();
            CmCreditGoodsEntity entity = vo.getEntity();

            if ("on".equalsIgnoreCase(req.getParameter("isBuyLimit"))) {
                entity.setIsBuyLimit(0);
            } else {
                entity.setIsBuyLimit(1);
            }

            //上架
            if ("up".equals(sign)) {
                entity.setStatus(0);
                // 清除当前秒杀活动兑换量
                redisUtils.addKeyVal(CmConstant.ORDER_COUNT + entity.getId(), "0");

                String des = entity.getDescription();
                entity.setDescription(
                        DateTimeUtils.getDateString(new Date(), DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT));
                cmProductStatService.saveOrUpdate(entity);
                entity.setDescription(des);

            } else {
                entity.setStatus(1);
                // 清除当前秒杀活动兑换量
                redisUtils.addKeyVal(CmConstant.ORDER_COUNT + entity.getId(), "0");
            }

            // 增加默认值
            entity.setUpdateTime(new Date());
            entity.setIsDeleted(0);
            CmCreditGoodsResponse responseE = cmCreditGoods.getCmCreditGoodsById(entity.getId());

            CmCreditGoodsResponse response = new CmCreditGoodsResponse();

            entity.setLatestBatch(uuidBatchId);
            entity.setLatestBatchName(fileName);
            request.setEntity(entity);
            model.addAttribute("entity", entity);
            CreditGoodsParamsVo creditGoodsParamsVo = new CreditGoodsParamsVo();
            creditGoodsParamsVo.setUserName(userName);
            request.setParamsVo(creditGoodsParamsVo);
            // subValidation(result, entity);
            if ("0".equals(entity.getGoodsType()) || "2".equals(entity.getGoodsType())) {
                // 设置添加实物商品默认字段
                request.setEntity(entity);
                model.addAttribute("entity", entity);
                response = cmCreditGoods.updateCmCreditGoodsById(request);
                resultMap.put("id", entity.getId());
                resultMap.put("goodsType", entity.getGoodsType());
            } else if ("1".equals(entity.getGoodsType())) {
                entity.setStock(responseE.getEntity().getStock());
                // 设置添加虚拟商品默认字段
                entity.setLatestBatch(uuidBatchId);
                entity.setLatestBatchName(fileName);
                request.setEntity(entity);
                model.addAttribute("entity", entity);
                List<CmExchangeCodeEntity> entityList = new LinkedList<CmExchangeCodeEntity>();
                CmExchangeCodeEntity exchangeCodeEntity = null;
                @SuppressWarnings("unchecked") UploadExcelPo uploadPo = (UploadExcelPo) req.getSession().getAttribute(
                        "uploadFilePo");
                // 判断是否是同一个页面的上传
                Long uniquePageKey = Long.parseLong(req.getParameter("uniquePageKey").toString());
                // 重新上传了兑换码,需要重新计算库存
                if (null != uploadPo && (uploadPo.getUniquePageKey().equals(uniquePageKey))) {
                    List<List<Object>> uploadFile = uploadPo.getExchangeCodeInList();
                    List<Object> list = null;
                    for (int i = 1; i < uploadFile.size() && i <= uploadFile.size(); i++) {

                        exchangeCodeEntity = new CmExchangeCodeEntity();
                        exchangeCodeEntity.setGoodId(entity.getId());
                        exchangeCodeEntity.setStatus(0);// 默认：未兑换
                        exchangeCodeEntity.setStartTime(entity.getStartTime());
                        exchangeCodeEntity.setEndTime(entity.getEndTime());
                        // 设置公共字段，创建时间等
                        exchangeCodeEntity.setCreateTime(entity.getCreateTime());
                        exchangeCodeEntity.setCityId(entity.getCityId());
                        exchangeCodeEntity.setCityName(entity.getCityName());
                        exchangeCodeEntity.setIsDeleted(0);// 0:正常，1：已删除
                        // 此处，所属批次未加
                        exchangeCodeEntity.setBatch(uuidBatchId);
                        list = uploadFile.get(i);
                        if (list.size() > 0) {
                            if (list.get(0) == null || list.get(0).toString().trim().equals("")) {
                                continue;
                            }
                            exchangeCodeEntity.setExchangeCode(list.get(0).toString());
                        }
                        // 将设置好的公共字段，和uploadFile中迭代出来的数据添加至list中
                        entityList.add(exchangeCodeEntity);
                    }
                    request.setExchangeCodeEntityList(entityList);
                    response = cmCreditGoods.updateCmCreditGoodsAndExchangeCode(request);
                } else {
                    response = cmCreditGoods.updateCmCreditGoods(request);
                    response.setResultCode(ReturnResult.SUCCESS.getResultCode());
                    response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
                }

                if (null != response) {
                    if (null == response.getBatchResults()) {
                        List<ConsultantBatchResult> batchResults = new ArrayList<>();
                        response.setBatchResults(batchResults);
                        model.addAttribute("batchResult", response);
                        resultMap.put("respCode", "0");
                    } else {
                        model.addAttribute("batchResult", response);
                    }
                }

                // 清除兑换码
                req.getSession().removeAttribute("uploadFilePo");
                resultMap.put("error", false);
                if (response != null) {
                    resultMap.put("successNum", response.getSuccessNum());
                    resultMap.put("failedNum", response.getFailedNum());
                    resultMap.put("batchResults", response.getBatchResults());
                }
                resultMap.put("id", entity.getId());
                resultMap.put("goodsType", "1");
            }

            //更新排序
            cmCreditGoods.updateSortList();

            if (response != null && response.getEntity() != null) {
                //刷新秒杀库存
                refreshRedisStock(response.getEntity());
            }

            return resultMap;
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            addErrorMessage(model, ex.getMessage());
            model.addAttribute("action", "edit");
            return resultMap;
        }
    }

    private synchronized void refreshRedisStock(CmCreditGoodsEntity entity) {
        // 如果是秒杀商品，则需要加入缓存，否则清空缓存
        if (entity.getIsSeckill() != null && 1 == entity.getIsSeckill()) {
            redisUtils.addKeyVal(CmConstant.SECKILL_STOCK + entity.getId(), String.valueOf(entity.getStock()));
            redisUtils.deleteKey(CmConstant.SECKILL_LEFT_STOCK_LIST + entity.getId());
            for (int i = 0; i < entity.getStock(); i++) {
                redisUtils.pushIntegerIntoRedisList(CmConstant.SECKILL_LEFT_STOCK_LIST + entity.getId(), 1);
            }
            // 清除该商品的秒杀记录
            cmSeckillBooked.deleteCmSeckillBookedByGoodId(entity.getId());
            // 清除当前秒杀活动兑换量
            redisUtils.addKeyVal(CmConstant.ORDER_COUNT + entity.getId(), "0");
            // 更新秒杀时间
            redisUtils.setValueNew("prduct:seckill:time:" + entity.getId(),
                    String.valueOf(entity.getSeckillStartTime().getTime()));
        }
    }

    /**
     * 更新排序值
     *
     * @return list page
     */
    @RequestMapping(value = "updateSortList", method = RequestMethod.GET)
    public String sortList() {
        cmCreditGoods.updateSortList();
        return redirect("/cmcreditgoods");
    }

    /**
     * 查询CmCreditGoods
     *
     * @param model   CmCreditGoods页面表单对象
     * @param number  分页配置
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String list(Integer number, Model model, HttpServletRequest request) {
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        // 获取城市列表
        List<KlfCityEntity> cityList = CityUtil.getCityList();
        model.addAttribute("cityList", cityList);
        String userRole = String.valueOf(request.getSession().getAttribute(CmConstant.USER_ROLE));
        // 获取用户角色
        if (!CmConstant.ROLE_ADMIN.equals(userRole)) {
            String cityKey = String.valueOf(request.getSession().getAttribute(CmConstant.CITY_KEY));
            // 区分城市,默认城市南京
            if (StringUtils.isEmpty(cityKey)) {
                searchParams.put("EQ_cityKey", cityKey);
            }
        }
        Page page = new Page(Page.TWENTY_PAGE_SIZE);
        if (null != number) {
            page.setCurrentPage(number);
        }
        searchParams.put("EQ_isDeleted", 0);
        CmCreditGoodsListRequest listRequest = new CmCreditGoodsListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        // 设定排序
        Object ocObj = request.getParameter("orderColumn");
        if (ocObj != null && !"".equals(ocObj.toString().trim())) {
            listRequest.setOrderColumn(ocObj.toString());
        } else {
            listRequest.setOrderColumn("sort_value desc,order_number desc,update_time  ");
        }
        Object omObj = request.getParameter("orderMode");
        if (omObj != null && !"".equals(omObj.toString().trim())) {
            listRequest.setOrderMode(omObj.toString());
        } else {
            listRequest.setOrderMode(Constant.DESC);
        }
        CmCreditGoodsListResponse response = cmCreditGoods.getCmCreditGoodsList(listRequest);
        model.addAttribute("page", response.getPaging());
        // 获取当前被抢的商品数量
        for (CmCreditGoodsEntity entity : response.getObjectList()) {
            if (entity.getIsSeckill() != null && entity.getIsSeckill() == 1) {
                // 剩余库存
                long availableCount = redisUtils.getListSize(CmConstant.SECKILL_LEFT_STOCK_LIST + entity.getId());
                // 当前被秒数量
                Integer secKillStock = (int) (entity.getStock() - availableCount);
                entity.setSeckillStock(secKillStock < 0 ? 0 : secKillStock);
                // 秒杀订单量
                Integer orderCount = redisUtils.getIntegerByKey(CmConstant.ORDER_COUNT + entity.getId());
                entity.setSeckillOrderCount(orderCount);
            }
            // 设置销量
            Page orderPage = new Page(Integer.MAX_VALUE);
            Map<String, Object> orderSearchParams = new HashMap<>(5);
            orderSearchParams.put("EQ_goodsId", entity.getId());
            CmOrderListRequest orderListRequest = new CmOrderListRequest();
            orderListRequest.setPaging(orderPage);
            orderListRequest.setSearchParams(orderSearchParams);
            CmOrderListResponse orderResponse = cmOrder.getCmOrderList(orderListRequest);
            int orderNum = 0;
            if (orderResponse != null && orderResponse.getObjectList() != null) {
                if (!orderResponse.getObjectList().isEmpty()) {
                    orderNum = orderResponse.getObjectList().size();
                }
            }
            entity.setExchangedCount(orderNum);
        }
        model.addAttribute("cmCreditGoods", response.getObjectList());
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }

    /**
     * 查询CmCreditGoods
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "/listCreditsOfAll", method = RequestMethod.GET)
    public String listCreditsOfAll(Integer number, Model model, HttpServletRequest request) {
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        if (searchParams.get("EQ_city") != null && org.apache.commons.lang3.StringUtils.isNotBlank(searchParams.get("EQ_city").toString())) {
            searchParams.put("EQ_cityKey", searchParams.get("EQ_city"));
        } else {
            String cityKey = (String) request.getSession().getAttribute(CmConstant.CITY_KEY);
            searchParams.put("EQ_cityKey", cityKey);
        }
        // 获取城市列表
//        List<KlfCityEntity> cityList = CityUtil.getCityList();
        String userName = String.valueOf(request.getSession().getAttribute(CmConstant.USER_NAME));
        List<KlfCityEntity> cityList = CityUtil.getCityListNew(userName);
        model.addAttribute("cityList", cityList);
        String userRole = String.valueOf(request.getSession().getAttribute(CmConstant.USER_ROLE));
        // 获取用户角色
        if (!CmConstant.ROLE_ADMIN.equals(userRole)) {
            String cityKey = String.valueOf(request.getSession().getAttribute(CmConstant.CITY_KEY));
            // 区分城市,默认城市南京
            if (StringUtils.isEmpty(cityKey)) {
                searchParams.put("EQ_cityKey", cityKey);
            }
        }
        Page page = new Page(Page.TWENTY_PAGE_SIZE);
        if (null != number) {
            page.setCurrentPage(number);
        }
        CmCreditGoodsListRequest listRequest = new CmCreditGoodsListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        // 设定排序
        Object ocObj = request.getParameter("orderColumn");
        if (ocObj != null && !"".equals(ocObj.toString().trim())) {
            listRequest.setOrderColumn(ocObj.toString());
        } else {
            listRequest.setOrderColumn("create_time");
        }
        Object omObj = request.getParameter("orderMode");
        if (omObj != null && !"".equals(omObj.toString().trim())) {
            listRequest.setOrderMode(omObj.toString());
        } else {
            listRequest.setOrderMode(Constant.DESC);
        }
        CmCreditGoodsListResponse response = cmCreditGoods.getCmCreditGoodsList(listRequest);
        model.addAttribute("page", response.getPaging());
        model.addAttribute("cmCreditGoods", response.getObjectList());
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }

    /**
     * 上架
     *
     * @return 结果视图
     */
    @SuppressWarnings("unused")
    @RequestMapping(value = "shelves/{ud}/{id}", method = {RequestMethod.GET})
    @ResponseBody
    public String shelves(@PathVariable String ud, @PathVariable String id) {

        CmCreditGoodsRequest request = new CmCreditGoodsRequest();
        CmCreditGoodsResponse response = new CmCreditGoodsResponse();
        String msg = null;
        try {
            if (!StringUtils.isEmpty(id)) {
                CmCreditGoodsResponse creditGoodsResp = cmCreditGoods.getCmCreditGoodsById(Integer.valueOf(id));
                CmCreditGoodsEntity entity = creditGoodsResp.getEntity();
                if ("up".equals(ud)) {
                    entity.setStatus(0);// 上架
                    // 如果是秒杀商品，则需要加入缓存，否则清空缓存
                    refreshRedisStock(entity);
                    String des = entity.getDescription();
                    entity.setDescription(
                            DateTimeUtils.getDateString(new Date(), DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT));
                    cmProductStatService.saveOrUpdate(entity);
                    entity.setDescription(des);
                    msg = "up";
                } else if ("down".equals(ud)) {
                    if (entity.getIsSeckill() != null && 1 == entity.getIsSeckill()) {
                        // 下架则清除秒杀缓存
                        redisUtils.deleteKey(CmConstant.SECKILL_STOCK + entity.getId());
                        // 清除当前秒杀活动兑换量
                        redisUtils.addKeyVal(CmConstant.ORDER_COUNT + entity.getId(), "0");
                        // 清空队列list
                        redisUtils.deleteKey(CmConstant.SECKILL_LEFT_STOCK_LIST + entity.getId());
                        // 清除该商品的秒杀记录
                        cmSeckillBooked.deleteCmSeckillBookedByGoodId(entity.getId());
                    }
                    entity.setStatus(1);// 未上架
                    msg = "down";
                }
                entity.setUpdateTime(new Date());
                request.setEntity(entity);
                cmCreditGoods.updateCmCreditGoods(request);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return msg;

    }

    /**
     * 删除上传批次名，未兑换的兑换码
     *
     * @return 结果视图
     */
    @SuppressWarnings("unused")
    @RequestMapping(value = "deleteExchangeCode/{id}", method = {RequestMethod.GET})
    @ResponseBody
    public String deleteExchangeCode(@PathVariable String id) {
        CmCreditGoodsRequest request = new CmCreditGoodsRequest();
        CmCreditGoodsResponse response = new CmCreditGoodsResponse();
        String msg = null;
        try {
            if (!StringUtils.isEmpty(id)) {
                CmExchangeCodeBatchResponse batchRes = cmExchangeCodeBatch.getCmExchangeCodeBatchById(
                        Integer.valueOf(id));
                CmExchangeCodeBatchEntity batchEntity = batchRes.getEntity();
                CmCreditGoodsResponse creditGoodsResp = cmCreditGoods.getCmCreditGoodsById(batchEntity.getGoodId());
                CmCreditGoodsEntity entity = creditGoodsResp.getEntity();
                // 查询未兑换的条数
                CmExchangeCodeListRequest ceclr = new CmExchangeCodeListRequest();
                Map<String, Object> map = new HashMap<>(10);
                map.put("EQ_batchId", id);
                map.put("EQ_status", 0);
                ceclr.setSearchParams(map);
                CmExchangeCodeListResponse exchangeList = cmExchangeCode.getCmExchangeCodeList(ceclr);
                Integer totalCount = exchangeList.getPaging().getRecords();

                List<CmExchangeCodeEntity> eCodeList = exchangeList.getObjectList();
                // 删除未兑换的兑换码
                CmExchangeCodeResponse exchangeCodeResponse = cmExchangeCode.deleteByBatchCode(Integer.parseInt(id));
                if (ReturnResult.FAIL.getResultCode().equals(exchangeCodeResponse.getResultCode())) {
                    msg = response.getResultCode();
                    return msg;
                }
                // 删除批次
                CmExchangeCodeBatchRequest batchReq = new CmExchangeCodeBatchRequest();
                batchRes.getEntity().setIsDeleted(1);
                batchReq.setEntity(batchRes.getEntity());
                cmExchangeCodeBatch.updateCmExchangeCodeBatch(batchReq);
                if (Integer.valueOf(exchangeCodeResponse.getResultCode()) > 0) {
                    // 更新商品
                    entity.setUpdateTime(new Date());
                    entity.setStock(entity.getStock() - totalCount);
                    entity.setLatestBatch(null);
                    entity.setLatestBatchName(null);
                    request.setEntity(entity);
                    response = cmCreditGoods.updateCmCreditGoods(request);
                    msg = response.getResultCode();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return msg;

    }

    /**
     * 功能描述: 上传Excel<br>
     *
     * @param request
     * @param model
     * @author nizhengjia
     */
    @RequestMapping(value = "upload", method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> upload(MultipartHttpServletRequest request, Model model) {
        Map<String, Object> resultMap = new HashMap<>(5);
        try {
            MultipartFile file = request.getFile("consultant_file");
            fileName = file.getOriginalFilename();
            List<List<Object>> importExcel = ExcelUtil.importExcelSecond(file.getInputStream());
            StringBuffer msg = null;
            int i = 0;
            for (List<Object> list : importExcel) {
                i++;
                msg = new StringBuffer();
                for (int j = 0; j < list.size(); j++) {
                    if (j == 1 && i != 1) {
                        msg.append(new BigDecimal(list.get(j).toString()).toPlainString()).append("   ");
                    } else {
                        msg.append(list.get(j)).append("   ");
                    }
                }
            }
            UploadExcelPo uploadPo = new UploadExcelPo();
            uploadPo.setExchangeCodeInList(importExcel);
            uploadPo.setFileName(fileName);
            Long uniquePageKey = Long.parseLong(request.getParameter("uniquePageKey").toString());
            uploadPo.setUniquePageKey(uniquePageKey);
            uploadPo.setUploadTime(new Date());
            request.getSession().setAttribute("uploadFilePo", uploadPo);
            resultMap.put("success", true);
            resultMap.put("fileName", fileName);
            resultMap.put("uploadTime", new Date());

        } catch (Exception se) {
            se.printStackTrace();
            resultMap.put("success", false);
        }
        return resultMap;
    }

    /**
     * 功能描述: 生成Excel<br>
     *
     * @author nizhengjia
     */
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void download(Integer number, Model model, HttpServletRequest request, HttpServletResponse response) {
        List<List<Object>> recordList = new ArrayList<>();
        ExcelUtil.exportExcel("兑换码模板导入模板.xls", "兑换码模板导入模板", excelTitles, recordList, response);
    }

    @RequestMapping(value = "showMessageSection", method = {RequestMethod.GET, RequestMethod.POST})
    public String showMessageSection(CodeMessageVo vo, Model model) {
        model.addAttribute("result", vo);
        return getAutoUrl();
    }

}
