package com.yd.api.customer.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yd.api.customer.service.CustomerTrackVideoService;
import com.yd.api.customer.vo.trackvideo.AddCustomerTrackVideoRequestVO;
import com.yd.api.customer.vo.trackvideo.QueryDetailsByIdResponseVO;
import com.yd.api.customer.vo.trackvideo.QueryTrackListRequestVO;
import com.yd.api.customer.vo.trackvideo.QueryTrackListResponseVO;
import com.yd.api.result.CommonResult;
import com.yd.api.result.CommonResultResponseVO;
import com.yd.dal.entity.customer.trackvideo.AgAclCustomerBehaviorTrackVideo;
import com.yd.dal.mapper.customer.trackvideo.AgAclCustomerBehaviorTrackVideoMapper;
import com.yd.rmi.ali.oss.service.OssService;
import com.yd.util.CommonUtil;
import com.yd.util.HttpUtil;
import com.yd.util.SpringContextUtil;
import com.yd.util.config.ZHBErrorConfig;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("CustomerTrackVideoService")
public class CustomerTrackVideoServiceImpl implements CustomerTrackVideoService {
	
    @Autowired
    private OssService ossService;
    
    @Autowired
    private AgAclCustomerBehaviorTrackVideoMapper customerBehaviorTrackVideoMapper;
    
	/**
	 * rrWeb录屏数据保存与更新
	 * @param AddCustomerTrackVideoRequestVO
	 * @return CommonResultResponseVO
	 */
    @Override
    public CommonResultResponseVO rrWebInfo(AddCustomerTrackVideoRequestVO requestVO) {
        CommonResultResponseVO resp = new CommonResultResponseVO();
        CommonResult commonResult = new CommonResult();
        rrWebInfoCheck(requestVO, commonResult);
        if (!commonResult.isSuccess()){
        	resp.setCommonResult(commonResult);
            return resp;
        }
        AgAclCustomerBehaviorTrackVideo trackVideo = new AgAclCustomerBehaviorTrackVideo();
        BeanUtils.copyProperties(requestVO, trackVideo);
        try {
            // 获取文件
            String token = requestVO.getToken();
            String shortToken = token.substring(token.length() - 10);
            String prefix = "customerBehaviorTrackVideo/" + shortToken + "/";

            SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmssSSS");
            String filename = sdf.format(new Date());
            String ossKey = prefix + filename;
            // 将txt上传到oss
            String fileOssPath = ossService.putFileToOss(null, ossKey, new ByteArrayInputStream(requestVO.getData().getBytes()));

            // 保存入库
            trackVideo.setDataOssPath(fileOssPath);
            trackVideo.setCustomerIp(SpringContextUtil.getCurrentIpAddress());
            trackVideo.setIsActive(1);
            trackVideo.setCreatedAt(new Date());
            trackVideo.setCreatedBy(-1L);
            trackVideo.setUpdatedAt(new Date());
            trackVideo.setUpdatedBy(-1L);
            customerBehaviorTrackVideoMapper.insert(trackVideo);
            
            boolean boole = true;
            if (requestVO.getCustomerId() != null){
            	customerBehaviorTrackVideoMapper.updateBySerialsNo(trackVideo);
            	boole = false;
            }
            if(!CommonUtil.isNullOrBlank(trackVideo.getOrderNo()) && boole){
            	customerBehaviorTrackVideoMapper.updateBySerialsNo(trackVideo);
            }
            resp.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));
        } catch (Exception e) {
            e.printStackTrace();
            resp.setCommonResult(new CommonResult(false, ZHBErrorConfig.getErrorInfo("800001")));
        }
        return resp;
    }

	/**
	 * 可回溯录屏列表查询接口
	 * @param QueryTrackListRequestVO
	 * @return QueryTrackListResponseVO
	 */
    @Override
    public QueryTrackListResponseVO queryTrackList(QueryTrackListRequestVO requestVO) {
        QueryTrackListResponseVO resp = new QueryTrackListResponseVO();
        try {
            PageInfo<AgAclCustomerBehaviorTrackVideo> page = requestVO.getPage();

            PageHelper.startPage(page.getPageNum(), page.getPageSize(), null);

            List<AgAclCustomerBehaviorTrackVideo> dataList = customerBehaviorTrackVideoMapper.selectByRecord(requestVO);

            PageInfo<AgAclCustomerBehaviorTrackVideo> pageInfo = new PageInfo<>(dataList);

            resp.setList(pageInfo.getList());
            pageInfo.setList(null);
            resp.setPage(pageInfo);

            resp.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));
        } catch (Exception e) {
            e.printStackTrace();
            resp.setCommonResult(new CommonResult(false, ZHBErrorConfig.getErrorInfo("800001")));
        }
        return resp;
    }

	/**
	 * 根据录屏ID查询可回溯录屏明细数据接口
	 * @param id
	 * @return QueryDetailsByIdResponseVO
	 */
    @Override
    public QueryDetailsByIdResponseVO queryDetailsById(Long id) {
        QueryDetailsByIdResponseVO resp = new QueryDetailsByIdResponseVO();
        try {
        	if(id == null){
        		String[] params = {"id"};
            	resp.setCommonResult(new CommonResult(false, ZHBErrorConfig.getErrorInfo("610001", params)));
                return resp;
        	}
            AgAclCustomerBehaviorTrackVideo trackVideo = customerBehaviorTrackVideoMapper.selectByPrimaryKey(id);
            if(trackVideo != null && !CommonUtil.isNullOrBlank(trackVideo.getDataOssPath())){
            	Map<String, Object> input = HttpUtil.getInput(trackVideo.getDataOssPath());
                if (!(boolean) input.get("success")) {
                	resp.setCommonResult(new CommonResult(false, ZHBErrorConfig.getErrorInfo("800001")));
                    return resp;
                }
                StringBuffer out = new StringBuffer();
                InputStream inputStream = null;
				try {
					inputStream = (InputStream) input.get("is");
					byte[] b = new byte[4096];
					for (int n; (n = inputStream.read(b)) != -1;) {
						out.append(new String(b, 0, n));
					}
	            	trackVideo.setData(out.toString());
				} catch (IOException e) {
					e.printStackTrace();
		            resp.setCommonResult(new CommonResult(false, ZHBErrorConfig.getErrorInfo("800001")));
				} finally {
					if(inputStream != null){
						inputStream.close();
					}
		        }
            }else{
            	resp.setCommonResult(new CommonResult(false, "find {"+id+"} data is null!"));
                return resp;
            }
            resp.setTrackVideo(trackVideo);
            resp.setCommonResult(new CommonResult(true, ZHBErrorConfig.getErrorInfo("800000")));
        } catch (Exception e) {
            e.printStackTrace();
            resp.setCommonResult(new CommonResult(false, ZHBErrorConfig.getErrorInfo("800001")));
        }
        return resp;
    }

	/**
	 * rrWeb录屏数据保存与更新 校验
	 * @param CommonResult
	 * @param AddCustomerTrackVideoRequestVO
	 * @return void
	 */
    private void rrWebInfoCheck(AddCustomerTrackVideoRequestVO requestVO, CommonResult commonResult) {
      if (CommonUtil.isNullOrBlank(requestVO.getSerialsNo())){
    	  String[] params = {"serialsNo"};
          commonResult.setSuccess(false);
          commonResult.setMessage(ZHBErrorConfig.getErrorInfo("610001", params));
          return;
      }
      if (CommonUtil.isNullOrBlank(requestVO.getToken())){
    	  String[] params = {"token"};
          commonResult.setSuccess(false);
          commonResult.setMessage(ZHBErrorConfig.getErrorInfo("610001", params));
          return;
      }
      if (requestVO.getPageType() == null){
    	  String[] params = {"pageType"};
          commonResult.setSuccess(false);
          commonResult.setMessage(ZHBErrorConfig.getErrorInfo("610001", params));
          return;
      }
      if (CommonUtil.isNullOrBlank(requestVO.getPageName())){
    	  String[] params = {"pageName"};
          commonResult.setSuccess(false);
          commonResult.setMessage(ZHBErrorConfig.getErrorInfo("610001", params));
          return;
      }
      if (CommonUtil.isNullOrBlank(requestVO.getUrl())){
    	  String[] params = {"url"};
          commonResult.setSuccess(false);
          commonResult.setMessage(ZHBErrorConfig.getErrorInfo("610001", params));
          return;
      }
      if (CommonUtil.isNullOrBlank(requestVO.getData())){
    	  String[] params = {"data"};
          commonResult.setSuccess(false);
          commonResult.setMessage(ZHBErrorConfig.getErrorInfo("610001", params));
          return;
      }
      commonResult.setSuccess(true);
      commonResult.setMessage(ZHBErrorConfig.getErrorInfo("800000"));
    }
    
}
