package com.ruoyi.web.controller.chenyanlogin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.controller.chenyanlogin.ChengYanAesUtil;
import com.ruoyi.web.controller.chenyanlogin.dto.*;
import com.ruoyi.web.controller.chenyanlogin.dto.HouseVillagerRelation;
import com.ruoyi.web.controller.chenyanlogin.entity.*;
import com.ruoyi.web.controller.chenyanlogin.mapper.*;
import com.ruoyi.web.controller.chenyanlogin.service.HuiCunService;
import com.ruoyi.web.domain.entity.HouseInfo;
import com.ruoyi.web.domain.entity.PersonHouseRelation;
import com.ruoyi.web.domain.entity.PersonInfo;
import com.ruoyi.web.domain.entity.SubsidyProjects;
import com.ruoyi.web.mapper.HouseInfoMapper;
import com.ruoyi.web.mapper.PersonHouseRelationMapper;
import com.ruoyi.web.mapper.PersonInfoMapper;
import com.ruoyi.web.mapper.SubsidyProjectsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.sound.midi.Soundbank;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;

import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.core.domain.AjaxResult.success;


@Service
public class HuiCunServiceImpl implements HuiCunService {
    private    static  final  String encodeRules ="gansu5jduv83m7xy";

    private    static  final  String BASE_URL ="https://huicuntest.cm-agri.com/liteapi";
    //基础数据查询接口
    private    static  final  String BASIC_DATA ="/zhxc-lite-web/web/huimu/getBasicData";
    //关爱人群数据查询接口
    private    static  final  String CARE_PEOPLE_DATA ="/zhxc-lite-web/web/huimu/getCarePeopleData";
    //事件上报数据查询接口
    private    static  final  String SNAPSHOT_REPORT_DATA ="/zhxc-lite-web/web/huimu/getSnapshotReportData";
    //一键呼叫数据查询接口
    private    static  final  String ZHWL_DEVICE_DATA ="/zhxc-lite-web/web/huimu/getZhwlDeviceData";
    //积分排行数据查询接口
    private    static  final  String POINT_RANK_DATA ="/zhxc-lite-web/web/huimu/getPointRankData";
    //文明红榜数据查询接口
    private    static  final  String CIVILIZED_DATA ="/zhxc-lite-web/web/huimu/getCivilizedData";
    //先进事迹资讯数据查询接口
    private    static  final  String VILLAGE_NEWS_DATA ="/zhxc-lite-web/web/huimu/getVillageNewsData";
    //同步人口数据查询接口
    private    static  final  String VILLAGER_DATA ="/zhxc-lite-web/web/huimu/syncVillagerData";
    //同步房屋数据查询接口
    private    static  final  String HOUSE_DATA ="/zhxc-lite-web/web/huimu/syncHouseData";
    //同步补贴数据查询接口
    private    static  final  String ALLOWANCE_DATA ="/zhxc-lite-web/web/huimu/syncAllowanceData";

    @Autowired
    private RestTemplate restTemplate;

    @Resource
    private ZhwlCaller zhwlCaller;

    //基础数据查询接口
    @Override
    public AjaxResult getBasicData() {
        Map<String, Object> requestParam = new HashMap<>();
        requestParam.put("areaCode", "510116999999");
        requestParam.put("nonce", UUID.randomUUID().toString());
        requestParam.put("timestamp", System.currentTimeMillis());
        Map<String, Object> responseData = getMap(requestParam, BASIC_DATA);
        if (responseData.get("code").equals(200)) {
            Object data = responseData.get("data");
            if ( data instanceof  JSONObject) {
                JSONObject dataStr = (JSONObject) responseData.get("data");
                BasicDataDto basicDataDto = JSONUtil.toBean(dataStr, BasicDataDto.class);
                return success(basicDataDto);
            }
            return success(null);
        } else {
            return error("同步失败" + responseData.get("message"));
        }
    }

    //关爱人群数据查询接口
    @Override
    public AjaxResult getCarePeopleData() {
        Map<String, Object> requestParam = new HashMap<>();
        requestParam.put("areaCode", "510116999999");
        requestParam.put("nonce", UUID.randomUUID().toString());
        requestParam.put("timestamp", System.currentTimeMillis());
        Map<String, Object> responseData = getMap(requestParam, CARE_PEOPLE_DATA);
        System.out.println(responseData);


//        String data = (String)responseData.get("data");
        Object data = responseData.get("data");
        if (responseData.get("code").equals(200) ) {
            if ( data instanceof  JSONObject){
                JSONObject dataStr = (JSONObject) responseData.get("data");
                CarePeopleData carePeopleData = JSONUtil.toBean(dataStr, CarePeopleData.class);
                return success(carePeopleData);
            }else {
                return success(null);
            }


        } else {
            return error("同步失败" + responseData.get("message"));
        }
    }
    // 事件上报数据查询接口
    @Override
    public AjaxResult getSnapshotReportData() {
        Map<String, Object> requestParam = new HashMap<>();
        requestParam.put("areaCode", "510116999999");
        requestParam.put("nonce", UUID.randomUUID().toString());
        requestParam.put("timestamp", System.currentTimeMillis());
        Map<String, Object> responseData = getMap(requestParam, SNAPSHOT_REPORT_DATA);
        if (responseData.get("code").equals(200)) {
            Object data = responseData.get("data");
            if ( data instanceof  JSONObject) {
                JSONObject dataStr = (JSONObject) responseData.get("data");
                SnapshotReportDto snapshotReportDto = JSONUtil.toBean(dataStr, SnapshotReportDto.class);
                return success(snapshotReportDto);
            }
            return success(null);
        } else {
            return error("同步失败" + responseData.get("message"));
        }

    }
    //一键呼叫数据查询接口
    @Override
    public AjaxResult getZhwlDeviceData() {
        Map<String, Object> requestParam = new HashMap<>();
        requestParam.put("areaCode", "510116999999");
        requestParam.put("nonce", UUID.randomUUID().toString());
        requestParam.put("timestamp", System.currentTimeMillis());
        Map<String, Object> responseData = getMap(requestParam, ZHWL_DEVICE_DATA);
        if (responseData.get("code").equals(200)) {
            Object data = responseData.get("data");
            if ( data instanceof  JSONObject) {
                JSONObject dataStr = (JSONObject) responseData.get("data");
                ZhwlDeviceDataDto snapshotReportDto = JSONUtil.toBean(dataStr, ZhwlDeviceDataDto.class);
                return success(snapshotReportDto);
            }
            return success(null);
        } else {
            return error("同步失败" + responseData.get("message"));
        }

    }

    @Override
    public AjaxResult getZhwlDeviceData(ZhwlCaller.DeviceListQueryVO queryVO) {
        ZhwlCaller.DeviceRespDTO response = zhwlCaller.getDeviceList(queryVO);
        //todo test start
//        List<ZhwlCaller.DeviceRespDTO.DeviceItemDTO> list = new ArrayList<>();
//        ZhwlCaller.DeviceRespDTO.DeviceItemDTO item1 = new ZhwlCaller.DeviceRespDTO.DeviceItemDTO();
//        item1.setDeviceId(10001L);
//        item1.setDeviceModelName("test-10001");
//        item1.setCreateTime(LocalDateTime.now().toString());
//        item1.setUpdateTime(LocalDateTime.now().toString());
//        list.add(item1);
//        ZhwlCaller.DeviceRespDTO.DeviceItemDTO item2 = new ZhwlCaller.DeviceRespDTO.DeviceItemDTO();
//        item2.setDeviceId(10002L);
//        item2.setDeviceModelName("test-10002");
//        item2.setCreateTime(LocalDateTime.now().toString());
//        item2.setUpdateTime(LocalDateTime.now().toString());
//        list.add(item2);
//        response.setData(list);
        //todo test end
        return success(response);
    }

    //积分排行数据查询接口
    @Override
    public AjaxResult getPointRankData() {
        Map<String, Object> requestParam = new HashMap<>();
        requestParam.put("areaCode", "510116999999");
        requestParam.put("nonce", UUID.randomUUID().toString());
        requestParam.put("timestamp", System.currentTimeMillis());
        Map<String, Object> responseData = getMap(requestParam, POINT_RANK_DATA);
        System.out.println(responseData);
        if (responseData.get("code").equals(200)) {
            Object data = responseData.get("data");
            if ( data instanceof  JSONArray) {
                List<JSONObject> dataStr = (List<JSONObject>) responseData.get("data");
                return success(dataStr);
            }
            return  success(null);
        } else {
            return error("同步失败" + responseData.get("message"));
        }

    }
    //文明红榜数据查询接口
    @Override
    public AjaxResult getCivilizedData() {
        Map<String, Object> requestParam = new HashMap<>();
        requestParam.put("areaCode", "510116999999");
        requestParam.put("nonce", UUID.randomUUID().toString());
        requestParam.put("timestamp", System.currentTimeMillis());
        Map<String, Object> responseData = getMap(requestParam, CIVILIZED_DATA);
        if (responseData.get("code").equals(200)) {
            Object data = responseData.get("data");
            if ( data instanceof  JSONObject) {
                JSONObject dataStr = (JSONObject) responseData.get("data");
                CivilizedDataDto civilizedDataDto = JSONUtil.toBean(dataStr, CivilizedDataDto.class);
                return success(civilizedDataDto);
            }
            return success(null);
        } else {
            return error("同步失败" + responseData.get("message"));
        }
    }
    //先进事迹资讯数据查询接口
    @Override
    public AjaxResult getVillageNewsData() {
        Map<String, Object> requestParam = new HashMap<>();
        requestParam.put("areaCode", "510116999999");
        requestParam.put("nonce", UUID.randomUUID().toString());
        requestParam.put("timestamp", System.currentTimeMillis());
        Map<String, Object> responseData = getMap(requestParam, VILLAGE_NEWS_DATA);
        System.out.println(responseData);
        if (responseData.get("code").equals(200)) {
            Object data = responseData.get("data");
            if ( data instanceof  JSONArray) {
//            List<VillageNewsDataDto> dataStr = (List<VillageNewsDataDto>) responseData.get("data");
                List<VillageNewsDataDto> dataStr = JSONUtil.toList((JSONArray) responseData.get("data"), VillageNewsDataDto.class
                );
                return success(dataStr);
            }
           return success(null);
        } else {
            return error("同步失败" + responseData.get("message"));
        }

    }
    //同步人口数据查询接口
    @Override
    public AjaxResult syncVillagerData(int type) {
        Map<String, Object> requestParam = new HashMap<>();
        requestParam.put("areaCode", "510116999999");
        requestParam.put("nonce", UUID.randomUUID().toString());
        requestParam.put("timestamp", System.currentTimeMillis());
        if (type ==1){
            Date date =new Date();
            Date beforeDate = DateUtil.offsetHour(date, -1);
            requestParam.put("startTime", beforeDate.getTime());
            requestParam.put("endTime", date.getTime());
        }
        Map<String, Object> responseData = getMap(requestParam, VILLAGER_DATA);
        if (responseData.get("code").equals(200)) {
            JSONObject dataStr = (JSONObject) responseData.get("data");
            SyncVillagerDataDto villageNewsDataDto = JSONUtil.toBean(dataStr, SyncVillagerDataDto.class);
            saveVillager(villageNewsDataDto);
            return success(villageNewsDataDto);
        } else {
            return error("同步失败" + responseData.get("message"));
        }
    }

    @Autowired
    private PersonInfoMapper personInfoMapper;
    @Autowired
    private TagsMapper tagsMapper;
    @Autowired
    private TagsPersonMapper tagsPersonMapper;

    @Transactional
    public void saveVillager(SyncVillagerDataDto villageNewsDataDto) {

        //标签
        savTags(villageNewsDataDto.getTagsList());

        //关联人口标签
        saveVillagerTag(villageNewsDataDto.getVillagerTagList());

        //人口
        List<VillagerList> villagerList = villageNewsDataDto.getVillagerList();
        for (VillagerList list : villagerList) {
            PersonInfo personInfo = personInfoMapper.selectById(list.getId());
            if (ObjectUtil.isEmpty(personInfo)){
                personInfo =  copyVillagerToPerson(personInfo,list);
                personInfo.setId(list.getId());
                personInfoMapper.insert(personInfo);
            }else {
                personInfo =  copyVillagerToPerson(personInfo,list);
                personInfo.setId(list.getId());
                personInfoMapper.updateById(personInfo);
            }
        }


    }

    private void saveVillagerTag(List<VillagerTagList> villagerTagList) {
        if (ObjectUtil.isNotEmpty(villagerTagList)){
            for (VillagerTagList list : villagerTagList) {
                TagsPerson tags = new TagsPerson();
                BeanUtil.copyProperties(list, tags);
                TagsPerson tags1 = tagsPersonMapper.selectById(list.getId());
                if(ObjectUtil.isEmpty(tags1)){
                    tagsPersonMapper.insert(tags);
                }else {
                    tagsPersonMapper.updateById(tags);
                }
            }
        }

    }

    private void savTags(List<TagsList> tagsList) {
        if (ObjectUtil.isNotEmpty(tagsList)) {
            for (TagsList list : tagsList) {
                Tags tags = new Tags();
                BeanUtil.copyProperties(list, tags);
                Tags tags1 = tagsMapper.selectById(list.getId());

                System.out.println(tags);
                if (ObjectUtil.isEmpty(tags1)) {
                    tagsMapper.insert(tags);
                } else {
                    tagsMapper.updateById(tags);
                }

            }
        }
    }

    private PersonInfo copyVillagerToPerson(PersonInfo personInfo, VillagerList list) {
        if (ObjectUtil.isEmpty(personInfo)){
            personInfo  =new PersonInfo();
        }
        personInfo.setAge(DateUtil.ageOfNow(list.getBirthday()));
        personInfo.setBirthDate(DateUtil.parse(list.getBirthday()));
        personInfo.setEducationLevel(getEduction(list.getEducationLevel()));
        personInfo.setEthnic(getNation(list.getNation()));
        if (list.getGender()){
            personInfo.setGender(2);
        }else {
            personInfo.setGender(1);
        }

//        personInfo.setGrid(list.getBirthday());
//        personInfo.setHouseholdId(list.getBirthday());
//        personInfo.setHouseholdRelation(list.getBirthday());
        personInfo.setIdCard(list.getIdCard());
        if (ObjectUtil.isNotEmpty(list.getMaritalStatus())){
            personInfo.setMaritalStatus(list.getMaritalStatus()+1);
        }

        personInfo.setOccupation(getProfession(list.getProfession()));
        personInfo.setPhone(list.getPhone());
//        personInfo.setPhotoUrl(list.getBirthday());
        personInfo.setPoliticalStatus(getPolitics(list.getPoliticsStatus()));
        personInfo.setPopulationCategory(list.getType());
        //TODO 标签
        List<TagsPerson> villager_id = tagsPersonMapper.selectList(new QueryWrapper<TagsPerson>().eq("villager_id", list.getId()));
        List tagsList  =new ArrayList();
        for (TagsPerson tagsPerson : villager_id) {
            Tags tags = tagsMapper.selectById(tagsPerson.getTagId());
            tagsList.add(tags.getTagName());
        }
        personInfo.setPopulationTags(JSONUtil.toJsonStr(tagsList));
        personInfo.setRealname(list.getName());
        personInfo.setReligion(getReligion(list.getReligion()));
//        personInfo.setSpecialIdentity(list.getBirthday());

        return personInfo;
    }

    private String getProfession(Integer profession) {
        if (ObjectUtil.isEmpty(profession)){
            return null;
        }
        //@务农，1务工
        switch (profession) {
            case 0:
                return "务农";
            case 1:
                return "务工";
            default:
                return "其他";
        }
    }

    private String getReligion(Integer religion) {
        if (ObjectUtil.isEmpty(religion)){
            return null;
        }
        //(0无，1佛教，2基督教，3伊斯兰教，4其他)
        switch (religion) {
            case 0:
                return "无";
            case 1:
                return "佛教";
            case 2:
                return "基督教";
            case 3:
                return "伊斯兰教";
            case 4:
                return "其他";
            default:
                return "其他";

        }
    }

    private String getPolitics(Integer politicsStatus) {
        if (ObjectUtil.isEmpty(politicsStatus)){
            return null;
        }
        //群众，1共青团员，2中共党员，3预备党员，4其它
        switch (politicsStatus) {
            case 1:
                return "共青团员";
            case 2:
                return "中共党员";
            case 3:
                return "预备党员";
            case 4:
                return "其他";
            default:
                return "其他";


        }
    }

    private String getNation(Integer nation) {
        if (ObjectUtil.isEmpty(nation)){
            return null;
        }
        //(0汉族、1壮族、2苗族、3回族、4满族)
        switch (nation) {
            case 0:
                return "汉族";
            case 1:
                return "壮族";
            case 2:
                return "苗族";
            case 3:
                return "回族";
            case 4:
                return "满族";
            default:
                return "其他";


        }
    }

    private String getEduction(Integer educationLevel) {
        if (ObjectUtil.isEmpty(educationLevel)){
            return null;
        }
        switch (educationLevel){
            case 0:
                return "文盲半文盲";
            case 1:
                return "小学";
            case 2:
                return "初中";
            case 3:
                return "高中";
            case 4:
                return "中等职业教育";
            case 5:
                return "专科教育";
            case 6:
                return "大学本科";
            case 7:
                return "硕士";
            case 8:
                return "博士";
            default:
                return "其他";


        }
    }

    @Autowired
    private HouseInfoMapper houseInfoMapper;
    @Autowired
    private PersonHouseRelationMapper  personHouseRelationMapper;
    @Autowired
    private HouseDigitalNumberMapper houseDigitalNumberMapper;
    @Autowired
    private HousePictureMapper housePictureMapper;
    @Autowired
    private HouseTagMapper houseTagMapper;


    //同步房屋数据查询接口
    @Override
    public AjaxResult syncHouseData(int type) {
        Map<String, Object> requestParam = new HashMap<>();
        requestParam.put("areaCode", "510116999999");
        requestParam.put("nonce", UUID.randomUUID().toString());
        requestParam.put("timestamp", System.currentTimeMillis());
        if (type ==1){
            Date date =new Date();
            Date beforeDate = DateUtil.offsetHour(date, -1);
            requestParam.put("startTime", beforeDate.getTime());
            requestParam.put("endTime", date.getTime());
        }
        Map<String, Object> responseData = getMap(requestParam,HOUSE_DATA);
        if (responseData.get("code").equals(200)) {
            JSONObject dataStr = (JSONObject) responseData.get("data");
            System.out.println(dataStr);
            HouseData villageNewsDataDto = JSONUtil.toBean(dataStr, HouseData.class);
            saveHous(villageNewsDataDto);
            return success(villageNewsDataDto);
        } else {
            return error("同步失败" + responseData.get("message"));
        }
    }
    @Transactional
    public void saveHous(HouseData villageNewsDataDto) {
        //房屋门牌图片数据
        saveHouseDigitalNumberPlate(villageNewsDataDto.getHouseDigitalNumberPlateList());
        saveHousePicture(villageNewsDataDto.getHousePictureList());
        saveHouseTag(villageNewsDataDto.getHouseTagList());
        saveHouseVillagerRelation(villageNewsDataDto.getHouseVillagerRelationList());

        savTags(villageNewsDataDto.getTagsList());
        saveHousInfo(villageNewsDataDto.getHouseList());
    }

    private void saveHouseVillagerRelation(List<HouseVillagerRelation> houseVillagerRelationList) {
        for (HouseVillagerRelation list : houseVillagerRelationList) {
            PersonHouseRelation tags1 = personHouseRelationMapper.selectById(list.getId());
            if(ObjectUtil.isEmpty(tags1)){
                tags1  = new PersonHouseRelation();
                tags1.setId(list.getId());
                tags1.setPersonId(list.getVillagerId());
                tags1.setHouseId(list.getHouseId());
                tags1.setVillagerType(list.getVillagerType());
                tags1.setCreateTime(new Date(list.getCreateTime()));
                personHouseRelationMapper.insert(tags1);
            }else {
                personHouseRelationMapper.updateById(tags1);
            }

        }

    }

    private void saveHouseTag(List<HouseTags> houseTagsList) {
        if (ObjectUtil.isNotEmpty(houseTagsList)){
            for (HouseTags list : houseTagsList) {
                HouseTag tags = new HouseTag();
                BeanUtil.copyProperties(list, tags);
                HouseTag tags1 = houseTagMapper.selectById(list.getId());
                if(ObjectUtil.isEmpty(tags1)){
                    houseTagMapper.insert(tags);
                }else {
                    houseTagMapper.updateById(tags);
                }

            }
        }


    }

    private void saveHousePicture(List<HousePictures> housePicturesList) {
        if (ObjectUtil.isNotEmpty(housePicturesList)) {
            if (ObjectUtil.isNotEmpty(housePicturesList)) {
                for (HousePictures list : housePicturesList) {
                    HousePicture tags = new HousePicture();
                    BeanUtil.copyProperties(list, tags);
                    HousePicture tags1 = housePictureMapper.selectById(list.getId());
                    if (ObjectUtil.isEmpty(tags1)) {
                        housePictureMapper.insert(tags);
                    } else {
                        housePictureMapper.updateById(tags);
                    }

                }
            }
        }
    }


    private void saveHouseDigitalNumberPlate(List<HouseDigitalNumberPlate> houseDigitalNumberPlateList) {
        if (ObjectUtil.isNotEmpty(houseDigitalNumberPlateList)) {
            for (HouseDigitalNumberPlate list : houseDigitalNumberPlateList) {
                HouseDigitalNumber tags = new HouseDigitalNumber();
                BeanUtil.copyProperties(list, tags);
                HouseDigitalNumber tags1 = houseDigitalNumberMapper.selectById(list.getId());

                if (ObjectUtil.isEmpty(tags1)) {
                    houseDigitalNumberMapper.insert(tags);
                } else {
                    houseDigitalNumberMapper.updateById(tags);
                }

            }
        }
    }

    private void saveHousInfo(List<House> houstList) {

        if (ObjectUtil.isNotEmpty(houstList)) {
            for (House list : houstList) {
                HouseInfo houseInfo = houseInfoMapper.selectById(list.getId());

                if (ObjectUtil.isEmpty(houseInfo)) {
                    houseInfo = copylistToHoues(houseInfo, list);
                    houseInfo.setId(list.getId());

                    houseInfoMapper.insert(houseInfo);
                } else {
                    houseInfo = copylistToHoues(houseInfo, list);
                    houseInfo.setId(list.getId());
                    houseInfoMapper.updateById(houseInfo);
                }
            }
        }
    }

    private HouseInfo copylistToHoues(HouseInfo houseInfo, House list) {
        if (ObjectUtil.isEmpty(houseInfo)){
            houseInfo = new HouseInfo();
        }
        houseInfo.setBuildingArea(list.getHomesteadArea());
        houseInfo.setCreateTime(new Date(list.getCreateTime()));
        houseInfo.setDoorplateNumber(list.getHouseNumber());
        houseInfo.setGrid(list.getGridId()+"");
        houseInfo.setHouseAddress(list.getAddress());
//        houseInfo.setHouseCategory(list.getHomesteadArea());
        houseInfo.setHouseCode(list.getHouseCode());
        houseInfo.setHouseOwnerId(list.getHouseOwnerId());
        //TODO 标签
        List<HouseTag> houseTags = houseTagMapper.selectList(new QueryWrapper<HouseTag>().eq("house_id", list.getId()));
        List tagsList  =new ArrayList();
        for (HouseTag tagsPerson : houseTags) {
            Tags tags = tagsMapper.selectById(tagsPerson.getTagId());
            tagsList.add(tags.getTagName());
        }
        houseInfo.setHouseTags(JSONUtil.toJsonStr(tagsList));

        houseInfo.setId(list.getId());

        //TODO 图片
        List<HousePicture> housePictures = housePictureMapper.selectList(new QueryWrapper<HousePicture>().eq("house_id", list.getId()));
        StringBuilder photoUrl = new StringBuilder();
        for (HousePicture picture : housePictures) {
            photoUrl.append(picture.getPicture());
        }
        houseInfo.setPhotoUrl(photoUrl.toString());
        System.out.println("1111111111111111"+list.toString());
        houseInfo.setRemainingPoints( new BigDecimal(list.getPointNow()).setScale(2, RoundingMode.HALF_UP) );
        houseInfo.setTotalPoints( new BigDecimal(list.getPointTotal()).setScale(2, RoundingMode.HALF_UP));
        houseInfo.setUpdateTime(new Date(list.getUpdateTime()));

        return houseInfo;
    }




    //同步补贴数据查询接口
    @Override
    public AjaxResult syncAllowanceData(int type) {
        Map<String, Object> requestParam = new HashMap<>();
        requestParam.put("areaCode", "510116999999");
        requestParam.put("nonce", UUID.randomUUID().toString());
        requestParam.put("timestamp", System.currentTimeMillis());
        if (type ==1){
            Date date =new Date();
            Date beforeDate = DateUtil.offsetHour(date, -1);
            requestParam.put("startTime", beforeDate.getTime());
            requestParam.put("endTime", date.getTime());
        }

        Map<String, Object> responseData = getMap(requestParam,ALLOWANCE_DATA);
        if (responseData.get("code").equals(200)) {
            JSONObject dataStr = (JSONObject) responseData.get("data");
            System.out.println(dataStr);
            AlllowanceDto villageNewsDataDto = JSONUtil.toBean(dataStr, AlllowanceDto.class);
            saveSubsidyProjects(villageNewsDataDto);
            return success(villageNewsDataDto);
        } else {
            return error("同步失败" + responseData.get("message"));
        }

    }

    @Autowired
    private SubsidyProjectsJianMapper subsidyProjectsJianMapper;
    @Autowired
    private SubsidyProjectsMapper subsidyProjectsMapper;
    private void saveSubsidyProjects(AlllowanceDto villageNewsDataDto) {

        //项目
        List<CardProject> cardProjectList = villageNewsDataDto.getCardProjectList();

        if (ObjectUtil.isNotEmpty(cardProjectList)) {
            for (CardProject list : cardProjectList) {
                SubsidyProjectsJian houseInfo = subsidyProjectsJianMapper.selectById(list.getId());
                SubsidyProjectsJian subsidyProjectsJian = new SubsidyProjectsJian();
                BeanUtil.copyProperties(list, subsidyProjectsJian);
                if (ObjectUtil.isEmpty(houseInfo)) {
                    subsidyProjectsJianMapper.insert(subsidyProjectsJian);
                } else {
                    subsidyProjectsJianMapper.updateById(subsidyProjectsJian);
                }
            }
        }
        //详细
        List<CardProjectAllowance> cardProjectAllowanceList = villageNewsDataDto.getCardProjectAllowanceList();
        for (CardProjectAllowance cardProjectAllowance : cardProjectAllowanceList) {
            SubsidyProjectsJian subsidyProjectsJian = subsidyProjectsJianMapper.selectById(cardProjectAllowance.getProjectId());
            SubsidyProjects subsidyProjects = new SubsidyProjects();
            subsidyProjects.setBankCard(cardProjectAllowance.getBankAccount());
            subsidyProjects.setCategory(getSubsidyType(subsidyProjectsJian.getAllowanceType()));
            subsidyProjects.setCreateTime(new Date(cardProjectAllowance.getDefTime()));
            subsidyProjects.setDate(new Date(cardProjectAllowance.getOfferTime()));
            subsidyProjects.setId(cardProjectAllowance.getId());
            subsidyProjects.setIdCard(cardProjectAllowance.getIdCard());
            subsidyProjects.setMoney(BigDecimal.valueOf(cardProjectAllowance.getAllowance()));
            subsidyProjects.setName(cardProjectAllowance.getNickName());
            subsidyProjects.setProjectName(subsidyProjectsJian.getProjectName());
//            subsidyProjects.setStatus();
            subsidyProjects.setUpdateTime((new Date(cardProjectAllowance.getUpdTime())));
            SubsidyProjects subsidyProjects1 = subsidyProjectsMapper.selectById(cardProjectAllowance.getId());
            if (ObjectUtil.isNotEmpty(subsidyProjects1)){
                subsidyProjectsMapper.updateById(subsidyProjects);
            }else {
                subsidyProjectsMapper.insert(subsidyProjects);
            }
        }

    }

    private String getSubsidyType(Integer allowanceType) {
        if (ObjectUtil.isEmpty(allowanceType)){
            return null;
        }
        //(1:社会保障 2:扶贫开发 3:林业 4:农业，必传)
        switch (allowanceType) {
            case 1:
                return "社会保障";
            case 2:
                return "扶贫开发";
            case 3:
                return "林业";
            case 4:
                return "农业";
            default:
                return "其他";
        }
    }


    private  Map<String, Object> getMap(Map requestParam , String lastUrl  ){
        try {
            // AES加密请求参数
            String encryptedRequest = ChengYanAesUtil.aesEncode(encodeRules, JSONUtil.toJsonStr(requestParam));
            Map<String, String> httpRequest = new HashMap<>();
            httpRequest.put("request", encryptedRequest);
            String url = BASE_URL + lastUrl;

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Client-Id", "web");
            headers.set("Trace-Id", "trace_" + System.currentTimeMillis()); // 链路追踪ID

            // 2. 创建请求实体（包含头和体）
            HttpEntity<Object> entity = new HttpEntity<>(httpRequest, headers);
            // 3. 发送请求
            ResponseEntity<String> response = restTemplate.postForEntity(
                    url,
                    entity,
                    String.class
            );

            // AES解密响应
            Map<String, String> responseMap = JSONUtil.toBean(response.getBody(), Map.class);
            String decryptedResponse = ChengYanAesUtil.aesDecode(encodeRules, responseMap.get("response"));

            // 解析响应数据
            Map<String, Object> responseData = JSONUtil.toBean(decryptedResponse, Map.class);
            return responseData;

        } catch (Exception e) {
            System.err.println("同步基础数据异常: " + e.getMessage());
            e.printStackTrace();
            return null;
        }

    }

//
//    public static AjaxResult main(String[] args) {
//
//        getBasicData();
//
//    }
}
