package com.hfkj.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.common.Base64Util;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.utils.RedisUtil;
import com.hfkj.config.CommonSysConst;
import com.hfkj.dao.BsStoreCidMapper;
import com.hfkj.dao.BsStorePushRecordMapper;
import com.hfkj.entity.BsStoreCid;
import com.hfkj.entity.BsStoreCidExample;
import com.hfkj.entity.BsStorePushRecord;
import com.hfkj.entity.BsStorePushRecordExample;
import com.hfkj.service.BsStoreCidService;
import com.hfkj.tts.HWYunSisService;
import com.hfkj.unipush.UniPushService;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author sum1dream
 */
@Service("bsStoreCidService")
public class BsStoreCidServiceImpl implements BsStoreCidService {

    private static Logger log = LoggerFactory.getLogger(BsStoreCidService.class);

    @Resource
    private BsStoreCidMapper bsStoreCidMapper;

    @Resource
    private BsStorePushRecordMapper storePushRecordMapper;

    @Resource
    private RedisUtil redisUtil;

    @Override
    public void insertStoreCid(BsStoreCid storeCid) {
        bsStoreCidMapper.insert(storeCid);
    }

    @Override
    public void editStoreCid(BsStoreCid storeCid) {
        bsStoreCidMapper.updateByPrimaryKey(storeCid);
    }

    @Override
    public BsStoreCid findByMap(Map<String, Object> map) {

        BsStoreCidExample example = new BsStoreCidExample();
        BsStoreCidExample.Criteria criteria = example.createCriteria();

        if (MapUtils.getLong(map, "storeId") != null) {
            criteria.andStoreIdEqualTo(MapUtils.getLong(map, "storeId"));
        }

        if (MapUtils.getLong(map, "storeNo") != null) {
            criteria.andStoreNoEqualTo(MapUtils.getLong(map, "storeNo"));
        }

        if (StringUtils.isNotBlank(MapUtils.getString(map, "storeName"))) {
            criteria.andStoreNameLike("%"+MapUtils.getString(map, "storeName")+"%");
        }

        List<BsStoreCid> list = bsStoreCidMapper.selectByExample(example);

        if (list.size() > 0) {
            return list.get(0);
        }

        return null;
    }

    @Override
    public void storePush(JSONObject object) {

        try {

            String key = "APP_PUSH" + object.getLong("storeId");

            if (redisUtil.get(key) == null) {
                redisUtil.set(key,object.getLong("storeId"), 5);
                if (object.getBigDecimal("price") == null || object.getLong("storeId") == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
                }

                Map<String, Object> map = new HashMap<>();
                map.put("storeId", object.getLong("storeId"));
                BsStoreCid bsStoreCid = findByMap(map);

                if (bsStoreCid == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "不存在推送关系");
                }

                // 获取语音播报地址
                String auditPath = HWYunSisService.ttsCustomDemo(object);

                if (auditPath == null) {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "生成语音失败");
                }

                String taskNo = Base64Util.generateOrderNo();
                object.put("taskNo", taskNo);
                object.put("cid", bsStoreCid.getCid());
                String msg = CommonSysConst.getSysConfig().getDomainName() + auditPath + "!@#PUSH#@!" + taskNo + "!@#PUSH#@!" + "惠支付收款：" + object.getBigDecimal("price");
                object.put("body", msg);
                if (UniPushService.pushToSingleByCid(object)) {
                    BsStorePushRecord storePushRecord = new BsStorePushRecord();
                    storePushRecord.setStoreId(object.getLong("storeId"));
                    storePushRecord.setCreateTime(new Date());
                    storePushRecord.setUpdateTime(new Date());
                    storePushRecord.setStatus(2);
                    storePushRecord.setExt1(taskNo);
                    storePushRecord.setVoiceUrl(msg);
                    insertStorePushRecord(storePushRecord);
                }
            } else {
                storePush(object);
            }

        } catch (Exception e) {
            log.info("请求超时：" + e);
        }

    }



    private void getPushRecord(Long storeId) {

        Map<String, Object> map = new HashMap<>();
        map.put("storeId", storeId);
        BsStoreCid bsStoreCid = findByMap(map);

        if (bsStoreCid == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "不存在推送关系");
        }

        // 查询可推送语音

        Map<String , Object> pushMap = new HashMap<>();
        pushMap.put("storeId" , storeId);
        pushMap.put("status" , 2);
        BsStorePushRecord storePushRecord =  findPushRecordByMap(pushMap);

        if (storePushRecord != null) {
            JSONObject object = new JSONObject();
            object.put("cid", bsStoreCid.getCid());
            object.put("storeId", bsStoreCid.getCid());
            object.put("body", storePushRecord.getVoiceUrl());
            UniPushService.pushToSingleByCid(object);
        }

    }

    @Override
    public void voiceSucceed(Long storeId , String taskNo) {
        Map<String , Object> pushMap = new HashMap<>();
        pushMap.put("storeId" , storeId);
        pushMap.put("ext1" , storeId);
        pushMap.put("status" , 2);
        BsStorePushRecord storePushRecord =  findPushRecordByMap(pushMap);

        if (storePushRecord != null) {
            storePushRecord.setStatus(1);
            storePushRecordMapper.updateByPrimaryKey(storePushRecord);

            redisUtil.del("APP_PUSH" + storePushRecord.getStoreId());
        }

        getPushRecord(storeId);
    }

    @Override
    public void insertStorePushRecord(BsStorePushRecord storePushRecord) {
        storePushRecordMapper.insert(storePushRecord);
    }

    @Override
    public void editStorePushRecord(BsStorePushRecord storePushRecord) {
        storePushRecordMapper.updateByPrimaryKey(storePushRecord);
    }

    @Override
    public BsStorePushRecord findPushRecordByMap(Map<String, Object> map) {
        BsStorePushRecordExample example = new BsStorePushRecordExample();
        BsStorePushRecordExample.Criteria criteria = example.createCriteria();

        if (MapUtils.getLong(map, "storeId") != null) {
            criteria.andStoreIdEqualTo(MapUtils.getLong(map, "storeId"));
        }
        if (MapUtils.getInteger(map, "status") != null) {
            criteria.andStatusEqualTo(MapUtils.getInteger(map, "status"));
        }

        List<BsStorePushRecord> list = storePushRecordMapper.selectByExample(example);

        if (list.size() > 0) {
            return list.get(0);
        }

        return null;
    }

    @Override
    public List<BsStorePushRecord> getList(Map<String, Object> map) {

        BsStorePushRecordExample example = new BsStorePushRecordExample();
        BsStorePushRecordExample.Criteria criteria = example.createCriteria();

        if (MapUtils.getLong(map, "storeId") != null) {
            criteria.andStoreIdEqualTo(MapUtils.getLong(map, "storeId"));
        }
        if (MapUtils.getInteger(map, "status") != null) {
            criteria.andStatusEqualTo(MapUtils.getInteger(map, "status"));
        }

        return storePushRecordMapper.selectByExample(example);
    }
}
