/**
 * Description: CmCreditGoodsWS接口
 * 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.ws.interfaces.impl;

import com.house365.beans.entity.CmAddGoodsEntity;
import com.house365.beans.entity.CmCreditGoodsEntity;
import com.house365.beans.entity.CmExchangeCodeBatchEntity;
import com.house365.beans.entity.CmExchangeCodeEntity;
import com.house365.beans.system.QueryParams;
import com.house365.beans.vo.CreditGoodsParamsVo;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.ws.beans.request.CmCreditGoodsListRequest;
import com.house365.ws.beans.request.CmCreditGoodsRequest;
import com.house365.ws.beans.response.CmCreditGoodsListResponse;
import com.house365.ws.beans.response.CmCreditGoodsResponse;
import com.house365.ws.interfaces.server.ICmCreditGoods;
import com.house365.ws.service.interfaces.*;
import com.house365.ws.system.ReturnResult;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Pattern;

/**
 * CmCreditGoodsWS接口<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2015-08-10
 * @see
 * @since 1.0
 */
@Service("cmCreditGoods")
public class CmCreditGoodsImpl implements ICmCreditGoods {
    /**
     * 日志记录器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(CmCreditGoodsImpl.class);

    /**
     * CmCreditGoods服务对象
     */
    @Autowired
    private ICmCreditGoodsService<CmCreditGoodsEntity> cmCreditGoodsService;
    @Autowired
    private ICmExchangeCodeService<CmExchangeCodeEntity> cmExchangeCodeService;
    @Autowired
    private ICmAddGoodsService<CmAddGoodsEntity> cmAddGoodsService;
    @Autowired
    private ICmExchangeCodeBatchService<CmExchangeCodeBatchEntity> cmExchangeCodeBatchService;

    @Autowired
    private ICmProductStatService cmProductStatService;


    //map转换成list
    @SuppressWarnings({"rawtypes", "unchecked"})
    public static List mapTransitionList(Map map) {
        List list = new ArrayList();
        Iterator iter = map.entrySet().iterator();  //获得map的Iterator
        while (iter.hasNext()) {
            Entry entry = (Entry) iter.next();
            list.add(entry.getValue());
        }
        return list;
    }

    public static void main(String[] args) {
        int i = (int) (Math.random() * 100000 * 9);
        System.out.println(i);
    }

    public static String parseDate(Date date, String format) {
        SimpleDateFormat dateformat = new SimpleDateFormat(format);
        return dateformat.format(date);
    }

    public static Date parseDate(String datestr, String dateFormate) {
        SimpleDateFormat df = new SimpleDateFormat(dateFormate);
        Date date = null;
        try {
            date = df.parse(datestr);
        } catch (java.text.ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * CmCreditGoods列表查询
     *
     * @param request CmCreditGoods列表查询请求
     * @return CmCreditGoods列表查询响应
     */
    @Override
    public CmCreditGoodsListResponse getCmCreditGoodsList(CmCreditGoodsListRequest request) {
        CmCreditGoodsListResponse response = new CmCreditGoodsListResponse();
        try {
            QueryParams<CmCreditGoodsEntity> queryParams = new QueryParams<>(request.getSearchParams());
            queryParams.setPaging(request.getPaging());
            queryParams.setOrderColumn(request.getOrderColumn());
            queryParams.setOrderMode(request.getOrderMode());
            List<CmCreditGoodsEntity> cmCreditGoodss = cmCreditGoodsService.queryByPage(queryParams);
            response.setPaging(queryParams.getPaging());
            response.setObjectList(cmCreditGoodss);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 保存CmCreditGoods
     *
     * @param request CmCreditGoods请求
     * @return 保存CmCreditGoods响应
     */
    @Override
    public CmCreditGoodsResponse addCmCreditGoods(CmCreditGoodsRequest request) {
        CmCreditGoodsResponse response = new CmCreditGoodsResponse();
        try {
            CmCreditGoodsEntity entity = request.getEntity();
            cmCreditGoodsService.save(entity);
            response.setEntity(entity);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 保存CmCreditGoods
     *
     * @param request CmCreditGoods请求
     * @return 保存CmCreditGoods响应
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    @Override
    public CmCreditGoodsResponse addCmCreditGoodsAndExchangeCode(CmCreditGoodsRequest request) {
        CmCreditGoodsResponse response = new CmCreditGoodsResponse();
        //获取商品参数
        CmCreditGoodsEntity entity = request.getEntity();
        entity.setDescription(htmlRemoveTag(entity.getDescription()));
        entity.setExchangeProcess(htmlRemoveTag(entity.getExchangeProcess()));
        entity.setAnnouncement(htmlRemoveTag(entity.getAnnouncement()));
        CreditGoodsParamsVo paramsVo = request.getParamsVo();
        //获取兑换码参数集合
        List<CmExchangeCodeEntity> exchangeCodeEntityListTemp = request.getExchangeCodeEntityList();
        List<CmExchangeCodeEntity> exchangeCodeEntityList = new ArrayList<>();
        if (null != exchangeCodeEntityListTemp) {
            CmExchangeCodeEntity exchangeCode = null;
            Map<String, CmExchangeCodeEntity> map = new LinkedHashMap<>();
            for (CmExchangeCodeEntity exchangeCodeEntity : exchangeCodeEntityListTemp) {
                exchangeCode = map.get(exchangeCodeEntity.getExchangeCode());
                if (exchangeCode == null) {
                    map.put(exchangeCodeEntity.getExchangeCode(), exchangeCodeEntity);
                }
            }
            exchangeCodeEntityList = mapTransitionList(map);
        }

        //获取exchangeCodeList
        List<String> exchangeCodeList = new ArrayList<>();
        for (CmExchangeCodeEntity en : exchangeCodeEntityList) {
            exchangeCodeList.add(en.getExchangeCode());
        }

        entity.setStock(exchangeCodeEntityList.size());
        //新增商品
        Integer sid = cmCreditGoodsService.save(entity);
        response.setEntity(entity);
        //把集合传到sql中查询，查不到则说明不重复可以保存
        if (CollectionUtils.isNotEmpty(exchangeCodeEntityList)) {
            //保存批次
            CmExchangeCodeBatchEntity codeBatch = new CmExchangeCodeBatchEntity();
            codeBatch.setGoodId(sid);
            codeBatch.setFileName(entity.getLatestBatchName());
            codeBatch.setCreaterId(paramsVo.getUserId());
            codeBatch.setCreaterName(paramsVo.getUserName());
            codeBatch.setCreateTime(new Date());
            codeBatch.setIsDeleted(0);
            Integer batchId = cmExchangeCodeBatchService.save(codeBatch);
            //新增兑换码
            for (CmExchangeCodeEntity exchangeCodeEntity : exchangeCodeEntityList) {
                exchangeCodeEntity.setBatchId(batchId);
                exchangeCodeEntity.setGoodId(entity.getId());//商品id
                cmExchangeCodeService.save(exchangeCodeEntity);
                response.incSuccessNum();
            }
        }
        response.setResultCode(ReturnResult.SUCCESS.getResultCode());
        response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        return response;
    }

    /**
     * 删除CmCreditGoods通过唯一标识
     *
     * @param id 唯一标识
     * @return 删除CmCreditGoods响应
     */
    @Override
    public CmCreditGoodsResponse deleteCmCreditGoodsById(Integer id) {
        CmCreditGoodsResponse response = new CmCreditGoodsResponse();
        try {
            cmCreditGoodsService.delete(id);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 修改CmCreditGoods
     *
     * @param request 修改CmCreditGoods请求
     * @return 修改CmCreditGoods响应
     */
    @Override
    public CmCreditGoodsResponse updateCmCreditGoods(CmCreditGoodsRequest request) {
        CmCreditGoodsResponse response = new CmCreditGoodsResponse();
        try {
            cmCreditGoodsService.update(request.getEntity());
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
            response.setEntity(request.getEntity());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 修改CmCreditGoods实物商品
     *
     * @param request 修改CmCreditGoods请求
     * @return 修改CmCreditGoods响应
     */
    @Override
    public CmCreditGoodsResponse updateCmCreditGoodsById(CmCreditGoodsRequest request) {
        CmCreditGoodsResponse response = new CmCreditGoodsResponse();
        CmCreditGoodsEntity entity = request.getEntity();
        CreditGoodsParamsVo paramsVo = request.getParamsVo();

        CmCreditGoodsEntity originGood = cmCreditGoodsService.getById(entity.getId());
        Integer replenishment = entity.getStock() - originGood.getStock();
        try {
            entity.setDescription(htmlRemoveTag(entity.getDescription()));
            entity.setExchangeProcess(htmlRemoveTag(entity.getExchangeProcess()));
            entity.setAnnouncement(htmlRemoveTag(entity.getAnnouncement()));
            cmCreditGoodsService.update(entity);
            //补货记录
            CmAddGoodsEntity cmAddGoodsEntity = new CmAddGoodsEntity();
            cmAddGoodsEntity.setGoodId(entity.getId());
            cmAddGoodsEntity.setGoodName(entity.getGoodsName());
            cmAddGoodsEntity.setAmount(replenishment);
            cmAddGoodsEntity.setOperatorName(paramsVo.getUserName());
            cmAddGoodsEntity.setOperatorId(paramsVo.getUserId());
            cmAddGoodsEntity.setCreateTime(new Date());
            cmAddGoodsService.save(cmAddGoodsEntity);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
            response.setEntity(entity);
        } catch (Exception ex) {
            ex.printStackTrace();
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 修改CmCreditGoods
     *
     * @param request CmCreditGoods请求
     * @return 保存CmCreditGoods响应
     */
    @SuppressWarnings("unchecked")
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    @Override
    public CmCreditGoodsResponse updateCmCreditGoodsAndExchangeCode(CmCreditGoodsRequest request) {
        CmCreditGoodsResponse response = new CmCreditGoodsResponse();
        response.setSuccessNum(0);
        CreditGoodsParamsVo paramsVo = request.getParamsVo();
        //获取商品参数
        CmCreditGoodsEntity entity = request.getEntity();
        //获取兑换码参数集合
        List<CmExchangeCodeEntity> exchangeCodeEntityListTemp = request.getExchangeCodeEntityList();
        List<CmExchangeCodeEntity> exchangeCodeEntityList = new ArrayList<>();
        if (null != exchangeCodeEntityListTemp) {
            CmExchangeCodeEntity exchangeCode = null;
            Map<String, CmExchangeCodeEntity> map = new LinkedHashMap<>();
            for (CmExchangeCodeEntity exchangeCodeEntity : exchangeCodeEntityListTemp) {
                exchangeCode = map.get(exchangeCodeEntity.getExchangeCode());
                if (exchangeCode == null) {
                    map.put(exchangeCodeEntity.getExchangeCode(), exchangeCodeEntity);
                }
            }
            exchangeCodeEntityList = mapTransitionList(map);
        }
        if (exchangeCodeEntityList.size() > 0) { //exchangeCodeEntityList start
            //获取exchangeCodeList
            List<String> exchangeCodeList = new ArrayList<>();
            for (CmExchangeCodeEntity en : exchangeCodeEntityList) {
                exchangeCodeList.add(en.getExchangeCode());
            }
            //把集合传到sql中查询，查不到则说明不重复可以保存
            Map<String, Object> params = new HashMap<>(10);
            params.put("exchangeCodeList", exchangeCodeList);
            params.put("goodsId", entity.getId());
            List<CmExchangeCodeEntity> codeList = cmExchangeCodeService.getNotRepeat(params);
            if (codeList.size() > 0) {//codeList.size()>0说明数据库中有重复数据
                //迭代查询出哪些是重复数据，用于前台提示重复
                for (CmExchangeCodeEntity codeEntity : codeList) {
                    //重复提示
                    response.setSuccessNum(0);
                    response.setFailedNum(codeList.size());
                    CmCreditGoodsResponse.ConsultantBatchResult result = new CmCreditGoodsResponse.ConsultantBatchResult();
                    result.setName(codeEntity.getGoodId() + "");//商品编号
                    result.setCode(codeEntity.getExchangeCode());//兑换码
                    result.setMsg("兑换码重复");
                    response.addBatchResult(result);
                }

            } else {
                if (CollectionUtils.isNotEmpty(exchangeCodeEntityList)) {
                    //保存批次
                    CmExchangeCodeBatchEntity codeBatch = new CmExchangeCodeBatchEntity();
                    codeBatch.setGoodId(entity.getId());
                    codeBatch.setFileName(entity.getLatestBatchName());
                    codeBatch.setCreaterId(paramsVo.getUserId());
                    codeBatch.setCreaterName(paramsVo.getUserName());
                    codeBatch.setCreateTime(new Date());
                    codeBatch.setIsDeleted(0);
                    Integer batchId = cmExchangeCodeBatchService.save(codeBatch);
                    //新增兑换码
                    for (CmExchangeCodeEntity exchangeCodeEntity : exchangeCodeEntityList) {
                        exchangeCodeEntity.setBatchId(batchId);
                        exchangeCodeEntity.setGoodId(entity.getId());//商品id
                        cmExchangeCodeService.save(exchangeCodeEntity);
                        response.incSuccessNum();
                    }
                }
            }

            //补货记录
            CmAddGoodsEntity cmAddGoodsEntity = new CmAddGoodsEntity();
            cmAddGoodsEntity.setGoodId(entity.getId());
            cmAddGoodsEntity.setGoodName(entity.getGoodsName());
            cmAddGoodsEntity.setOperatorName(paramsVo.getUserName());
            cmAddGoodsEntity.setOperatorId(paramsVo.getUserId());
            cmAddGoodsEntity.setAmount(response.getSuccessNum());
            cmAddGoodsEntity.setCreateTime(new Date());
            cmAddGoodsService.save(cmAddGoodsEntity);

        }//exchangeCodeEntityList end

        //获取兑换码上传成功条数，此为虚拟库存数量
        entity.setStock(entity.getStock() + response.getSuccessNum());
        //更新商品
        cmCreditGoodsService.update(entity);
        response.setEntity(entity);
        response.setResultCode(ReturnResult.SUCCESS.getResultCode());
        response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        return response;
    }

    /**
     * 通过ID获取CmCreditGoods
     *
     * @param id 唯一标识
     * @return 通过ID获取CmCreditGoods响应
     */
    @Override
    public CmCreditGoodsResponse getCmCreditGoodsById(Integer id) {
        CmCreditGoodsResponse response = new CmCreditGoodsResponse();
        try {
            CmCreditGoodsEntity entity = cmCreditGoodsService.getById(id);
            response.setEntity(entity);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    @Override
    public void updateSortList() {
        LOGGER.info("run task [updateSortList]");
        cmCreditGoodsService.updateSortList();
    }

    @Override
    public void refreshTask() {
        LOGGER.info("run task [refreshTask]");
        cmProductStatService.refreshTask();

    }

    /**
     * 以下均为自动生成
     */

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean isControlService() {
        return false;
    }

    @Override
    public boolean isLogService() {
        return false;
    }

    @Override
    public boolean isMonitorService() {
        return false;
    }

    @Override
    public Object rollback() {
        return null;
    }

    @Override
    public void commit() {
    }


    /**
     * 删除Html标签
     *
     * @param inputString
     * @return
     */
    private String htmlRemoveTag(String inputString) {
        if (inputString == null)
            return null;
        String htmlStr = inputString; // 含html标签的字符串
        String textStr = "";
        java.util.regex.Pattern p_script;
        java.util.regex.Matcher m_script;
        java.util.regex.Pattern p_style;
        java.util.regex.Matcher m_style;
        java.util.regex.Pattern p_body;
        java.util.regex.Matcher m_html;
        try {
            //定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
            String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>";
            //定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
            String regEx_style = "<[\\s]*?[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>";
            String regEx_body = "<[\\s]*?[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>";
//            String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
            p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
            m_script = p_script.matcher(htmlStr);
            htmlStr = m_script.replaceAll(""); // 过滤script标签
            p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
            m_style = p_style.matcher(htmlStr);
            htmlStr = m_style.replaceAll(""); // 过滤style标签
            p_body = Pattern.compile(regEx_body, Pattern.CASE_INSENSITIVE);
            m_html = p_body.matcher(htmlStr);
            htmlStr = m_html.replaceAll(""); // 过滤html标签
            textStr = htmlStr;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return textStr;// 返回文本字符串
    }
}
