package com.sptg.estate.biz.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.sptg.common.core.beans.ExcelResultEnum;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.common.core.util.JsonUtils;
import com.sptg.estate.api.dto.ResidentialDto;
import com.sptg.estate.api.entity.Agency;
import com.sptg.estate.api.entity.Residential;
import com.sptg.estate.api.feigns.ResidentialFeign;
import com.sptg.estate.biz.service.AgencyServiceInterface;
import com.sptg.estate.biz.service.ResidentialServiceInterface;
import com.sptg.permissions.api.dto.OrgDto;
import com.sptg.permissions.api.entity.Organization;
import com.sptg.permissions.api.feigns.OrgFeign;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.persistence.criteria.CriteriaBuilder;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * title: ResidentialController
 * package: com.sptg.estate.biz.controller
 * description:小区 控制器
 */
@RestController
public class ResidentialController implements ResidentialFeign {

    private final ResidentialServiceInterface residentialServiceInterface;
    private final AgencyServiceInterface agencyServiceInterface;
    private final OrgFeign orgFeign;

    @Autowired
    public ResidentialController(ResidentialServiceInterface residentialServiceInterface,AgencyServiceInterface agencyServiceInterface,OrgFeign orgFeign) {
        this.residentialServiceInterface = residentialServiceInterface;
        this.agencyServiceInterface = agencyServiceInterface;
        this.orgFeign = orgFeign;
    }

    @Override
    @PostMapping(value = "/residential/showResidentialList")
    public ResultBean<Page<Residential>> showResidentialList(@RequestBody ResidentialDto residentialDto) {
        return this.residentialServiceInterface.showResidentialList(residentialDto);
    }

    @Override
    @PostMapping(value = "/residential/addResidential")
    public ResultBean<Residential> addResidential(@RequestBody ResidentialDto residentialDto) {
        return this.residentialServiceInterface.addResidential(residentialDto);
    }

    @Override
    @GetMapping(value = "/residential/findResidentialById/{id}")
    public Residential findResidentialById(@PathVariable(value = "id") Long id) {
        return this.residentialServiceInterface.findResidentialById(id);
    }

    @Override
    @PostMapping(value = "/residential/updateResidential")
    public ResultBean<Boolean> updateResidential(@RequestBody ResidentialDto residentialDto) {
        return this.residentialServiceInterface.updateResidential(residentialDto);
    }

    @Override
    @PostMapping(value = "/residential/updateResidentialEntity")
    public ResultBean<Boolean> updateResidentialEntity(@RequestBody Residential residential) {
        return this.residentialServiceInterface.updateResidentialEntity(residential);
    }

    @Override
    @PostMapping(value = "/residential/getListByCondition")
    public ResultBean<Residential> getListByCondition(@RequestBody ResidentialDto residentialDto) {
        return this.residentialServiceInterface.getListByCondition(residentialDto);
    }

    @Override
    @PostMapping(value = "/residential/updateEntity")
    public boolean updateEntity(@RequestBody Residential residential) {
        return this.residentialServiceInterface.updateById(residential);
    }

    @Override
    @GetMapping(value = "/residential/{oldId}")
    public Residential getByOldId(@PathVariable(value = "oldId") String oldId) {
        Wrapper<Residential> wrapper = new EntityWrapper<>();
        wrapper.eq("old_id", oldId);
        return this.residentialServiceInterface.selectOne(wrapper);
    }

    @Override
    public List<Residential> getListByLikeName(@RequestBody ResidentialDto dto) {
        return this.residentialServiceInterface.getListByLikeName(dto);
    }

    @Override
    @PostMapping(value = "/residential/deleteResidential")
    public ResultBean<Boolean> deleteResidential(@RequestBody ResidentialDto residentialDto) {
        return this.residentialServiceInterface.deleteResidential(residentialDto);
    }

    @Override
    @PostMapping(value = "/residential/trashOrRecover")
    public ResultBean<Boolean> trashOrRecover(@RequestBody ResidentialDto residentialDto) {
        return this.residentialServiceInterface.trashOrRecover(residentialDto);
    }

    @Override
    @PostMapping(value = "/residential/deleteResidentialList")
    public ResultBean<Boolean> deleteResidentialList(@RequestBody ResidentialDto residentialDto) {
        try {
            return this.residentialServiceInterface.deleteResidentialList(residentialDto);
        } catch (Exception e) {
            if (StringUtils.isBlank(e.getMessage())) {
                return new ResultBean<>(ResultEnum.ERROR);
            } else {
                return new ResultBean<>("500", e.getMessage());
            }
        }
    }

    @Override
    @PostMapping(value = "/residential/importResidentialList")
    public ResultBean<Boolean> importResidentialList(@RequestBody List<ResidentialDto> list) {
        try {
            return this.residentialServiceInterface.importResidentialList(list);
        } catch (Exception e) {
            if (StringUtils.isBlank(e.getMessage())) {
                return new ResultBean<>(ExcelResultEnum.ERROR);
            } else {
                return new ResultBean<>("200", e.getMessage());
            }
        }
    }

    @Override
    @PostMapping(value = "/residential/findListByPosition")
    public ResultBean<Residential> findListByPosition(@RequestBody ResidentialDto residentialDto) {
        return this.residentialServiceInterface.findListByPosition(residentialDto);
    }

    @Override
    @PostMapping(value = "/residential/statisticsUserCountList")
    public ResultBean<Page<Residential>> statisticsUserCountList(@RequestBody ResidentialDto residentialDto) {
        return new ResultBean<>(ResultEnum.SUCCESS, this.residentialServiceInterface.statisticsUserCountList(residentialDto));
    }

    @Override
    @PostMapping(value = "/residential/getStatisticsUserCountList")
    public List<Residential> getStatisticsUserCountList(@RequestBody ResidentialDto residentialDto) {
        return this.residentialServiceInterface.getStatisticsUserCountList(residentialDto);
    }

    @Override
    @PostMapping(value = "/residential/getByOrgIdList")
    public List<Residential> getByOrgIdList(@RequestBody List<Long> idList) {
        Wrapper<Residential> wrapper = new EntityWrapper<>();
        wrapper.in("l_id", idList);
        wrapper.notIn("i_status", OperationConstant.MINUS_ONE);
        return this.residentialServiceInterface.selectList(wrapper);
    }

    @Override
    @PostMapping(value = "/residential/statisticsUserCount")
    public ResultBean<Long> statisticsUserCount(@RequestParam(value = "orgPosition") String orgPosition) {
        long count = this.residentialServiceInterface.statisticsUserCount(orgPosition);
        return new ResultBean<>(ResultEnum.SUCCESS, count);
    }

    @Override
    @PostMapping(value = "/residential/getResidentialAccount")
    public ResultBean<Map<String, Integer>> getResidentialAccount(@RequestBody ResidentialDto residentialDto) {
        Map<String, Integer> map = new HashMap<>(2);
        residentialDto.setIsAllType(OperationConstant.ONE);
        int totalCount = this.residentialServiceInterface.getResidentialAccount(residentialDto);
        map.put("totalCount", totalCount);
        residentialDto.setIsAllType(OperationConstant.TWO);
        int monthCount = this.residentialServiceInterface.getResidentialAccount(residentialDto);
        map.put("monthCount", monthCount);
        return new ResultBean<>(ResultEnum.SUCCESS, map);
    }

//    @Override
//    @PostMapping(value = "/residential/getResidentialList")
//    public ResultBean<Residential> getResidentialList(ResidentialDto residentialDto){
//        residentialDto.setOrgPosition("0/1/");
////        residentialDto.setOrgPid(1L);
//        return this.residentialServiceInterface.findListByPosition(residentialDto);
//    }

    @Override
    @PostMapping(value = "/residential/getByRegionArea")
    public ResultBean<Residential> getByRegionArea(@RequestBody Residential residential) {
        return this.residentialServiceInterface.getByRegionArea(residential);
    }

    @Override
    @PostMapping(value = "/residential/getResidentialCount")
    public Integer getResidentialCount(@RequestBody ResidentialDto residentialDto) {
        residentialDto.setIsAllType(OperationConstant.ONE);
        int totalCount = this.residentialServiceInterface.getResidentialAccount(residentialDto);
        return totalCount;
    }

    @Override
    @PostMapping(value = "/residential/getUnitCount")
    public Long getUnitCount(@RequestBody ResidentialDto residentialDto) {
        return this.residentialServiceInterface.getUnitCount(residentialDto);
    }

    @Override
    @PostMapping(value = "/residential/statisticsCityCountList")
    public List<Map<String, Object>> statisticsCityCountList(@RequestBody ResidentialDto residentialDto) {
        return this.residentialServiceInterface.statisticsCityCountList(residentialDto.getRegionProvince(), residentialDto.getOrgPosition());
    }

    @Override
    @PostMapping(value = "/residential/getResidentialByNameAndRegion")
    public int getResidentialByNameAndRegion(@RequestBody ResidentialDto residentialDto) {
        return this.residentialServiceInterface.getResidentialByNameAndRegion(residentialDto);
    }

    @Override
    @GetMapping(value = "/residential/findResidentialByNumber/{residentialNumber}")
    public Residential findResidentialByNumber(@PathVariable(value = "residentialNumber") String residentialNumber) {
        return this.residentialServiceInterface.findResidentialByNumber(residentialNumber);
    }

    @Override
    @PostMapping(value = "/residential/getUserCountForRegionAuthorize")
    public long getUserCountForRegionAuthorize(@RequestParam(value = "orgPosition") String orgPosition) {
        long totalCount = this.residentialServiceInterface.getUserCountForRegionAuthorize(orgPosition);
        return totalCount;
    }

    /**
     * 同步亲邻智能物联网平台小区数据
     *
     * @return
     */
    @GetMapping("residential/sync")
    public int test() {
        int result = 0;
//		IResidentialService residentialService =new ResidentialServiceImpl();
        RestTemplate restTemplate = new RestTemplate();
//		HttpHeaders httpHeaders =
        ResponseEntity responseEntity = null;
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE, "text/plain");
        headers.add(HttpHeaders.HOST, "qiotapi.qinlinkeji.com");
        headers.add("Cookie", "acw_tc=2760821216040233709218017edfed503c3f299563c0716431831777dc716e");
        Map<String, Object> map = new HashMap<>();
        map.put("pageNum", 3);
        map.put("pageSize", 100);

        HttpEntity<String> requestEntity = new HttpEntity<String>(JsonUtils.objectToJson(map), headers);
        ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
        };
        String url = "https://qiotapi.qinlinkeji.com/admin/community/findListPage?sessionId=admin:2c94812e75fa974901762dc0b4b503ad";
        URI uri = URI.create(url);
        responseEntity = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, reference);


        Map map1 = (Map) responseEntity.getBody();
        Map map2 = (Map) map1.get("data");
        List<Map> list = (List<Map>) map2.get("list");
//		IResidentialService residentialService = new ResidentialServiceImpl();
        for (int i = 0; i < list.size(); i++) {
            int temResult = syncDetail(list.get(i).get("id").toString());
            result = result + temResult;
        }

        return result;
    }

    /**
     * 同步小区详情
     *
     * @param residentialId
     * @return
     */

    public int syncDetail(String residentialId) {

        RestTemplate restTemplate = new RestTemplate();
//		HttpHeaders httpHeaders =
        ResponseEntity responseEntity = null;
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_TYPE, "text/plain");
        headers.add(HttpHeaders.HOST, "qiotapi.qinlinkeji.com");
        headers.add("Cookie", "acw_tc=2760821216040233709218017edfed503c3f299563c0716431831777dc716e");
        Map<String, Object> map = new HashMap<>();


        HttpEntity<String> requestEntity = new HttpEntity<String>(JsonUtils.objectToJson(map), headers);
        ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
        };
        String url = "https://qiotapi.qinlinkeji.com/admin/community/findById?sessionId=admin:2c94812e75fa974901762dc0b4b503ad&id=" + residentialId;
        URI uri = URI.create(url);
        responseEntity = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, reference);


        Map map1 = (Map) responseEntity.getBody();

        Map residentialMap = (Map) map1.get("data");

        Residential residential = new Residential();

        residential.setAccessControlMode((Integer) residentialMap.get("accessControlMode"));
        residential.setActivationProcess((Integer) residentialMap.get("activationProcess"));
        residential.setAddress(residentialMap.get("address").toString());
        residential.setBindingVirtualCard((Integer) residentialMap.get("bindingVirtualCard"));
        residential.setRegionCity(residentialMap.get("cityCode").toString());
        residential.setCommunityDeveloper(residentialMap.get("communityDeveloper").toString());
        residential.setName(residentialMap.get("communityName").toString());
        residential.setCommunityOperator(residentialMap.get("communityOperator").toString());
        if(residentialMap.get("communityType")!=null){
            residential.setCommunityType(residentialMap.get("communityType").toString());
        }

        residential.setRegionArea(residentialMap.get("districtCode").toString());
        residential.setOldId(residentialMap.get("id").toString());
        residential.setIsForceSubscribeWechat((Integer) residentialMap.get("isForceSubscribeWechat"));
        residential.setIsIdCardRequired((Integer) residentialMap.get("isIdCardRequired"));
        residential.setIsImmedUploadPic((Integer) residentialMap.get("isImmedUploadPic"));
        residential.setIsOpenHousingManagement((Integer) residentialMap.get("isOpenHousingManagement"));
        residential.setIsOpenMobileValidate((Integer) residentialMap.get("isOpenMobileValidate"));
        residential.setIsOpenPropertyPayment((Integer) residentialMap.get("isOpenPropertyPayment"));
        residential.setLatitude(residentialMap.get("latitude").toString());
        residential.setLongitude(residentialMap.get("longitude").toString());
        residential.setOperateCompanyId(Long.valueOf( residentialMap.get("operateCompanyId").toString()));
        residential.setOperateCompanyName(residentialMap.get("operateCompanyName").toString());
        residential.setPermissionExpires((Integer) residentialMap.get("permissionExpires"));
        residential.setPropertyCompanyId((Integer) residentialMap.get("propertyCompanyId"));
        residential.setPropertyName(residentialMap.get("propertyName").toString());
        if(residentialMap.get("propertyCompanyId")!=null){
            residential.setEstatePid(Long.valueOf(residentialMap.get("propertyCompanyId").toString()));
            if(residentialMap.get("propertyName")!=null){
                residential.setEstatePidName(residentialMap.get("propertyName").toString());
            }
        }


        residential.setPropertyPhone(residentialMap.get("propertyPhone").toString());
        residential.setRegionProvince(residentialMap.get("provinceCode").toString());

        //判断表中是否存在该小区数据
        Residential residential1 = this.residentialServiceInterface.getResidentialByOldId(residential.getOldId());

        if (residential1 != null) {
            residential.setId(residential1.getId());
            this.residentialServiceInterface.updateResidentialEntity(residential);

        } else {
            this.residentialServiceInterface.addResidentialBySync(residential);
        }


        return 1;
    }

    /**
     * 获取当前所有小区批量自动生成小区机构
     *
     * @return
     */
        @PostMapping(value = "residential/addOrgByResidential")
    public ResultBean<Boolean> addOrgByResidential() {
        List<Residential> records = this.residentialServiceInterface.getList();
        for(int i = 0;i<records.size();i++){
            Residential residential = records.get(i);
            OrgDto organization = new OrgDto();
            organization.setIsEnable(1);
            organization.setClientCount(0);
            organization.setDeptCount(0);
            organization.setLayerNumber(3);

            //小区所属社区
            Agency agency = this.agencyServiceInterface.findAgencyById(residential.getAgencyId());
            if(agency == null){
                System.out.println(residential.toString()+residential.getId()+residential.getName());
                continue;
            }
            residential.setAgencyName(agency.getAgencyName());

            //小区机构的上级是该小区所属社区的所属机构
           Organization agencyOrg = this.orgFeign.getOrgById(agency.getOrgPid());
           if(agencyOrg == null){
               System.out.println(residential.toString());
               continue;
           }
           residential.setRootOrgId(agencyOrg.getId());
            organization.setPid(agency.getOrgPid());
            agency.setOrgName(agencyOrg.getName());
            this.agencyServiceInterface.updateById(agency);
            organization.setParentName(agencyOrg.getName());


            organization.setAddress(residential.getAddress());
            organization.setOrgType(6);
            organization.setPosition(agencyOrg.getPosition());//后面再追加自己的id
            organization.setName(residential.getName());
            organization.setPersonName(residential.getPersonName());
            organization.setPersonTel(residential.getPersonTel());
            organization.setRegionArea(residential.getRegionArea());
            organization.setRegionCity(residential.getRegionCity());
            organization.setRegionProvince(residential.getRegionProvince());
            organization.setRegionStreet(residential.getRegionStreet());
            organization.setRootOrgId(1L);
            organization.setCreateDate(residential.getCreateDate());
            organization.setRegion(agency.getProvinceName()+"-"+agency.getCityName()+"-"+agency.getAreaName());
            organization.setStatus(0);
            ResultBean<Organization> organizationResultBean = this.orgFeign.addEntity(organization);
            Organization organization1 = organizationResultBean.getData();
            residential.setOrgPid(organization1.getId());
            residential.setOrgPidName(organization1.getName());
            residential.setOrgPosition(organization1.getPosition());
            organization1.setCode("O"+organization1.getId());
            this.orgFeign.updateEntity(organization1);
            this.residentialServiceInterface.updateById(residential);
        }
        return null;
    }

}
