package com.diaoyun.zion.chinafrica.service.impl;

import com.diaoyun.zion.chinafrica.dao.TbCfCartRecordRDao;
import com.diaoyun.zion.chinafrica.dao.TbCfExpTemKeywordDao;
import com.diaoyun.zion.chinafrica.dao.TbCfItemDetailDao;
import com.diaoyun.zion.chinafrica.entity.TbCfCartRecordREntity;
import com.diaoyun.zion.chinafrica.entity.TbCfExpressTemplateEntity;
import com.diaoyun.zion.chinafrica.entity.TbCfItemDetailEntity;
import com.diaoyun.zion.chinafrica.service.TbCfCartRecordRService;
import com.diaoyun.zion.chinafrica.service.TbCfItemDetailService;
import com.diaoyun.zion.chinafrica.vo.TbCfCartItemDetailVo;
import com.diaoyun.zion.chinafrica.vo.TbCfItemDetailVo;
import com.diaoyun.zion.chinafrica.vo.TbCfUserInfoVo;
import com.diaoyun.zion.master.base.Result;
import com.diaoyun.zion.master.base.StateConstant;
import com.diaoyun.zion.master.common.TokenManager;
import com.diaoyun.zion.master.enums.ResultCodeEnum;
import com.diaoyun.zion.master.security.JwtTokenProvider;
import com.diaoyun.zion.master.util.IdUtil;
import com.diaoyun.zion.master.util.ValidateUtils;
import com.diaoyun.zion.master.util.WordposHelper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

/**
 * 商品详情Service实现类
 *
 * @author G
 * @date 2019-08-16 15:51:16
 */
@Service("tbCfItemDetailService")
public class TbCfItemDetailServiceImpl implements TbCfItemDetailService {
    @Autowired
    private TbCfItemDetailDao tbCfItemDetailDao;

    @Autowired
    private TbCfCartRecordRDao tbCfCartRecordRDao;
    @Autowired
    private TbCfExpTemKeywordDao tbCfExpTemKeywordDao;


    @Resource(name="redisTokenManager")
    private TokenManager tokenManager;

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @Autowired
    private HttpServletRequest request; //自动注入request


    @Override
    public TbCfItemDetailEntity queryObject(String itemId) {
        return tbCfItemDetailDao.queryObject(itemId);
    }

    @Override
    public List<TbCfItemDetailEntity> queryList(Map<String, Object> map) {
        return tbCfItemDetailDao.queryList(map);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return tbCfItemDetailDao.queryTotal(map);
    }

    @Override
    public int save(TbCfItemDetailEntity tbCfItemDetail) {
        tbCfItemDetail.setItemId(IdUtil.createIdbyUUID());
        return tbCfItemDetailDao.save(tbCfItemDetail);
    }

    @Override
    public int update(TbCfItemDetailEntity tbCfItemDetail) {
        return tbCfItemDetailDao.update(tbCfItemDetail);
    }

    @Override
    public int delete(String itemId) {
        return tbCfItemDetailDao.delete(itemId);
    }

    @Override
    public int deleteBatch(String[] itemIds) {
        return tbCfItemDetailDao.deleteBatch(itemIds);
    }

    @Override
    public Result addToCart(TbCfItemDetailVo tbCfItemDetailVo) throws InterruptedException, ExecutionException, TimeoutException {
        String token = jwtTokenProvider.resolveToken(request);
        TbCfUserInfoVo tbCfUserInfoVo = tokenManager.validate(token);
        //填充新商品必要信息
        TbCfCartRecordREntity tbCfCartRecord = tbCfCartRecordRDao.querySkuAndUrl(tbCfItemDetailVo.getItemSku(),tbCfItemDetailVo.getSourceItemId());
        if (tbCfCartRecord!=null) {
            tbCfItemDetailVo.setItemId(tbCfCartRecord.getItemId());
            tbCfItemDetailVo.setItemNum(tbCfCartRecord.getItemNum() + tbCfItemDetailVo.getItemNum());
            tbCfItemDetailVo.setCreateTime(new Date());
        }else{
            tbCfItemDetailVo.setItemId(IdUtil.createIdbyUUID());
            tbCfItemDetailVo.setCreateTime(new Date());
        }
        //为商品分类,后面计算运费
        TbCfExpressTemplateEntity expressTemplate = recognizeItemCategory(tbCfItemDetailVo.getItemTitle());
        tbCfItemDetailVo.setItemCategory(expressTemplate.getTemplateId());
        //加入商品详情
        TbCfItemDetailEntity tbCfItemDetail= new TbCfItemDetailEntity();
        BeanUtils.copyProperties(tbCfItemDetailVo,tbCfItemDetail);
        //将商品加入购物车表
        TbCfCartRecordREntity tbCfCartRecordREntity1 = tbCfCartRecordRDao.queryByItemId(tbCfItemDetailVo.getItemId());
        if(tbCfCartRecordREntity1 == null ){
            tbCfItemDetailDao.save(tbCfItemDetail);
            TbCfCartRecordREntity tbCfCartRecordREntity = new TbCfCartRecordREntity();
            tbCfCartRecordREntity.setCartRecordId(IdUtil.createIdbyUUID());
            tbCfCartRecordREntity.setCheckFlag(StateConstant.VALID);
            tbCfCartRecordREntity.setEnableFlag(StateConstant.VALID);
            tbCfCartRecordREntity.setItemId(tbCfItemDetailVo.getItemId());
            tbCfCartRecordREntity.setUserId(tbCfUserInfoVo.getUserId());
            tbCfCartRecordREntity.setCreateTime(new Date());
            tbCfCartRecordREntity.setItemNum(tbCfItemDetailVo.getItemNum());
            tbCfCartRecordREntity.setItemSku(tbCfItemDetailVo.getItemSku());
            tbCfCartRecordREntity.setSourceItemId(tbCfItemDetailVo.getSourceItemId());
            tbCfCartRecordRDao.save(tbCfCartRecordREntity);
        } else{
            tbCfItemDetailDao.update(tbCfItemDetail);
            TbCfCartRecordREntity tbCfCartRecordREntity = new TbCfCartRecordREntity();
            tbCfCartRecordREntity.setCartRecordId(tbCfCartRecordREntity1.getCartRecordId());
            tbCfCartRecordREntity.setItemId(tbCfItemDetailVo.getItemId());
            tbCfCartRecordREntity.setCheckFlag(StateConstant.VALID);
            tbCfCartRecordREntity.setEnableFlag(StateConstant.VALID);
            tbCfCartRecordREntity.setUserId(tbCfUserInfoVo.getUserId());
            tbCfCartRecordREntity.setCreateTime(new Date());
            tbCfCartRecordREntity.setItemNum(tbCfItemDetailVo.getItemNum());
            tbCfCartRecordRDao.update(tbCfCartRecordREntity);
        }
        return new Result(ResultCodeEnum.SUCCESS.getDesc());
    }

    @Override
    public Result changeItemNum(String itemId, int itemNum) {
        TbCfItemDetailEntity tbCfItemDetailEntity = new TbCfItemDetailEntity();
        tbCfItemDetailEntity.setItemId(itemId);
        tbCfItemDetailEntity.setItemNum(itemNum);
        int res=tbCfItemDetailDao.update(tbCfItemDetailEntity);
        if(res>0) {
            return new Result(ResultCodeEnum.SUCCESS.getDesc());
        } else {
            return new Result().setCode(ResultCodeEnum.ERROR.getCode()).setMessage("fail to edit");
        }

    }

    @Override
    public List<TbCfCartItemDetailVo> getCartItemList() {
        //获取用户
        String token = jwtTokenProvider.resolveToken(request);
        TbCfUserInfoVo tbCfUserInfoVo = tokenManager.validate(token);
        String userId=tbCfUserInfoVo.getUserId();
        return tbCfItemDetailDao.getCartItemList(userId,null);
    }

    @Override
    public Result changeItemState(String cartRecordId, Integer checkFlag) {
        Result result=new Result(ResultCodeEnum.SUCCESS.getDesc());
        int res=tbCfItemDetailDao.changeItemState(cartRecordId,checkFlag);
        if(res<1) {
            result.setCode(ResultCodeEnum.ERROR.getCode()).setMessage("fail to edit");
        }
        return result;
    }

    /**
     * 获取运费模板（包含分类）
     *
     * @param itemTitle
     * @return
     */
    private TbCfExpressTemplateEntity recognizeItemCategory(String itemTitle) throws ExecutionException, InterruptedException, TimeoutException {
        Map<String, Object> wordResult = separateText(itemTitle);
        //pos_code 16为名词，用名词去匹配; 23非汉字串
        JSONArray baseTokens = (JSONArray) wordResult.get("base_tokens");
        List<String> keywordList = new ArrayList<>();
        for (int i = 0; i < baseTokens.size(); i++) {
            JSONObject jsonObject = (JSONObject) baseTokens.get(i);
            if (16 == (Integer) jsonObject.get("pos_code")) {
                keywordList.add((String) jsonObject.get("word"));
            }
            if (23 == (Integer) jsonObject.get("pos_code")) {
                keywordList.add((String) jsonObject.get("word"));
            }
        }
        //总的可能适用的运费模板
        Set<TbCfExpressTemplateEntity> totalTemplateSet = new HashSet<>();
        if (!keywordList.isEmpty()) {
            for (String keyword : keywordList) {
                //根据keyword获取运费模板
                List<TbCfExpressTemplateEntity> tbCfExpressTemplateList = tbCfExpTemKeywordDao.getTemplateByKeyword(keyword);
                totalTemplateSet.addAll(tbCfExpressTemplateList);
                //TODO 后续优化
                if(ValidateUtils.isContainChinese(keyword)) {
                    if ("0".equals(tbCfExpressTemplateList.size())) {
                        String[] split = keyword.split("");
                        for (int i = 0; i < split.length; i++) {
                            if(i+1<=split.length){
                                List<TbCfExpressTemplateEntity> tbCfExpressTemplateLists = tbCfExpTemKeywordDao.getTemplateByKeyword(split[i]+split[i+1]);
                                totalTemplateSet.addAll(tbCfExpressTemplateLists);
                            }
                        }
                    }
                }
            }
        }
        //没有的话就设置 其他
        if (totalTemplateSet.isEmpty()) {
            //根据keyword获取运费模板
            List<TbCfExpressTemplateEntity> tbCfExpressTemplateList = tbCfExpTemKeywordDao.getTemplateByKeyword("其他");
            totalTemplateSet.addAll(tbCfExpressTemplateList);
        }
        //取第一个运费
        Iterator<TbCfExpressTemplateEntity> iterator = totalTemplateSet.iterator();
        TbCfExpressTemplateEntity useTemplate = iterator.next();
        return useTemplate;
    }

    /**
     * 分词
     * @param text
     * @return
     */
    private Map<String, Object> separateText(String text) throws ExecutionException, InterruptedException, TimeoutException {
        List<Map<String, Object>> futureList = new ArrayList<>();
        Map<String, Object> titleMap = new HashMap<>();
        titleMap.put("text", text);
        WordposHelper.separeteText(futureList, titleMap, text);
        WordposHelper.waitForResult(futureList);
        return titleMap;
    }
}
