package com.sptg.gateway.controller.implement;

import com.baomidou.mybatisplus.plugins.Page;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
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.Base64DecodeMultipartFileUtils;
import com.sptg.common.security.annotation.Security;
import com.sptg.common.security.enums.DataFormatEnum;
import com.sptg.common.security.service.SecurityServiceInterface;
import com.sptg.device.api.dto.DevicePathDto;
import com.sptg.device.api.entity.DevicePath;
import com.sptg.device.api.feigns.DevicePathFeign;
import com.sptg.estate.api.dto.IntegratedServiceDto;
import com.sptg.estate.api.dto.ProjectDto;
import com.sptg.estate.api.dto.ResidentialDto;
import com.sptg.estate.api.entity.*;
import com.sptg.estate.api.feigns.*;
import com.sptg.permissions.api.entity.Account;
import com.sptg.permissions.api.feigns.ConfFeign;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * title: ProjectController
 * package: com.sptg.estate.biz.service
 * description: 实施小程序-项目控制器
 *
 *               
 *                      
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/app/project")
public class ProjectController {

    private final SecurityServiceInterface<Account> securityServiceInterface;
    private final ProjectFeign projectFeign;
    private final ContractFeign contractFeign;
    private final IntegratedServiceFeign integratedServiceFeign;
    private final ConfFeign confFeign;
    private final ResidentialFeign residentialFeign;
    private final FastFileStorageClient fastFileStorageClient;
    private final DevicePathFeign devicePathFeign;
    private final UnitFeign unitFeign;

    /**
     * 功能描述: 统计项目数量
     * @return ResultBean<hashMap> 返回结果
     *               
     *                      
     */
    @PostMapping(value = "/count")
    @Security(format = DataFormatEnum.JSON)
    public Map<String,Object> count(){
        Map<String,Object> hashMap = new HashMap<>(3);
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "获取结果失败");
        try {
            //获取登录账号
            Account onLineUser = this.securityServiceInterface.getOnLineUser();
            // 统计项目数量
            ResultBean<Integer> resultBean = this.projectFeign.countByOrgPosition(onLineUser.getOrgPosition());
            if(resultBean.getCode().equals(ResultEnum.SUCCESS.getCode())){
                hashMap.put("result_code", 1);
                hashMap.put("result_msg", "获取成功");
                hashMap.put("count", resultBean.getData());
            }
        }catch (Exception e){
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     * 查询实施项目列表(分页)
     * @param page {
     *              current         :    当前页码,
     *              size            :    登录密码
     *
     *            }
     * @param projectDto{
     *            residentialName   :    项目名称
     *         }
     *               
     *                     
     */
    @PostMapping(value = "/showList")
    @Security(format = DataFormatEnum.JSON)
    public Map<String,Object> showList(@RequestBody ProjectDto projectDto, @RequestBody Page<Project> page){
        Map<String,Object> hashMap = new HashMap<>(3);
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "获取数据失败");
        try {
            //获取当前登陆用户
            Account onLineUser = this.securityServiceInterface.getOnLineUser();
            projectDto.setOrgPosition(onLineUser.getOrgPosition());
            projectDto.setPage(page);
            ResultBean<Page<Project>> resultBean =  this.projectFeign.showList(projectDto);
            if(resultBean.getCode().equals(ResultEnum.SUCCESS.getCode())){
                hashMap.put("list", resultBean.getData().getRecords());
                hashMap.put("result_code", 1);
                hashMap.put("result_msg", "成功");
            }
        }catch (Exception e){
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }

        return hashMap;
    }

    /**
     * 查询实施项目列表(分页)
     * @param page {
     *              current         :    当前页码,
     *              size            :    登录密码
     *
     *            }
     * @param projectDto{
     *            residentialName   :    项目名称
     *         }
     *               
     *                     
     */
    @PostMapping(value = "/showListInstallation")
    @Security(format = DataFormatEnum.JSON)
    public Map<String,Object> showListInstallation(@RequestBody ProjectDto projectDto, @RequestBody Page<Project> page){
        Map<String,Object> hashMap = new HashMap<>(3);
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "获取数据失败");
        try {
            //获取当前登陆用户
            Account onLineUser = this.securityServiceInterface.getOnLineUser();
            projectDto.setOrgPosition(onLineUser.getOrgPosition());
            projectDto.setPage(page);
            ResultBean<Page<Project>> resultBean =  this.projectFeign.showListInstallation(projectDto);
            if(resultBean.getCode().equals(ResultEnum.SUCCESS.getCode())){
                hashMap.put("list", resultBean.getData().getRecords());
                hashMap.put("result_code", 1);
                hashMap.put("result_msg", "成功");
            }
        }catch (Exception e){
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }

        return hashMap;
    }

    /**
     * 查询实施项目列表(分页)
     * @param page {
     *              current         :    当前页码,
     *              size            :    登录密码
     *
     *            }
     * @param projectDto{
     *            residentialName   :    项目名称
     *         }
     *               
     *                     
     */
    @PostMapping(value = "/showListTest")
    @Security(format = DataFormatEnum.JSON)
    public Map<String,Object> showListTest(@RequestBody ProjectDto projectDto, @RequestBody Page<Project> page){
        Map<String,Object> hashMap = new HashMap<>(3);
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "获取数据失败");
        try {
            //获取当前登陆用户
            Account onLineUser = this.securityServiceInterface.getOnLineUser();
            projectDto.setOrgPosition(onLineUser.getOrgPosition());
            projectDto.setPage(page);
            ResultBean<Page<Project>> resultBean =  this.projectFeign.showListTest(projectDto);
            if(resultBean.getCode().equals(ResultEnum.SUCCESS.getCode())){
                hashMap.put("list", resultBean.getData().getRecords());
                hashMap.put("result_code", 1);
                hashMap.put("result_msg", "成功");
            }
        }catch (Exception e){
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }

        return hashMap;
    }

    /**
     * 功能描述: 项目详情
     * @param map {
     *               id     :  项目id
      *            }
     * @return ResultBean<hashMap> 返回结果
     *               
     *                      
     */
    @PostMapping(value = "/detail")
    @Security(format = DataFormatEnum.JSON)
    public Map<String,Object> detail(@RequestBody Map<String,String> map){
        Map<String,Object> hashMap = new HashMap<>(3);
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "获取详情失败");
        try {
            String id = map.get("id");
            if(StringUtils.isBlank(id)){
                hashMap.put("result_msg", "id不能为空");
                return hashMap;
            }
            Project project  = this.projectFeign.findById(Long.valueOf(id)).getData();
            if(project!=null){
                Contract contract = this.contractFeign.findByProjectId(project.getId()).getData();
                if(contract!=null && contract.getIntegratedServiceId()!=null){
                    IntegratedService integratedService = this.integratedServiceFeign.findById(contract.getIntegratedServiceId());
                    contract.setIntegratedServiceName(integratedService.getName());
                    //有合同扫描图片
                    List<ContractImg> list = contract.getList();
                    if(list!=null && list.size()>0){
                        String fastDfsServer = this.confFeign.getFileServerHost();
                        for(ContractImg contractImg :list){
                            //拼接图片显示地址
                            contractImg.setImgUri(fastDfsServer+contractImg.getImgUri());
                        }
                    }
                    hashMap.put("contract", contract);
                }
                hashMap.put("result_code", 1);
                hashMap.put("project", project);
            }
        }catch (Exception e){
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     * 功能描述: 获取小区信息列表
     * @param residentialDto 查询条件
     * @return ResultBean<Page>
     *               
     *                      
     */
    @PostMapping(value = "/getResidentialList")
    @Security(format = DataFormatEnum.JSON)
    public Map<String,Object> getResidentialList(@RequestBody ResidentialDto residentialDto,@RequestBody Page<Residential> page){
        Map<String,Object> hashMap = new HashMap<>(3);
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "获取数据失败");
        try {
            residentialDto.setPage(page);
            //  获取授权小区的列表
            ResultBean<Page<Residential>> resultBean = this.residentialFeign.showResidentialList(residentialDto);
            if (resultBean.getCode().equals(ResultEnum.SUCCESS.getCode())){
                hashMap.put("result_code", 1);
                hashMap.put("result_msg", "获取数据成功");
                hashMap.put("list", resultBean.getData().getRecords());
            }
        }catch (Exception e){
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }

        return hashMap;
    }

    /**
     * 功能描述:检测小区关联的小区项目数量，一个小区只能创建一个项目
     * @param
     * @return
     *               
     *                      
     */
    @PostMapping("/countByResidentialId")
    @Security(format = DataFormatEnum.JSON)
    public Map<String,Object> countByResidentialId(@RequestBody Map<String,String> map){
        Map<String,Object> hashMap = new HashMap<>(3);
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "检测失败");
        try {
            String residentialId = map.get("residentialId");
            if(StringUtils.isBlank(residentialId)){
                hashMap.put("result_msg", "residentialId不能为空");
                return hashMap;
            }
            ResultBean<Boolean> resultBean = this.projectFeign.countByResidentialId(Long.valueOf(residentialId));
            if(resultBean.getCode().equals(ResultEnum.SUCCESS.getCode())){
                hashMap.put("result_code", 1);
                hashMap.put("result", resultBean.getData());
            }
        }catch (Exception e){
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }
    /**
     * 功能描述:获取综合服务列表
     * @param
     * @return
     *               
     *                      
     */
    @PostMapping(value = "/getIntegratedServiceList")
    @Security(format = DataFormatEnum.JSON)
    public Map<String,Object> getIntegratedServiceList(@RequestBody IntegratedServiceDto integratedServiceDto, @RequestBody Page<IntegratedService> page){
        Map<String,Object> hashMap = new HashMap<>(3);
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "获取数据失败");
        try {
            //获取总部综合服务方
            integratedServiceDto.setRootOrgId((long) 1);
            integratedServiceDto.setPage(page);
            ResultBean<Page<IntegratedService>> resultBean = integratedServiceFeign.showList(integratedServiceDto);
            if(resultBean.getCode().equals(ResultEnum.SUCCESS.getCode())){
                hashMap.put("result_code", 1);
                hashMap.put("result_msg", "获取数据成功");
                hashMap.put("list", resultBean.getData().getRecords());
            }
        }catch (Exception e){
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }
    /**
     * 功能描述:base64文件上传
     * @param base64Str  文件的base64字符串  加文件头
     * @return
     *               
     *                      
     */
    @RequestMapping(value = "/uploadBase64")
    @Security(format = DataFormatEnum.JSON)
    public Map<String,Object> uploadBase64File(@RequestBody String base64Str){
        Map<String,Object> hashMap = new HashMap<>(3);
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "文件上传失败");
        try {
            MultipartFile multipartFile  = Base64DecodeMultipartFileUtils.base64ToMultipart(base64Str);
            /*
             * 返回的对象storePath
             *  storePath.fullPath = "group1/M00/00/00/wKgAYlvpNveAQ9jgAACQxvfzaOY198.jpg"
             *  storePath.group = "group1"
             *  storePath.path = "M00/00/00/wKgAYlvpNveAQ9jgAACQxvfzaOY198.jpg"
             */
            StorePath storePath = fastFileStorageClient.uploadFile(
                    multipartFile.getInputStream(),multipartFile.getSize(),
                    FilenameUtils.getExtension(multipartFile.getOriginalFilename()),null);
            if(storePath!=null){
                hashMap.put("result_code", 1);
                hashMap.put("result_msg", "文件上传成功");
                hashMap.put("storePath", storePath);
            }
        }catch (Exception e){
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     * 功能描述:添加
     * @param dto  实施项目数据
     * @param contract  合同数据
     * @return
     *               
     *                      
     */
    @RequestMapping(value = "/insert")
    @Security(format = DataFormatEnum.JSON)
    public Map<String,Object> insert(@RequestBody ProjectDto dto,@RequestBody Contract contract){
        Map<String,Object> hashMap = new HashMap<>(3);
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "添加失败");
        try {
            if(dto.getResidentialId()==null){
                hashMap.put("result_msg", "residentialId不能为空");
                return hashMap;
            }
            dto.setContract(contract);
            //获取当前登陆用户
            Account onLineUser = this.securityServiceInterface.getOnLineUser();
            dto.setStatus(OperationConstant.ZERO);
            dto.setCreateAccountId(onLineUser.getId());
            dto.setCreateName(onLineUser.getUserName());
            dto.setCreateDate(new Date());
            dto.setOrgId(onLineUser.getOrgId());
            dto.setRootOrgId(onLineUser.getRootOrgId());
            dto.setOrgPosition(onLineUser.getOrgPosition());
            ResultBean<Boolean> resultBean = this.projectFeign.insertProjectAndContract(dto);
            if(resultBean.getCode().equals(ResultEnum.SUCCESS.getCode())){
                hashMap.put("result_code", 1);
                hashMap.put("result_msg", "添加成功");
            }
        }catch (Exception e){
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     * 功能描述:根据小区id获取位置列表
     * @param
     * @return
     *               
     *                      
     */
    @PostMapping(value = "/getDevicePathListByXqId")
    @Security(format = DataFormatEnum.JSON)
    public Map<String,Object> getDevicePathListByXqId(@RequestBody Map<String,String> map){
        Map<String,Object> hashMap = new HashMap<>(3);
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "获取数据失败");
        try {
            String residentialId = map.get("residentialId");
            String type = map.get("type");
            if(StringUtils.isBlank(residentialId)){
                hashMap.put("result_msg", "residentialId不能为空");
                return hashMap;
            }
            if(StringUtils.isBlank(type)){
                hashMap.put("result_msg", "type不能为空");
                return hashMap;
            }
            DevicePathDto devicePathDto = new DevicePathDto();
            devicePathDto.setXqId(Long.valueOf(residentialId));
            devicePathDto.setType(Integer.valueOf(type));
            List<DevicePath> list = this.devicePathFeign.getList(devicePathDto);
            hashMap.put("result_code", 1);
            hashMap.put("list", list);
            if(list!=null && list.size()>0){
                hashMap.put("result_msg", "获取数据成功");
            }else{
                hashMap.put("result_msg", "未获取到相关数据");
            }
        }catch (Exception e){
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     * 功能描述:根据小区id获取单元列表
     * @param
     * @return
     *               
     *                      
     */
    @PostMapping(value = "/getUnitListByXqId")
    @Security(format = DataFormatEnum.JSON)
    public Map<String,Object> getUnitListByXqId(@RequestBody Map<String,String> map){
        Map<String,Object> hashMap = new HashMap<>(3);
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "获取数据失败");
        try {
            String residentialId = map.get("residentialId");
            if(StringUtils.isBlank(residentialId)){
                hashMap.put("result_msg", "residentialId不能为空");
                return hashMap;
            }
            List<Unit> list = this.unitFeign.getListByXqId(Long.valueOf(residentialId));
            hashMap.put("result_code", 1);
            hashMap.put("list", list);
            if(list!=null && list.size()>0){
                hashMap.put("result_msg", "获取数据成功");
            }else{
                hashMap.put("result_msg", "未获取到相关数据");
            }
        }catch (Exception e){
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }

    /**
     * 功能描述:根据小区id获取小区信息
     * @param
     * @return
     *               
     *                      
     */
    @PostMapping(value = "/findResidentialById")
    @Security(format = DataFormatEnum.JSON)
    public Map<String,Object> findResidentialById(@RequestBody Map<String,String> map){
        Map<String,Object> hashMap = new HashMap<>(3);
        hashMap.put("result_code", 0);
        hashMap.put("result_msg", "获取数据失败");
        try {
            String residentialId = map.get("residentialId");
            if(StringUtils.isBlank(residentialId)){
                hashMap.put("result_msg", "residentialId不能为空");
                return hashMap;
            }
            Residential residential = this.residentialFeign.findResidentialById(Long.valueOf(residentialId));
            hashMap.put("result_code", 1);
            hashMap.put("residential", residential);
            hashMap.put("result_msg", "获取数据成功");
        }catch (Exception e){
            log.error("异常", e);
            hashMap.put("result_msg", "后台程序异常");
        }
        return hashMap;
    }
}
