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).getfRowVersion();
        }
        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.setfRegCode(jsonObject.getString("regCode"));
                tLpgGasBottleFiles.setfEquNo(jsonObject.getString("equNo"));
                tLpgGasBottleFiles.setfEquType(jsonObject.getString("equType"));
                tLpgGasBottleFiles.setfMedium(jsonObject.getString("medium"));
                tLpgGasBottleFiles.setfMakeDate(jsonObject.getDate("makeDate"));
                tLpgGasBottleFiles.setfMakeInfo(jsonObject.getString("makeInfo"));
                tLpgGasBottleFiles.setfSelfId(jsonObject.getString("selfId"));
                String pressure = jsonObject.getString("pressure");
                if (pressure != null && !pressure.isEmpty()) {
                    tLpgGasBottleFiles.setfPressure(new BigDecimal(pressure));
                } else {
                    tLpgGasBottleFiles.setfPressure(new BigDecimal(0));
                }
                String volume = jsonObject.getString("volume");
                if (volume != null && !volume.isEmpty()) {
                    tLpgGasBottleFiles.setfVolume(new BigDecimal(volume));
                } else {
                    tLpgGasBottleFiles.setfVolume(new BigDecimal(0));
                }
                tLpgGasBottleFiles.setfAppId(jsonObject.getString("appId"));
                tLpgGasBottleFiles.setfQRcode(jsonObject.getString("qRcode"));
                tLpgGasBottleFiles.setfBuildUser(jsonObject.getString("buildUser"));
                tLpgGasBottleFiles.setfAddTime(jsonObject.getDate("addtime"));
                tLpgGasBottleFiles.setfOptName(jsonObject.getString("optName"));
                tLpgGasBottleFiles.setfUpTime(jsonObject.getDate("uptime"));
                tLpgGasBottleFiles.setfState(jsonObject.getString("state"));
                tLpgGasBottleFiles.setfUpOptName(jsonObject.getString("upOptName"));
                tLpgGasBottleFiles.setfPChkDate(jsonObject.getDate("pChkDate"));
                tLpgGasBottleFiles.setfNChkDate(jsonObject.getDate("nChkDate"));
                tLpgGasBottleFiles.setfProductDate(jsonObject.getDate("productDate"));
                tLpgGasBottleFiles.setfDiscardDate(jsonObject.getDate("discardDate"));
                tLpgGasBottleFiles.setfSafeJudgeDate(jsonObject.getDate("safeJudgeDate"));
                String gpressure = jsonObject.getString("gpressure");
                if (gpressure != null && !gpressure.isEmpty()) {
                    tLpgGasBottleFiles.setfGPressure(new BigDecimal(gpressure));
                } else {
                    tLpgGasBottleFiles.setfGPressure(new BigDecimal(0));
                }
                String wpressure = jsonObject.getString("wpressure");
                if (wpressure != null && !wpressure.isEmpty()) {
                    tLpgGasBottleFiles.setfWPressure(new BigDecimal(wpressure));
                } else {
                    tLpgGasBottleFiles.setfWPressure(new BigDecimal(0));
                }
                String selfWeight = jsonObject.getString("selfWeight");
                if (selfWeight != null && !selfWeight.isEmpty()) {
                    tLpgGasBottleFiles.setfSelfWeight(new BigDecimal(selfWeight));
                } else {
                    tLpgGasBottleFiles.setfSelfWeight(new BigDecimal(0));
                }
                String thickness = jsonObject.getString("thickness");
                if (thickness != null && !thickness.isEmpty()) {
                    tLpgGasBottleFiles.setfThickness(new BigDecimal(thickness));
                } else {
                    tLpgGasBottleFiles.setfThickness(new BigDecimal(0));
                }
                tLpgGasBottleFiles.setfPermitNo(jsonObject.getString("permitNo"));
                tLpgGasBottleFiles.setfValveName(jsonObject.getString("valveTypeName"));
                tLpgGasBottleFiles.setfPayImage(jsonObject.getString("payImage"));
                tLpgGasBottleFiles.setfBatchImage(jsonObject.getString("batchImage"));
                tLpgGasBottleFiles.setfDeviceImage(jsonObject.getString("deviceImage"));
                tLpgGasBottleFiles.setfCheckImage(jsonObject.getString("checkImage"));
                tLpgGasBottleFiles.setfEquNoImage(jsonObject.getString("equNoImage"));
                tLpgGasBottleFiles.setfSelfIdImage(jsonObject.getString("selfIdImage"));
                tLpgGasBottleFiles.setfBotImage(jsonObject.getString("botImage"));
                tLpgGasBottleFiles.setfBotSpecName(jsonObject.getString("botSpecName"));
                tLpgGasBottleFiles.setfBottleType(jsonObject.getString("bottleType"));
                String inspectedTimes = jsonObject.getString("inspectedTimes");
                if (inspectedTimes != null && !inspectedTimes.isEmpty()) {
                    tLpgGasBottleFiles.setfInspectedTimes(Long.valueOf(inspectedTimes));
                } else {
                    tLpgGasBottleFiles.setfInspectedTimes(0L);
                }
                tLpgGasBottleFiles.setfIsSpecialized(jsonObject.getString("isSpecialized"));
                tLpgGasBottleFiles.setfValveManuFacturer(jsonObject.getString("valveManufacturer"));
                tLpgGasBottleFiles.setfInspectionLabel(jsonObject.getString("inspectionLabel"));
                tLpgGasBottleFiles.setfThirdPartyLabel(jsonObject.getString("thirdPartyLabel"));
                tLpgGasBottleFiles.setfHoleCode(jsonObject.getString("holeCode"));
                tLpgGasBottleFiles.setfBottleStorageType(jsonObject.getString("bottleStorageType"));
                tLpgGasBottleFiles.setfRowVersion(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.setfGzId(jsonObject.getLong("gzId"));
                tLpgAirChargeFile.setfStationName(jsonObject.getString("stationName"));
                tLpgAirChargeFile.setfBarCode(jsonObject.getString("barCode"));
                tLpgAirChargeFile.setfVaseCode(jsonObject.getString("vaseCode"));
                tLpgAirChargeFile.setfScaleNum(jsonObject.getString("scaleNum"));
                tLpgAirChargeFile.setfFillStatrTime(jsonObject.getString("fillStatrTime"));
                tLpgAirChargeFile.setfFillEndTime(jsonObject.getString("fillEndTime"));
                tLpgAirChargeFile.setfSetWeight(jsonObject.getString("setWeight"));
                tLpgAirChargeFile.setfWtNet(jsonObject.getString("wtNet"));
                tLpgAirChargeFile.setfSetBottleWeight(jsonObject.getString("setBottleWeight"));
                tLpgAirChargeFile.setfBottleWeight(jsonObject.getString("bottleWeight"));
                tLpgAirChargeFile.setfWtGross(jsonObject.getString("wtGross"));
                tLpgAirChargeFile.setfOprateName(jsonObject.getString("oprateName"));
                tLpgAirChargeFilesService.insertTLpgAirChargeFiles(tLpgAirChargeFile);
            }
            if(data.size()==100){
                this.getFillingData();
            }
            //List<TLpgGasBottleFiles> lpgGasBottleFilesList = new ArrayList<>();
        }
    }
}
