package com.zfire.jiasm.syncdata.base;

import com.zfire.jiasm.syncdata.constant.DictTypeEnum;
import com.zfire.jiasm.syncdata.constant.RedisConstant;
import com.zfire.jiasm.syncdata.exception.RemoteServiceException;
import com.zfire.jiasm.syncdata.plus.entity.Brand;
import com.zfire.jiasm.syncdata.plus.entity.SysDict;
import com.zfire.jiasm.syncdata.plus.service.BrandService;
import com.zfire.jiasm.syncdata.plus.service.SysDictService;
import com.zfire.jiasm.syncdata.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

/**
 * 基础服务实现类
 * @author yaozx
 * @since 2023-01-01
 */
@Slf4j
@Service
public class BaseService {
    @Resource
    BrandService brandService;
    @Resource
    RedisUtil redis;
    @Resource
    SysDictService sysDictService;


    // 提取消息渠道ID 消息渠道名称
    public String getxxly(String xxly){
        String phone = "电话";
        String dictcode = "";
        if (redis.hasKey(RedisConstant.XXLY_CODE + phone)) {
            dictcode = (String) redis.get(RedisConstant.XXLY_CODE + phone);
        } else {
            SysDict sysDict =  sysDictService.lambdaQuery().
                    eq(SysDict::getDictType, DictTypeEnum.DICT_TYPE_XXQD_SOURCE.getCode())
                    .eq(SysDict::getDictValue,xxly).last("limit 1").one();
            if (sysDict != null){
                dictcode = sysDict.getDictCode();

                redis.set(RedisConstant.XXLY_CODE + phone, dictcode,RedisConstant.BRAND_CODE_TIME_LENGTH);
            }
        }

       return dictcode;
    }

    public Brand getBrand() {
        Brand brand = new Brand();
        String gree = "格力";

        if (redis.hasKey(RedisConstant.BRAND_CODE + gree)) {
            brand = (Brand) redis.get(RedisConstant.BRAND_CODE + gree);
        } else {
            brand = brandService.lambdaQuery().eq(Brand::getBrand,gree)
                    .last("limit 1")
                    .one();
            if (brand != null){
                redis.set(RedisConstant.BRAND_CODE + gree, brand,RedisConstant.BRAND_CODE_TIME_LENGTH);
            }
        }

        return brand;
    }


    public void saveToFile(String desUrl, File id){
        FileOutputStream fos = null;
        BufferedInputStream bis = null ;
        HttpURLConnection httpUrl =null;
        URL url =null;
        int BUFFER_SIZE = 1024;
        byte[] buf = new byte[BUFFER_SIZE];
        int size = -1;

        try {
            url = new URL(desUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            bis = new BufferedInputStream(httpUrl.getInputStream());
            fos = new FileOutputStream(id);
            while (true){
                size = bis.read(buf);
                if (size == -1){
                    break;
                }
                fos.write(buf,0,size);
            }
            fos.flush();
        } catch (Exception e){
            e.printStackTrace();
            throw new RemoteServiceException(e.getMessage());
        } finally {
            try{
                fos.close();
                bis.close();
                httpUrl.disconnect();
            }catch (Exception e){
                e.printStackTrace();
                throw new RemoteServiceException(e.getMessage());
            }
        }
    }


    public void initFile(File id){
        FileOutputStream fos = null;
        BufferedInputStream bis = null ;
        int BUFFER_SIZE = 1024;
        byte[] buf = new byte[BUFFER_SIZE];
        int size = -1;

        try {
            bis = new BufferedInputStream(this.getClass().getResourceAsStream("/static/bx.jpg"));
            fos = new FileOutputStream(id);
            while (true){
                size = bis.read(buf);
                if (size == -1){
                    break;
                }
                fos.write(buf,0,size);
            }
            fos.flush();
        } catch (IOException e){
        } catch (ClassCastException e){
        } finally {
            try{
                fos.close();
                bis.close();
            }catch (IOException e){
            }catch (NullPointerException e){
            }
        }
    }


    public String dateSub(Date d) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
        long localTime = d.getTime()-8*60*60*1000;
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(localTime);
        Date utcDate = new Date(calendar.getTimeInMillis());
        return sf.format(utcDate);
    }

    public String dateAdd(Date d) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
        long localTime = d.getTime()-8*60*60*1000;
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(localTime);
        Date utcDate = new Date(calendar.getTimeInMillis());
        return sf.format(utcDate);
    }

    public Date utcToDateStr(String utcTime) throws ParseException {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        TimeZone utcZone = TimeZone.getTimeZone("UTC");
        sf.setTimeZone(utcZone);
        Date date = null;
        String dateTime = "";
        try {
            date = sf.parse(utcTime);
            dateTime = sdf.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return sdf.parse(dateTime);
    }


}
