package cn.com.countrygarden.bi.main.service.propertyAgreement.impl;

import cn.com.countrygarden.bi.main.dao.propertyAgreement.PropertyAgreementMapper;
import cn.com.countrygarden.bi.main.dto.propertyAgreement.PropertyAgreementDto;
import cn.com.countrygarden.bi.main.dto.propertyAgreement.PropertyAgreementVo;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.propertyAgreement.PropertyAgreement;
import cn.com.countrygarden.bi.main.service.propertyAgreement.PropertyAgreementService;
import cn.com.countrygarden.bi.main.util.DateUtil;
import cn.com.countrygarden.bi.main.util.Des3EncodeCBC;
import cn.com.countrygarden.bi.main.util.HttpsUtil;
import cn.com.countrygarden.bi.main.util.PageUtil;
import cn.com.countrygarden.bi.main.util.erp.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageRowBounds;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
@Slf4j
@Service
@PropertySource("classpath:/application.properties")
public class PropertyAgreementServiceImpl implements PropertyAgreementService {
    @Autowired
    private PropertyAgreementMapper propertyAgreementMapper;

    @Override
    public PageData selectPageList(PropertyAgreementDto param) {
        String signedTimeStartStr = param.getSignedTimeStartStr();
        String signedTimeEndStr = param.getSignedTimeEndStr();

        if (StringUtils.hasText(signedTimeStartStr)) {
            Date date = DateUtil.parseDateWuyexie(signedTimeStartStr+" 00:00");
            param.setSignedTimeStart(date);
        }
        if (StringUtils.hasText(signedTimeEndStr)) {
            Date date = DateUtil.parseDateWuyexie(signedTimeEndStr+" 23:59");
            param.setSignedTimeEnd(date);
        }


        int pageOffset = PageUtil.getPageOffset(param.getPageIndex(), param.getPageSize());
        param.setPageOffset(pageOffset);

        List<PropertyAgreementDto> data = propertyAgreementMapper.findList(param);
        for (PropertyAgreementDto ele : data) {
            ele.setSignedTimeStr(DateUtil.simpleFormat(ele.getSignedTime(),"yyyy-MM-dd HH:mm:ss"));
        }

        Integer total = propertyAgreementMapper.findCount(param);

        PageRowBounds pageRowBounds = new PageRowBounds(param.getPageIndex(), param.getPageSize());
        pageRowBounds.setTotal(total.longValue());
        pageRowBounds.setCount(true);

        PageData pageData = new PageData(data, pageRowBounds);
        return pageData;
    }

    @Override
    @Transactional
    @Scheduled(cron = "${schedule.cron.propertyAgreementSchdule}")//每天两点执行定时调度
    public boolean synchronizeData() throws IOException {
        byte[] key = "IJZVYCX798GABX7GLREUKBD1".getBytes();
        byte[] keyiv = "HDATKKIL".getBytes();
        //Date nowTime = new Date();
       // Date startTime = propertyAgreementMapper.findMaxTime();


            String startTime=DateUtil.getYestodaytijis()+" 00:00";
            String nowTime=DateUtil.getYestodaytijis()+" 23:59";

        getPropertyAgreement(key, keyiv, DateUtil.parseDateTime(nowTime), DateUtil.parseDateTime(startTime),null);
    /*    if (startTime == null) {
            Date date = DateUtil.parseDate("2019-01-01");
            int i = DateUtil.diffDay(date, new Date());
            for (int j = 0; j < i; j++) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.add(Calendar.DATE,j);//把日期往后增加一天.整数往后推,负数往前移动
                Date flagTime = calendar.getTime();
                Date endTime = DateUtil.parseDate(DateUtil.simpleFormat(flagTime, "yyyy-MM-dd 23:59:59"), "yyyy-MM-dd HH:mm:ss");
                getPropertyAgreement(key, keyiv, endTime, flagTime);
            }
            // 最后一天的处理逻辑
            getPropertyAgreement(key, keyiv, nowTime, DateUtil.parseDate(DateUtil.simpleFormat(nowTime, "yyyy-MM-dd 00:00:00")));
        } else {
            getPropertyAgreement(key, keyiv, nowTime, startTime);
        }*/
        return true;
    }


    private void getPropertyAgreement(byte[] key, byte[] keyiv, Date nowTime, Date lastTime,String areaid) {
        //加密参数
        String newOutputStr = getOutputStr(key, keyiv, lastTime, nowTime,areaid);
        System.out.println(newOutputStr);
        // 发送请求
        String info = HttpsUtil.httpsRequestWuxie("https://xsfhy.bgy.com.cn/OnlineTradeCoreApi/SLBApi/GetSignedDoc", "POST", newOutputStr);
        JSONObject jsonInfo = JSON.parseObject(info);
        String retFile = jsonInfo.getString("ret");
        if (!"0".equals(retFile)) {
            return;
        }
        String packageFile = jsonInfo.getString("package");
        // 解密结果
        byte[] bytes = null;
        try {
            bytes = new BASE64Decoder().decodeBuffer(packageFile);
            byte[] bytes1 = Des3EncodeCBC.des3DecodeCBC(key, keyiv, bytes);
            String s = new String(bytes1, "UTF-8");
            List<PropertyAgreementVo> eles = JSON.parseArray(s, PropertyAgreementVo.class);
            for (PropertyAgreementVo ele : eles) {
                PropertyAgreement propertyAgreement = getPropertyAgreement(nowTime, ele);

                List<PropertyAgreement> list=propertyAgreementMapper.selectClick(propertyAgreement);
                if(CollectionUtils.isEmpty(list)){
                    propertyAgreementMapper.insert(propertyAgreement);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getOutputStr(byte[] key, byte[] keyiv, Date lastTime, Date nowTime,String areaid) {
        String unixTime = System.currentTimeMillis() / 1000 + "";


        String packageInfo = "{\n" +
                "\t\"startTime\": \"#{startTime}\",\n" +
                "\t\"endTime\": \"#{endTime}\"\n" +
                "}";
      /*  packageInfo = packageInfo
                .replace("#{startTime}", DateUtil.dateToStrOfFormat(lastTime, "yyyy/MM/dd HH:mm"))
                .replace("#{endTime}", DateUtil.dateToStrOfFormat(nowTime, "yyyy/MM/dd HH:mm"));*/

        JSONObject result1 = new JSONObject();
        JSONObject result = new JSONObject();
        result.put("startTime", DateUtil.dateToStrOfFormat(lastTime, "yyyy/MM/dd HH:mm"));
        result.put("endTime", DateUtil.dateToStrOfFormat(nowTime, "yyyy/MM/dd HH:mm"));
        if(StringUtil.isNotBlank(areaid)){
            result.put("areaid", areaid);
        }
        packageInfo=result.toString();


        try {
            byte[] bytes = Des3EncodeCBC.des3EncodeCBC(key, keyiv, packageInfo.getBytes());
            packageInfo = new BASE64Encoder().encode(bytes);

        } catch (Exception e) {
            e.printStackTrace();
        }
        result1.put("package",packageInfo);
   /*     String outputStr = "{\n" +
                "\"companyid\":\"3C877D40-DCB1-4304-AC50-242E032A761A\",\n" +
                "\"channelid\":\"PublicInfo\",\n" +
                "\"time\":\"#{unixTime}\",\n" +
                "\"package\":\"#{package}\"\n" +
                "\n" +
                "}";*/
      /*  String outputStr = "{\n" +
                "\"package\":\"#{package}\"\n" +
                "\n" +
                "}";
        packageInfo="{\"package\": \"{\"startTime\": \"2018/01/01 00:00\",\"endTime\": \"2021/07/26 00:00\"}\"}";*/


        return result1.toString();
                //.replace("#{unixTime}", unixTime);
    }

    private PropertyAgreement getPropertyAgreement(Date nowTime, PropertyAgreementVo ele) throws ParseException {
        PropertyAgreement propertyAgreement = new PropertyAgreement();
        propertyAgreement.setAreaid(ele.getAreaid());
        propertyAgreement.setAreaName(ele.getAreaName());
        propertyAgreement.setCstname(ele.getCstname());
        propertyAgreement.setFileName(ele.getFileName());
        propertyAgreement.setFileUrl(ele.getFileUrl());
        propertyAgreement.setAreaid(ele.getAreaid());
        propertyAgreement.setHtRoomName(ele.getHtRoomName());
        propertyAgreement.setRegionName(ele.getRegionName());
        propertyAgreement.setRoomid(ele.getRoomid());
        propertyAgreement.setSalesRegionName(ele.getSalesRegionName());
        propertyAgreement.setSignedTime(DateUtil.parseDateTime(ele.getSignedTime()));
        propertyAgreement.setCreateTime(nowTime);
        return propertyAgreement;
    }

    @Override
    public List<String> selectOrganList() {
        List<String> organLists = propertyAgreementMapper.findOrganList();
        return organLists;
    }

    @Transactional
    @Override
    public boolean synchronizeDataTest(String startTime, String nowTime,String areaid) {
        byte[] key = "IJZVYCX798GABX7GLREUKBD1".getBytes();
        byte[] keyiv = "HDATKKIL".getBytes();
        //Date nowTime = new Date();
        // Date startTime = propertyAgreementMapper.findMaxTime();

        if(StringUtil.isBlank(startTime) && StringUtil.isBlank(nowTime)){
             startTime=DateUtil.getYestodaytijis()+" 00:00";
             nowTime=DateUtil.getYestodaytijis()+" 23:59";
        }
        getPropertyAgreement(key, keyiv, DateUtil.parseDateTime(nowTime), DateUtil.parseDateTime(startTime),areaid);
        return true;
    }


}
