package com.hai.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.pay.util.sdk.WXPayConstants;
import com.hai.common.utils.*;
import com.hai.config.CommonSysConst;
import com.hai.dao.HighUserEtcMapper;
import com.hai.entity.HighDiscountAgentCode;
import com.hai.entity.HighUser;
import com.hai.entity.HighUserEtc;
import com.hai.service.*;

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 javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("highTestService")
public class HighTestServiceImpl implements HighTestService {

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

    @Resource
    private HighUserService highUserService;

    @Resource
    private HighUserEtcMapper highUserEtcMapper;

    @Resource
    private HighDiscountAgentCodeService highDiscountAgentCodeService;


    @Resource
    private HighDiscountUserRelService highDiscountUserRelService;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    @Transactional(rollbackFor=Exception.class,propagation= Propagation.REQUIRES_NEW)
    public void getReadFile() throws Exception {
//        BufferedReader bufferedReader = null;
//
//        Map<String , String> mapUser = new HashMap<>();
//
//        //cookie过期时间为7天
//        int EXPIRE = 3600*24*7;
//
//        List<HighUser> highUsers = highUserService.getListUser(mapUser);
//
//        for (HighUser user: highUsers) {
//            redisUtil.set(user.getPhone(), user.getPhone(), EXPIRE);
//        }
//
//        FileReader fileReader = new FileReader("/home/project/hsg/readFile/etccq.txt");
//        if (fileReader == null) {
//            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "读取空数据");
//        }
//
//        bufferedReader = new BufferedReader(fileReader);
//        String temp = bufferedReader.readLine();
//        int i = 0;
//        while (temp != null) {
//            i++;
//            String[] arr = temp.split(";");
//
//            String phone = (String) redisUtil.get(arr[3]);
//
//            if (phone == null || highUsers.size() == 0) {
//                HighUser user = new HighUser();
//
//                user.setStatus(1);
//                user.setInfoCompleteStatus(1);
//                user.setGold(0);
//                user.setRegTime(new Date());
//                user.setName(arr[2]);
//                user.setPhone(arr[3]);
//                user.setExt4("1");
//
//                highUserService.insertUser(user);
//
//                HighUserEtc userEtc = new HighUserEtc();
//
//                userEtc.setCreateTime(new Date());
//                userEtc.setStatus(1);
//                userEtc.setUserId(user.getId());
//                userEtc.setCustomerName(arr[2]);
//                userEtc.setCustomerTel(arr[3]);
//                userEtc.setVehicleId(arr[0]);
//                userEtc.setVehiclePlate(arr[1]);
//
//                highUserEtcMapper.insert(userEtc);
//
////                Map<String , Object> map = new HashMap<>();
////                map.put("userId" , user.getId());
////                map.put("userPhone" , user.getPhone());
////                map.put("discountPackageId" , 48);
//
////                highDiscountPackageService.freeUserDiscountPackage(map);
//            }
//
//            temp = bufferedReader.readLine();
//        }
    }

    @Override
    @Transactional(rollbackFor=Exception.class,propagation= Propagation.REQUIRES_NEW)
    public void getUserDiscount(Long id)  throws Exception{
        List<HighDiscountAgentCode> codeList = highDiscountAgentCodeService.getDiscountCodeByStatus(id , 1);
        Map<String , String> map = new HashMap<>();
        map.put("ext4" , "1");
        List<HighUser> userList = highUserService.getListUser(map);

        int num = 0;
        for (HighUser user : userList) {
            // 领取优惠券
            highDiscountUserRelService.receiveDiscount(user.getId(), codeList.get(num).getId());
            num++;
        }
    }

    @Override
    public JSONObject getMobile(String phone , Integer amount , String orderNo) throws Exception {

        String timestamp = String.valueOf(System.currentTimeMillis());

        Map<String , Object> map = new HashMap<>();
        map.put("mobile" , phone);
        map.put("amount" , amount);
        map.put("out_order_id" , orderNo);
        map.put("app_key" , CommonSysConst.getSysConfig().getCzAppKey());
        map.put("timestamp" , timestamp.substring(0,timestamp.length()-3));
        map.put("is_fast" , "1");
        map.put("notify_url" , CommonSysConst.getSysConfig().getCzNotifyUrl());

        String signStr = WxUtils.generateSignatureAppSecret(map, CommonSysConst.getSysConfig().getTelApiSecret() , WXPayConstants.SignType.MD5);

        map.put("sign" , signStr);

        return HttpsUtils.doPost(CommonSysConst.getSysConfig().getCzUrl() , map);
    }

    @Override
    public JSONObject findByLatAndLng(String lng, String lat) throws Exception {

        Map<String,Object> map = new HashMap<>();//参数
        map.put("ak", "SfrwGH7INvjPq7BwCrYrioBQZm9XXxrR");//申请百度开放平台KEY(ak)
        map.put("output", "json");// 输出Json数据
        map.put("extensions_town", "true");// 行政区划返回乡镇级数据（town），仅国内召回乡镇数据
        map.put("coordtype", "wgs84ll"); // GPS 经纬度类型
        map.put("location", lat+","+lng+"");//百度经纬度

        String url = "http://api.map.baidu.com/reverse_geocoding/v3/";

        return HttpsUtils.doGet(url , map);

    }
}
