package com.zehong.web.controller.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.zehong.common.core.domain.entity.SysUser;
import com.zehong.common.core.page.PageDomain;
import com.zehong.common.core.page.TableSupport;
import com.zehong.common.core.redis.RedisCache;
import com.zehong.common.exception.CustomException;
import com.zehong.common.utils.DateUtils;
import com.zehong.common.utils.GovernmentDataCopyUtil;
import com.zehong.common.utils.StringUtils;
import com.zehong.common.utils.http.HttpClientUtils;
import com.zehong.common.utils.sql.SqlUtil;
import com.zehong.system.domain.TLpgAirChargeFiles;
import com.zehong.system.domain.TLpgGasBottleFiles;
import com.zehong.system.domain.TProAppInforBrowse;
import com.zehong.system.domain.TUserLocation;
import com.zehong.system.domain.vo.ProAppInforBrowseVo;
import com.zehong.system.service.ISysUserService;
import com.zehong.system.service.ITLpgAirChargeFilesService;
import com.zehong.system.service.ITLpgGasBottleFilesService;
import com.zehong.system.service.ITUserLocationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Component("timeTasks")
public class TimeTasksController {
    @Value("${wjyhq.apiUrl}")
    private String apiUrl;

    @Value("${wjyhq.authCode}")
    private String authCode;

    @Value("${wjyhq.accessKey}")
    private String accessKey;

    @Value("${wjyhq.secretKey}")
    private String secretKey;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    ITUserLocationService tUserLocationService;
    @Autowired
    private ITLpgGasBottleFilesService tLpgGasBottleFilesService;
    @Autowired
    private ITLpgAirChargeFilesService tLpgAirChargeFilesService;

    /**
     * 获取token
     * @return token
     * @throws Exception
     */
    public String getToken()throws Exception{
        String token = redisCache.getCacheObject("yhqToken");
        if(StringUtils.isEmpty(token)){
            token = getNewToken();
        }
        return token;
    }

    /**
     * 刷新token
     * @return token
     * @throws Exception
     */
    public String getNewToken()throws Exception{
        JSONObject param = new JSONObject();
        param.put("authCode", authCode);
        param.put("accessKey",accessKey);
        param.put("secretKey",secretKey);
        String result = HttpClientUtils.doPost(apiUrl+"/SyncDataApi/CreateToken",param.toJSONString(),null);
        if(StringUtils.isEmpty(result)) throw new CustomException("获取液化气token接口失败!");
        JSONObject resultJson = JSONObject.parseObject(result);
        redisCache.setCacheObject("yhqToken", resultJson.getJSONObject("result").getString("token"));
        String dateString = resultJson.getJSONObject("result").getString("expdate");
        Date date = DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", dateString);
        redisCache.setCacheObjectExpireAt("yhqToken", date);
        return  resultJson.getJSONObject("result").getString("token");
    }

    /**
     * 获取钢瓶档案
     * @return token
     * @throws Exception
     */
    public void getArchivesList()throws Exception{
        String token = getToken();
        JSONObject param = new JSONObject();
        param.put("maxReturnNum",100);

        PageHelper.startPage(1, 1, "f_gas_bottle_files_id desc");
        List<TLpgGasBottleFiles> selectUpTime = tLpgGasBottleFilesService.selectTLpgGasBottleFilesList(new TLpgGasBottleFiles());
        String lastRowVersion = "0";
        if(selectUpTime!=null && selectUpTime.size()>0){
            lastRowVersion = selectUpTime.get(0).getRowVersion();
        }
        param.put("lastUpTime","");
        param.put("state",0);
        param.put("lastRowVersion",lastRowVersion);
        Map<String,Object> head = new HashMap<>();
        head.put("authorization","Bearer "+token);
        String result = HttpClientUtils.doPost(apiUrl+"/SyncDataApi/ArchivesList",param.toJSONString(),head);
        if(StringUtils.isEmpty(result)) throw new CustomException("获取钢瓶档案接口失败!");
        JSONObject json = JSONObject.parseObject(result);
        //结果入库
        if(null != json && "1".equals(json.getString("code")) && null != json.getJSONArray("result")){
            JSONArray data = json.getJSONArray("result");
            //List<TLpgGasBottleFiles> lpgGasBottleFilesList = new ArrayList<>();
            for(int i = 0; i < data.size(); i++){
                JSONObject jsonObject = data.getJSONObject(i);
                TLpgGasBottleFiles tLpgGasBottleFiles = new TLpgGasBottleFiles();
                tLpgGasBottleFiles.setRegCode(jsonObject.getString("regCode"));
                tLpgGasBottleFiles.setEquNo(jsonObject.getString("equNo"));
                tLpgGasBottleFiles.setEquType(jsonObject.getString("equType"));
                tLpgGasBottleFiles.setMedium(jsonObject.getString("medium"));
                tLpgGasBottleFiles.setMakeDate(jsonObject.getDate("makeDate"));
                tLpgGasBottleFiles.setMakeInfo(jsonObject.getString("makeInfo"));
                tLpgGasBottleFiles.setSelfId(jsonObject.getString("selfId"));
                String pressure = jsonObject.getString("pressure");
                if (pressure != null && !pressure.isEmpty()) {
                    tLpgGasBottleFiles.setPressure(new BigDecimal(pressure));
                } else {
                    tLpgGasBottleFiles.setPressure(new BigDecimal(0));
                }
                String volume = jsonObject.getString("volume");
                if (volume != null && !volume.isEmpty()) {
                    tLpgGasBottleFiles.setVolume(new BigDecimal(volume));
                } else {
                    tLpgGasBottleFiles.setVolume(new BigDecimal(0));
                }
                tLpgGasBottleFiles.setAppId(jsonObject.getString("appId"));
                tLpgGasBottleFiles.setQrcode(jsonObject.getString("qRcode"));
                tLpgGasBottleFiles.setBuildUser(jsonObject.getString("buildUser"));
                tLpgGasBottleFiles.setAddTime(jsonObject.getDate("addtime"));
                tLpgGasBottleFiles.setOptName(jsonObject.getString("optName"));
                tLpgGasBottleFiles.setUpTime(jsonObject.getDate("uptime"));
                tLpgGasBottleFiles.setState(jsonObject.getString("state"));
                tLpgGasBottleFiles.setUpOptName(jsonObject.getString("upOptName"));
                tLpgGasBottleFiles.setPchkDate(jsonObject.getDate("pChkDate"));
                tLpgGasBottleFiles.setNchkDate(jsonObject.getDate("nChkDate"));
                tLpgGasBottleFiles.setProductDate(jsonObject.getDate("productDate"));
                tLpgGasBottleFiles.setDiscardDate(jsonObject.getDate("discardDate"));
                tLpgGasBottleFiles.setSafeJudgeDate(jsonObject.getDate("safeJudgeDate"));
                String gpressure = jsonObject.getString("gpressure");
                if (gpressure != null && !gpressure.isEmpty()) {
                    tLpgGasBottleFiles.setGpressure(new BigDecimal(gpressure));
                } else {
                    tLpgGasBottleFiles.setGpressure(new BigDecimal(0));
                }
                String wpressure = jsonObject.getString("wpressure");
                if (wpressure != null && !wpressure.isEmpty()) {
                    tLpgGasBottleFiles.setWpressure(new BigDecimal(wpressure));
                } else {
                    tLpgGasBottleFiles.setWpressure(new BigDecimal(0));
                }
                String selfWeight = jsonObject.getString("selfWeight");
                if (selfWeight != null && !selfWeight.isEmpty()) {
                    tLpgGasBottleFiles.setSelfWeight(new BigDecimal(selfWeight));
                } else {
                    tLpgGasBottleFiles.setSelfWeight(new BigDecimal(0));
                }
                String thickness = jsonObject.getString("thickness");
                if (thickness != null && !thickness.isEmpty()) {
                    tLpgGasBottleFiles.setThickness(new BigDecimal(thickness));
                } else {
                    tLpgGasBottleFiles.setThickness(new BigDecimal(0));
                }
                tLpgGasBottleFiles.setPermitNo(jsonObject.getString("permitNo"));
                tLpgGasBottleFiles.setValveName(jsonObject.getString("valveTypeName"));
                tLpgGasBottleFiles.setPayImage(jsonObject.getString("payImage"));
                tLpgGasBottleFiles.setBatchImage(jsonObject.getString("batchImage"));
                tLpgGasBottleFiles.setDeviceImage(jsonObject.getString("deviceImage"));
                tLpgGasBottleFiles.setCheckImage(jsonObject.getString("checkImage"));
                tLpgGasBottleFiles.setEquNoImage(jsonObject.getString("equNoImage"));
                tLpgGasBottleFiles.setSelfIdImage(jsonObject.getString("selfIdImage"));
                tLpgGasBottleFiles.setBotImage(jsonObject.getString("botImage"));
                tLpgGasBottleFiles.setBatchImage(jsonObject.getString("botSpecName"));
                tLpgGasBottleFiles.setBottleType(jsonObject.getString("bottleType"));
                String inspectedTimes = jsonObject.getString("inspectedTimes");
                if (inspectedTimes != null && !inspectedTimes.isEmpty()) {
                    tLpgGasBottleFiles.setInspectedTimes(Long.valueOf(inspectedTimes));
                } else {
                    tLpgGasBottleFiles.setInspectedTimes(0L);
                }
                tLpgGasBottleFiles.setIsSpecialized(jsonObject.getString("isSpecialized"));
                tLpgGasBottleFiles.setValveManuFacturer(jsonObject.getString("valveManufacturer"));
                tLpgGasBottleFiles.setInspectionLabel(jsonObject.getString("inspectionLabel"));
                tLpgGasBottleFiles.setThirdPartyLabel(jsonObject.getString("thirdPartyLabel"));
                tLpgGasBottleFiles.setHoleCode(jsonObject.getString("holeCode"));
                tLpgGasBottleFiles.setBottleStorageType(jsonObject.getString("bottleStorageType"));
                tLpgGasBottleFiles.setRowVersion(jsonObject.getString("rowVersion"));
                tLpgGasBottleFilesService.insertTLpgGasBottleFiles(tLpgGasBottleFiles);
            }
            if(data.size()==100){
                this.getArchivesList();
            }
        }
    }

    /**
     * 获取充装记录
     * @return token
     * @throws Exception
     */
    public void getFillingData()throws Exception{
        String token = getToken();
        JSONObject param = new JSONObject();
        //Integer pageIndex = 1;
        //Integer startNum = 0;
        Integer tLpgAirChargeFilesTotal = tLpgAirChargeFilesService.selectTLpgAirChargeFilesTotal();
        Integer pageIndex = tLpgAirChargeFilesTotal / 100 + 1;
        Integer startNum = tLpgAirChargeFilesTotal%100;
        param.put("pageIndex",pageIndex);
        param.put("pageSize",100);
        Map<String,Object> head = new HashMap<>();
        head.put("authorization","Bearer "+token);
        String result = HttpClientUtils.doPost(apiUrl+"/SyncDataApi/FillingData",param.toJSONString(),head);
        if(StringUtils.isEmpty(result)) throw new CustomException("获取充装记录接口失败!");
        JSONObject json = JSONObject.parseObject(result);
        //结果入库
        if(null != json && "1".equals(json.getString("code")) && null != json.getJSONArray("result")){
            JSONArray data = json.getJSONArray("result");
            for(int i = startNum; i < data.size(); i++){
                JSONObject jsonObject = data.getJSONObject(i);
                TLpgAirChargeFiles tLpgAirChargeFile = new TLpgAirChargeFiles();
                tLpgAirChargeFile.setGzId(jsonObject.getLong("gzId"));
                tLpgAirChargeFile.setStationName(jsonObject.getString("stationName"));
                tLpgAirChargeFile.setBarCode(jsonObject.getString("barCode"));
                tLpgAirChargeFile.setVaseCode(jsonObject.getString("vaseCode"));
                tLpgAirChargeFile.setScaleNum(jsonObject.getString("scaleNum"));
                tLpgAirChargeFile.setFillStatrTime(jsonObject.getString("fillStatrTime"));
                tLpgAirChargeFile.setFillEndTime(jsonObject.getString("fillEndTime"));
                tLpgAirChargeFile.setSetWeight(jsonObject.getString("setWeight"));
                tLpgAirChargeFile.setWtNet(jsonObject.getString("wtNet"));
                tLpgAirChargeFile.setSetBottleWeight(jsonObject.getString("setBottleWeight"));
                tLpgAirChargeFile.setBottleWeight(jsonObject.getString("bottleWeight"));
                tLpgAirChargeFile.setWtGross(jsonObject.getString("wtGross"));
                tLpgAirChargeFile.setOprateName(jsonObject.getString("oprateName"));
                tLpgAirChargeFilesService.insertTLpgAirChargeFiles(tLpgAirChargeFile);
            }
            if(data.size()==100){
                this.getFillingData();
            }
            //List<TLpgGasBottleFiles> lpgGasBottleFilesList = new ArrayList<>();
        }
    }
}
