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.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.UnitDto;
import com.sptg.estate.api.entity.Building;
import com.sptg.estate.api.entity.Residential;
import com.sptg.estate.api.entity.Unit;
import com.sptg.estate.api.feigns.UnitFeign;
import com.sptg.estate.biz.service.BuildingServiceInterface;
import com.sptg.estate.biz.service.ResidentialServiceInterface;
import com.sptg.estate.biz.service.UnitServiceInterface;
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 java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * title: UnitController
 * package: com.sptg.estate.biz.controller
 * description: 单元 控制器
 */

@RestController
public class UnitController implements UnitFeign {

    private final UnitServiceInterface unitServiceInterface;
    private final BuildingServiceInterface buildingServiceInterface;
    private final ResidentialServiceInterface residentialServiceInterface;

    @Autowired
    public UnitController(UnitServiceInterface unitServiceInterface, BuildingServiceInterface buildingServiceInterface, ResidentialServiceInterface residentialServiceInterface) {
        this.unitServiceInterface = unitServiceInterface;
        this.buildingServiceInterface = buildingServiceInterface;
        this.residentialServiceInterface = residentialServiceInterface;
    }

    @Override
    @PostMapping(value = "/unit/showUnitList")
    public ResultBean<Page<Unit>> showUnitList(@RequestBody UnitDto unitDto) {
        return this.unitServiceInterface.showUnitList(unitDto);
    }

    @Override
    @PostMapping(value = "/unit/addUnit")
    public ResultBean<UnitDto> addUnit(@RequestBody UnitDto unitDto) {
        return this.unitServiceInterface.addUnit(unitDto);
    }

    @Override
    @GetMapping(value = "/unit/findUnitById/{id}")
    public Unit findUnitById(@PathVariable(value = "id") Long id) {
        return this.unitServiceInterface.findUnitById(id);
    }

    @Override
    @PostMapping(value = "/unit/updateUnit")
    public ResultBean<Boolean> updateUnit(@RequestBody UnitDto unitDto) {
        return this.unitServiceInterface.updateUnit(unitDto);
    }

    @Override
    @PostMapping(value = "/unit/deleteUnit")
    public ResultBean<Boolean> deleteUnit(@RequestBody UnitDto unitDto) {
        return this.unitServiceInterface.deleteUnit(unitDto);
    }

    @Override
    @PostMapping(value = "/unit/trashOrRecover")
    public ResultBean<Boolean> trashOrRecover(@RequestBody UnitDto unitDto) {
        return this.unitServiceInterface.trashOrRecover(unitDto);
    }

    @Override
    @PostMapping(value = "/unit/deleteUnitList")
    public ResultBean<Boolean> deleteUnitList(@RequestBody UnitDto unitDto) {
        try {
            return this.unitServiceInterface.deleteUnitList(unitDto);
        } catch (Exception e) {
            if (StringUtils.isBlank(e.getMessage())) {
                return new ResultBean<>(ResultEnum.ERROR);
            } else {
                return new ResultBean<>("500", e.getMessage());
            }
        }
    }

    @Override
    @PostMapping(value = "/unit/findListByPosition")
    public ResultBean<Unit> findListByPosition(@RequestBody UnitDto unitDto) {
        return this.unitServiceInterface.findListByPosition(unitDto);
    }

    @Override
    @PostMapping(value = "/unit/findListByPid")
    public ResultBean<Unit> findListByPid(@RequestBody UnitDto unitDto) {
        return this.unitServiceInterface.findListByPid(unitDto);
    }

    @Override
    @GetMapping(value = "/unit/getListByXqId/{xqId}")
    public List<Unit> getListByXqId(@PathVariable(value = "xqId") Long xqId) {
        Wrapper<Unit> wrapper = new EntityWrapper<>();
        wrapper.eq("l_residential_id", xqId);
        wrapper.notIn("i_status", OperationConstant.MINUS_ONE);
        return this.unitServiceInterface.selectList(wrapper);
    }

    @Override
    @PostMapping(value = "/unit/getListByIdList")
    public List<Unit> getListByIdList(@RequestBody List<Long> dyIdList) {
        Wrapper<Unit> wrapper = new EntityWrapper<>();
        wrapper.in("l_id", dyIdList);
        wrapper.notIn("i_status", OperationConstant.MINUS_ONE);
        return this.unitServiceInterface.selectList(wrapper);
    }

    @Override
    @PostMapping(value = "/unit/getListByIdListAndUnitName")
    public List<Unit> getListByIdListAndUnitName(@RequestBody List<Long> dyIdList,@RequestParam("unitName") String unitName) {
        Wrapper<Unit> wrapper = new EntityWrapper<>();
        wrapper.in("l_id",dyIdList);
        wrapper.notIn("i_status", OperationConstant.MINUS_ONE);
        wrapper.like(StringUtils.isNotBlank(unitName),"s_name",unitName);
        return this.unitServiceInterface.selectList(wrapper);
    }

    @Override
    @PostMapping(value = "/unit/importUnitList")
    public ResultBean<Boolean> importUnitList(@RequestBody UnitDto unitDto) {
        return this.unitServiceInterface.importUnitList(unitDto);
    }

    @Override
    @PostMapping(value = "/unit/getUnitAccount")
    public ResultBean<Map<String, Integer>> getUnitAccount(@RequestBody UnitDto unitDto) {
        Map<String, Integer> map = new HashMap<>(2);
        unitDto.setIsAllType(OperationConstant.ONE);
        int totalCount = this.unitServiceInterface.getUnitAccount(unitDto);
        map.put("totalCount", totalCount);
        unitDto.setIsAllType(OperationConstant.TWO);
        int monthCount = this.unitServiceInterface.getUnitAccount(unitDto);
        map.put("monthCount", monthCount);
        return new ResultBean<>(ResultEnum.SUCCESS, map);
    }

    @Override
    @PostMapping(value = "/unit/getUnitCount")
    public int getUnitCount(@RequestBody UnitDto unitDto) {
        unitDto.setIsAllType(OperationConstant.ONE);
        int totalCount = this.unitServiceInterface.getUnitAccount(unitDto);
        return totalCount;
    }

    @Override
    @PostMapping(value = "/unit/findUnitByCondition")
    public int findUnitByCondition(@RequestBody UnitDto unitDto) {
        return this.unitServiceInterface.findUnitByCondition(unitDto);
    }

    @Override
    @PostMapping(value = "/unit/findUnitByNameAndNumber")
    public Unit findUnitByNameAndNumber(@RequestBody UnitDto unitDto) {
        return this.unitServiceInterface.findUnitByNameAndNumber(unitDto);
    }

    @Override
    @PostMapping(value = "/unit/addUnitByImport")
    public Unit addUnitByImport(@RequestBody Unit unit) {
        return this.unitServiceInterface.addUnitByImport(unit);
    }

    @Override
    @GetMapping(value = "/unit/getByUnitNumberAndXqId")
    public Unit getByUnitNumberAndXqId(
            @RequestParam(value = "xqId") Long xqId,
            @RequestParam(value = "unitNumber") String unitNumber) {
        Wrapper<Unit> wrapper = new EntityWrapper<>();
        wrapper.eq("l_residential_id", xqId);
        wrapper.eq("s_unit_number", unitNumber);
        return this.unitServiceInterface.selectOne(wrapper);
    }

    @Override
    @PostMapping(value = "/unit/updateEntity")
    public boolean updateEntity(@RequestBody Unit unit) {
        System.out.println("/unit/updateEntity");
        return this.unitServiceInterface.updateById(unit);
    }

    @Override
    @PostMapping(value = "/unit/updateUnitList")
    public boolean updateUnitList(@RequestBody List<Unit> unitList){
        return this.unitServiceInterface.updateBatchById(unitList);
    }

    @Override
    @PostMapping(value = "/unit/getListByLikeName")
    public List<Unit> getListByLikeName(@RequestBody UnitDto dto) {
        return this.unitServiceInterface.getListByLikeName(dto);
    }

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

    @Override
    @GetMapping(value = "/unit/getByUnitNumber/{unitNumber}")
    public Unit getByUnitNumber(@PathVariable(value = "unitNumber") String unitNumber) {
        if (StringUtils.isNotBlank(unitNumber)) {
            return this.unitServiceInterface.findByUnitNumber(unitNumber);
        }
        return null;
    }

    @Override
    public int addUnitBySync(Unit unit) {
        return this.unitServiceInterface.addUnitSync(unit);
    }

    @Override
    @GetMapping(value = "/unit/getListByBuildingId")
    public List<Unit> getListByBuildingId(@RequestParam(value = "buildingId") Long buildingId) {
        return this.unitServiceInterface.getListByBuildingId(buildingId);
    }

    @Override
    public List<Unit> getListByCondition(@RequestBody UnitDto unitDto) {
        return this.unitServiceInterface.getListByCondition(unitDto);
    }

    /**
     * 同步亲邻智能物联网平台单元数据
     *
     * @return
     */
    @GetMapping("/unit/sync")
    public int unitSync() {
        List<Building> buildingList = this.buildingServiceInterface.getListByCondition(null);
        int addResult = 0;
        int updateResult = 0;

        for (int j = 0; j < buildingList.size(); j++) {
            Building building = buildingList.get(j);
            Residential residential = residentialServiceInterface.findResidentialById(building.getResidentialId());
            RestTemplate restTemplate = new RestTemplate();
            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=2760822c16041156819701506e1f0df2b6797f5010bb8a47e5c8d932fa360e");
            Map<String, Object> map = new HashMap<>();
//			{
//				"communityId": "9463",
//				"id": 122792,
//				"nodeType": 1,
//				"requestSource": 2}
            map.put("communityId", residential.getOldId());
            map.put("id", buildingList.get(j).getOldId());
            map.put("nodeType", 1);
            map.put("requestSource", 2);

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


            Map map1 = (Map) responseEntity.getBody();
            List<Map> list = (List<Map>) map1.get("data");

            for (int i = 0; i < list.size(); i++) {
                Unit unit = new Unit();

                Integer integer = (Integer) list.get(i).get("id");
                unit.setOldId(integer.toString());
                unit.setName((String) list.get(i).get("label"));
                unit.setBuildingId(building.getId());
                unit.setBuildingName(buildingList.get(j).getName());
                unit.setResidentialId(residential.getId());
                unit.setResidentialName(residential.getName());

                Unit unit1 = unitServiceInterface.findByOldId(unit.getOldId());
                if (unit1 != null) {
                    unit.setId(unit1.getId());
                    int result1 = this.unitServiceInterface.updateUnitSync(unit);
                    updateResult = result1 + updateResult;
                } else {
                    int result1 = this.unitServiceInterface.addUnitSync(unit);
                    if(result1 ==1){
                        building.setUnitNumber(building.getUnitNumber()+1);
                        this.buildingServiceInterface.updateBuildingBySync(building);
                        residential.setUnitNumber(residential.getUnitNumber()+1);
                        this.residentialServiceInterface.updateResidentialEntity(residential);
                    }
                    addResult = result1 + addResult;
                }
            }
            System.out.println("楼栋id为" + buildingList.get(j).getOldId() + "的单元：" + list);

        }
        System.out.println("单元：" + "   add:" + addResult + "      update:" + updateResult);
        return addResult + updateResult;
    }

    @PostMapping("/unit/bindNewId")
    public void bindNewId() {
        List<Unit> unitList = unitServiceInterface.selectList(new EntityWrapper<>(new Unit()));
        System.out.println(unitList.size());
        unitList.parallelStream().forEach(unit -> {
            Long residentialOldId = unit.getResidentialOldId();
            Residential residential = this.residentialServiceInterface.getResidentialByOldId(residentialOldId.toString());
            unit.setResidentialId(residential.getId());
            Building building = this.buildingServiceInterface.findByOldId(unit.getBuildingOldId().toString());
            unit.setBuildingId(building.getId());
            unitServiceInterface.updateById(unit);
        });
    }

    @PostMapping("/unit/setOrgPosition")
    public void setOrgPosition() {
        List<Unit> unitList = unitServiceInterface.selectList(new EntityWrapper<>(new Unit()));
        System.out.println(unitList.size());
        for(int i=0;i<unitList.size();i++){
            Unit unit = unitList.get(i);
            Building building = this.buildingServiceInterface.findBuildingById(unit.getBuildingId());
            if(building == null){
                System.out.println(unitList.get(i)+" "+unit.getId());
                continue;
            }
            unit.setOrgPosition(building.getOrgPosition()+unit.getId()+"/");
            unitServiceInterface.updateById(unit);
        }
    }
}
