/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import dm.jdbc.util.StringUtil;
import io.renren.entity.CarEntity;
import io.renren.entity.CarRecordEntity;
import io.renren.service.AutoTaskService;
import io.renren.service.CarService;
import io.renren.util.HttpUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class AutoTaskServiceImpl  implements AutoTaskService {

	@Autowired
	private CarService carService;

	@Value("${uspace.url}")
	private String uspaceUrl;
	@Value("${uspace.appId}")
	private String uspaceAppId;
	@Value("${uspace.secret}")
	private String uspaceSecret;

    @Value("${pms.url}")
    private String pmsUrl;

    @Value("${pms.password}")
    private String pmsPassword;

    @Value("${uspace.personchepaiList}")
    private String personchepaiList;

    @Value("${uspace.parkrecord}")
    private String parkrecord;

	@Override
	public int getCarInfo(String time1,String time2) {
		int records=0;
        int page=1;
        Map<String, Object> paramers =new HashMap<String, Object>();
        paramers.put("uspaceAppId", uspaceAppId);
        paramers.put("uspaceSecret", uspaceSecret);
		if(StringUtil.isNotEmpty(time1)){
			paramers.put("time1", time1);
		}
		if(StringUtil.isNotEmpty(time2)){
			paramers.put("time2",time2);
		}
        paramers.put("page", page);
        String response = "";
        try {
            response= HttpUtil.sendxwwwform(uspaceUrl+personchepaiList,paramers);
            JSONObject json= JSONObject.parseObject(response);
            JSONArray data =json.getJSONArray("data");
			records =json.getInteger("records");
			List<CarEntity> list = JSONArray.parseArray(data.toJSONString(), CarEntity.class);
            if(list!=null&&list.size()>0){
                for(CarEntity car :list){
                    car.setCarNo(car.getChepai());
                    car.setCardNo(car.getId()+"");
                    car.setStruStartTime(car.getCreat_time());
                    car.setStruStopTime(car.getExpirydate());
                    car.setPlateType("4");
                    if(car.getChepai().length()==7){
                        car.setPlateColor("0");
                    }else{
                        car.setPlateColor("4");
                    }
                    //判断是否新增或删除
                    CarEntity cars =carService.getCarById(car.getId());
                    if(cars==null){
                        carService.insertCar(car);
                    }else{
                        if(car.getIsDel()!=cars.getIsDel()){
                            car.setSync("0");
                            carService.updateCar(car);
                        }
                    }
                }
                Integer total =json.getInteger("total");
                if(total>page){
                    for(int i=1;i<=total;i++){
                        paramers.put("page", i+1);
                        response=HttpUtil.sendxwwwform(uspaceUrl,paramers);
                         JSONObject jsons= JSONObject.parseObject(response);
                        JSONArray datas =jsons.getJSONArray("data");
                        List<CarEntity> lists = JSONArray.parseArray(datas.toJSONString(), CarEntity.class);
                        for(CarEntity car :lists){
                            car.setCarNo(car.getChepai());
                            car.setCardNo(car.getId()+"");
                            car.setStruStartTime(car.getCreat_time());
                            car.setStruStopTime(car.getExpirydate());
                            car.setPlateType("4");
                            if(car.getChepai().length()==7){
                                car.setPlateColor("0");
                            }else{
                                car.setPlateColor("4");
                            }
                            //判断是否新增或删除
                            CarEntity cars =carService.getCarById(car.getId());
                            if(cars==null){
                                carService.insertCar(car);
                            }else{
                                if(car.getIsDel()!=cars.getIsDel()){
                                    car.setSync("0");
                                    carService.updateCar(car);
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
		return records;
	}

    @Override
    public void getCarRecord(CarRecordEntity car) {
        Map<String, Object> paramers =new HashMap<String, Object>();
        paramers.put("uspaceAppId", uspaceAppId);
        paramers.put("uspaceSecret", uspaceSecret);
        paramers.put("chepai", car.getPlateNo());
        paramers.put("deviceKey", car.getTerminalNo());
        paramers.put("pic_url", car.getPicVehicleFileData());
        paramers.put("creat_time", car.getPassTime());
        String type="";
        if("出口".equals(car.getLaneName())){
            type="2";
        }else{
            type="1";
        }
        paramers.put("type", type);
        System.out.println("=============上传通信记录数据格式"+paramers);
        String response = "";
        try {
            response= HttpUtil.sendxwwwform(uspaceUrl+parkrecord,paramers);
            JSONObject json= JSONObject.parseObject(response);
            System.out.println("=============上传通信记录返回数据"+json);
            int state =json.getInteger("state");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

/*
	@Override
	public int syncHk() {
		int records=0;
		HikTest test = new HikTest();
		CarEntity car=new CarEntity();
		car.setSync("0");
		List<CarEntity> list=carService.selectCarList(car);
		test.initCarList(list);
        HikIn in = new HikIn();
        in.initCarList(list);

        return records;
	}
*/

    @Override
    public int syncHk() {
        int records=0;
        int addRecords=0;
        int removeRecords=0;
        //获取未同步的车辆信息
        CarEntity car=new CarEntity();
        car.setSync("0");
        List<CarEntity> list=carService.selectCarList(car);
        records=list.size();
        String response = "";
        String addUrl=pmsUrl+"addInnerVehicle";//白名单车辆新增或修改
        String removeUrl=pmsUrl+"delInnerVehicle";//根据车牌删除白名单车辆
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            for(CarEntity carEntity:list){
                String strMD5Pwd= DigestUtils.md5Hex(pmsPassword).toUpperCase();
                String strSign= DigestUtils.md5Hex((carEntity.getCarNo()+strMD5Pwd)).toUpperCase();
                if("2".equals(carEntity.getIsDel())){//删除车辆不进行授权 移出白名单
                    Map<String, Object> paramer =new HashMap<String, Object>();
                    paramer.put("plateNo", carEntity.getCarNo());
                    paramer.put("startTime", sdf.format(carEntity.getStruStartTime()));
                    paramer.put("endTime", sdf.format(carEntity.getStruStopTime()));
                    paramer.put("ownerName", "dcsoft");
                    paramer.put("ownerPhone", "13155555555");
                    paramer.put("createTime", sdf.format(new Date()));
                    paramer.put("sign", strSign);
                    response= HttpUtil.postData(addUrl,paramer);
                    JSONObject json= JSONObject.parseObject(response);
                    System.out.println("白名单车辆新增或修改返回===="+json);
                    String data =json.get("code")+"";
                    if("0".equals(data)){
                        carEntity.setSync("1");
                        carService.updateCar(carEntity);
                        addRecords++;
                    }
                }else{
                    Map<String, Object> paramers =new HashMap<String, Object>();
                    paramers.put("plateNo", carEntity.getCarNo());
                    paramers.put("sign", strSign);
                    response= HttpUtil.postData(removeUrl,paramers);
                    JSONObject json= JSONObject.parseObject(response);
                    System.out.println("白名单车辆新增或修改返回===="+json);
                    String data =json.get("code")+"";
                    if("0".equals(data)){
                        carEntity.setSync("1");
                        carService.updateCar(carEntity);
                        removeRecords++;
                    }
                }
            }
            System.out.println("白名单车辆新增或修改===="+addRecords);
            System.out.println("删除白名单车辆===="+removeRecords);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return records;
    }



}
