package com.sptg.gateway.controller.estate;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.plugins.Page;
import com.sptg.common.core.beans.PageBean;
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.constant.SysLogConstant;
import com.sptg.common.core.util.WebUtils;
import com.sptg.common.security.annotation.Security;
import com.sptg.common.security.enums.DataFormatEnum;
import com.sptg.common.security.service.SecurityServiceInterface;
import com.sptg.estate.api.constant.EstateSecurityToken;
import com.sptg.estate.api.dto.AgencyDto;
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.AgencyFeign;
import com.sptg.estate.api.feigns.ResidentialFeign;
import com.sptg.permissions.api.dto.OrgDto;
import com.sptg.permissions.api.entity.Account;
import com.sptg.permissions.api.entity.Organization;
import com.sptg.permissions.api.feigns.OrgFeign;
import com.sptg.statistics.api.constant.SysLogMenuConstant;
import com.sptg.statistics.api.entity.SysOperationLog;
import com.sptg.statistics.api.feigns.SysOperationLogFeign;
import com.sptg.third.api.feigns.grid.GridEstateFeign;
import com.sun.org.apache.xpath.internal.operations.Bool;
import lombok.RequiredArgsConstructor;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * title: AgencyController
 * package: com.sptg.gateway.controller.estate
 * description: 社区机构 网关控制器
 * 社区机构默认保存在权限--》机构表内
 *
 *
 */
@RestController
@RequestMapping("/estate/agency")
@RequiredArgsConstructor
public class AgencyController {

    private final SecurityServiceInterface<Account> securityServiceInterface;
    private final OrgFeign orgFeign;
    private final SysOperationLogFeign sysOperationLogFeign;
    private final AgencyFeign agencyFeign;
    private final GridEstateFeign gridEstateFeign;
    private final ResidentialFeign residentialFeign;

    /**
     * 功能描述:社区机构页面初始化
     * @return ModelAndView
     *
     *
     */
    @GetMapping("/index")
    @Security(token = EstateSecurityToken.ESTATE_AGENCY_MANAGE,format = DataFormatEnum.VIEW)
    public ModelAndView index(){
        return new ModelAndView("estate/agency-manage");
    }


    /**
     * 功能描述:分页查询,根据条件查询机构列表
     * @param dto 机构传输对象
     * @param pageBean 分页条件
     * @return ResultBean<Page>
     *
     *
     */
    @GetMapping(value = "/showAgencyList")
//    @Security(token = EstateSecurityToken.ESTATE_AGENCY_MANAGE,format = DataFormatEnum.JSON)
    public ResultBean<Page<Agency>> showAgencyList(AgencyDto dto, PageBean<Agency,AgencyDto> pageBean){
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        //数据权限
        dto.setOrgPosition(onLineUser.getOrgPosition());
        dto.setPage(pageBean);
//        this.agencyFeign.showAgencyList(dto);
        return this.agencyFeign.showAgencyList(dto);
    }

    public ResultBean<Page> showAgencyListOld(OrgDto dto, PageBean<Organization,OrgDto> pageBean){
        dto = null == dto ? new OrgDto() : dto;
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setPosition(onLineUser.getOrgPosition());
        dto.setFlag(OperationConstant.THREE);
        pageBean.setDto(dto);
        return new ResultBean<>(ResultEnum.SUCCESS,this.orgFeign.pagingQuery(pageBean));
    }

    /**
     * 功能描述: 修改机构状态
     * @param orgDto 机构业务对象
     * @return ResultBean<Boolean>
     *
     *
     */
    @PostMapping(value = "/updateIsEnable")
    @Security(token = EstateSecurityToken.ESTATE_AGENCY_UPDATE,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> updateIsEnable(OrgDto orgDto){
        Assert.notNull(orgDto,"非法参数");
        Assert.notNull(orgDto.getId(),"机构Id不能为空");
        Assert.notNull(orgDto.getIsEnable(),"请设置机构开启或禁用");
        //  获取当前用户
        Organization oldObj = this.orgFeign.getOrgById(orgDto.getId());
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        orgDto.setPosition(onLineUser.getOrgPosition());
        ResultBean<Boolean> resultBean = this.orgFeign.updateIsEnable(orgDto);
        if(resultBean.getData()!=null && resultBean.getData()){
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            Organization newObj = this.orgFeign.getOrgById(orgDto.getId());
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ESTATE_AGENCY_MANAGE, SysLogConstant.ALTER_EVENT,
                    WebUtils.getIp(),orgDto.getIsEnable()==1?"启用机构":"禁用机构",orgDto,onLineUser,oldObj,newObj);
            sysOperationLogFeign.info(sysOperationLog);
            /*------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    /**
     * 功能描述:添加页面初始化
     * @return ModelAndView
     *
     *
     */
    @GetMapping("/add")
    @Security(token = EstateSecurityToken.ESTATE_AGENCY_ADD,format = DataFormatEnum.VIEW)
    public ModelAndView add(String selectTreeId){
        ModelAndView modelAndView = new ModelAndView("estate/agency-add");
        modelAndView.addObject("selectTreeId",selectTreeId);
        return modelAndView;
    }

    /**
     * 功能描述: 添加机构
     * @param dto 机构业务对象
     * @return ResultBean<Organization>
     *
     *
     */
    @PostMapping(value = "/addAgency")
    @Security(token = EstateSecurityToken.ESTATE_AGENCY_ADD,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> addAgency(AgencyDto dto){
        Assert.notNull(dto,"非法参数");
        Assert.hasText(dto.getAgencyName(),"社区名称不能为空");
//        Assert.notNull(dto.getOrgPid(),"所属机构Id不能为空");
        Assert.hasText(dto.getRegionArea(),"机构所在区域不能为空");

       /* // 判重
        List<Agency> agencyList = this.agencyFeign.getListByCondition(dto);
        if(agencyList != null && agencyList.size() > 0){
            Assert.isTrue(false,"所在地区已存在社区");
        }
        //1、先建立社区机构，默认挂在根机构下
        Organization org = this.orgFeign.getOrgById(1L);
        OrgDto orgDto = new OrgDto();
        orgDto.setPid(org.getId());
        orgDto.setPosition(org.getPosition());
        ResultBean<Organization> resultBean = this.orgFeign.addEntity(orgDto);
        if(null != resultBean && resultBean.getCode().equals(ResultEnum.SUCCESS.getCode())) {
            //2、再建立社区资源，orgpo跟社区机构的orgPosition保持一致
            // 有ID回，
            Organization agencyOrg = resultBean.getData();

        }
        //社区实体的机构路径与所属社区机构一致
        Organization organization = this.orgFeign.getOrgById(dto.getOrgPid());
        dto.setOrgPosition(organization.getPosition());
        dto.setOrgName(organization.getName());*/

        ResultBean<Agency> resultBean = this.agencyFeign.addAgency(dto);
        boolean flag = resultBean.getData() != null &&resultBean.getData().getId()!=null;
        if(flag){
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            //  获取当前用户
            Account onLineUser = this.securityServiceInterface.getOnLineUser();
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ESTATE_AGENCY_MANAGE, SysLogConstant.ADD_EVENT,
                    WebUtils.getIp(),dto,onLineUser,dto);
            sysOperationLogFeign.info(sysOperationLog);
            /*------------------------------------------------------------------------------------------------------------------*/
            /*---------------------------------------------------推送数据到网格--------------------------------------------------------*/
            ResultBean<String> stringResultBean = this.gridEstateFeign.gridAgencyPush(resultBean.getData());
            if(stringResultBean.getData() != null && stringResultBean.getData().equals("操作成功")){
                SysOperationLog sysOperationLog1=new SysOperationLog("推送社区成功", SysLogConstant.ADD_EVENT,
                        WebUtils.getIp(),dto,onLineUser,dto);
                sysOperationLogFeign.info(sysOperationLog1);
            }else{
                SysOperationLog sysOperationLog1=new SysOperationLog("推送社区失败", SysLogConstant.ADD_EVENT,
                        WebUtils.getIp(),dto,onLineUser,dto);
                sysOperationLogFeign.info(sysOperationLog1);
            }

            /*------------------------------------------------------------------------------------------------------------------*/

            return new ResultBean<>(ResultEnum.SUCCESS);
        }else{
            return new ResultBean<>(ResultEnum.ERROR);
        }


    }

    public ResultBean<Organization> addAgencyOld(OrgDto dto){
        Assert.notNull(dto,"非法参数");
        Assert.hasText(dto.getName(),"机构名称不能为空");
        Assert.notNull(dto.getPid(),"机构父级Id不能为空");
        Assert.hasText(dto.getRegionArea(),"机构所在区域不能为空");
        //  获取当前用户
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        dto.setPosition(onLineUser.getOrgPosition());
        dto.setCreateAccountId(onLineUser.getId());
        dto.setFlag(OperationConstant.THREE);
        dto.setCode("O");
        ResultBean<Organization> resultBean=this.orgFeign.addEntity(dto);
        if(resultBean.getData()!=null){
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
                SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ESTATE_AGENCY_MANAGE, SysLogConstant.ADD_EVENT,
                        WebUtils.getIp(),dto,onLineUser,dto);
                sysOperationLogFeign.info(sysOperationLog);
            /*------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    /**
     * 功能描述:修改页面初始化
     * @param id 必填
     * @return ModelAndView
     *
     *
     */
    @GetMapping("/edit/{id}")
    @Security(token = EstateSecurityToken.ESTATE_AGENCY_UPDATE,format = DataFormatEnum.VIEW)
    public ModelAndView edit(@PathVariable(value = "id")Long id){
        //  获取需要修改的机构
        if (null == id){
            //  没有找到要修改的机构
            return new ModelAndView("common/404");
        }
        ModelAndView modelAndView = new ModelAndView("estate/agency-edit");
        modelAndView.addObject("id",id);
        return modelAndView;
    }

    /**
     * 功能描述: 根据Id获取社区信息
     * @param id 必填
     * @return ResultBean<Organization>
     *
     *
     */
    @GetMapping(value = "/getAgencyById/{id}")
    @Security(token = EstateSecurityToken.ESTATE_AGENCY_MANAGE,format = DataFormatEnum.JSON)
    public ResultBean<Agency> getAgencyById(@PathVariable(value = "id") Long id){
        Agency agency = this.agencyFeign.findAgencyById(id);
        return new ResultBean<>(ResultEnum.SUCCESS,agency);
    }
//    @GetMapping(value = "/getAgencyById/{id}")
//    @Security(token = EstateSecurityToken.ESTATE_AGENCY_MANAGE,format = DataFormatEnum.JSON)
//    public ResultBean<Organization> getAgencyById(@PathVariable(value = "id") Long id){
//        Organization organization = this.orgFeign.getOrgById(id);
//        return new ResultBean<>(ResultEnum.SUCCESS,organization);
//    }

    /**
     * 功能描述: 修改社区机构（不修改父节点）
     * @param dto 机构业务对象
     * @return ResultBean<Organization>
     *
     *
     */
    @PostMapping(value = "/editAgency")
    @Security(token = EstateSecurityToken.ESTATE_AGENCY_UPDATE,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> editAgency(AgencyDto dto){
        Assert.notNull(dto,"非法参数");
        //  获取当前用户信息
        Agency agency = this.agencyFeign.findAgencyById(dto.getId());
        Agency oldObj = BeanUtil.copyProperties(agency, Agency.class);
//        agency.setAgencyName(dto.getAgencyName());// 名称有多处绑定，不提供更改
        agency.setLongitude(dto.getLongitude());
        agency.setLatitude(dto.getLatitude());
        agency.setAddress(dto.getAddress());
        agency.setPersonName(dto.getPersonName());
        agency.setPersonPhone(dto.getPersonPhone());
        agency.setRemark(dto.getRemark());

//        dto.setPosition(onLineUser.getOrgPosition());
//        dto.setFlag(OperationConstant.THREE);
        ResultBean<Boolean> resultBean = this.agencyFeign.updateAgency(BeanUtil.copyProperties(agency, AgencyDto.class));
        if(resultBean.getData()!=null && resultBean.getData()){

            Organization org = this.orgFeign.getOrgById(agency.getOrgPid());
//            org.setName(dto.getAgencyName());// 名称有多处绑定，不提供更改
            org.setAddress(dto.getAddress());
            org.setPersonName(dto.getPersonName());
            org.setPersonTel(dto.getPersonPhone());
            org.setRemark(dto.getRemark());
            if (this.orgFeign.updateEntity(org)){
                /*---------------------------------------------------记录日志--------------------------------------------------------*/
                Agency newObj = this.agencyFeign.findAgencyById(dto.getId());
                Account onLineUser = this.securityServiceInterface.getOnLineUser();
                SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ESTATE_AGENCY_MANAGE, SysLogConstant.ALTER_EVENT,
                        WebUtils.getIp(),dto,onLineUser,oldObj,newObj);
                sysOperationLogFeign.info(sysOperationLog);
                /*------------------------------------------------------------------------------------------------------------------*/
            }

        }
        return resultBean;
    }

    /**
     * 功能描述: 删除社区机构
     * @param dto 机构业务对象
     * @return ResultBean<Boolean>
     *
     *
     */
    @PostMapping(value = "/deleteAgency")
    @Security(token = EstateSecurityToken.ESTATE_AGENCY_DELETE,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> deleteAgency(AgencyDto dto){
        Assert.notNull(dto,"非法参数");
//        Assert.notNull(dto.getOrgPid(),"机构Id不能为空");
        //  获取当前用户信息
        Agency oldObj = this.agencyFeign.findAgencyById(dto.getId());
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
//        dto.setPosition(onLineUser.getOrgPosition());
//        dto.setFlag(OperationConstant.THREE);
        ResultBean<Boolean> resultBean=this.agencyFeign.deleteAgency(dto);
        if(resultBean.getData()!=null  && resultBean.getData() ){
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ESTATE_AGENCY_MANAGE, SysLogConstant.DELETE_EVENT,
                    WebUtils.getIp(),dto,onLineUser,oldObj);
            sysOperationLogFeign.info(sysOperationLog);
            /*------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    /* -------------------------------------------------- 公共方法,不做权限限制 -------------------------------------------------- */
    /* -------------------------------------------------------------------------------------------------------------------------- */

    /**
     * 功能描述: 根据位置查询当前小区
     * @param residentialDto 机构业务对象
     * @return ResultBean<Organization>
     *
     *
     */
    @GetMapping(value = "/findResidentialListByCondition")
    @Security(format = DataFormatEnum.JSON)
    public ResultBean<Residential> findResidentialListByCondition(ResidentialDto residentialDto){
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        residentialDto.setOrgPosition(onLineUser.getOrgPosition());
//        orgDto.setFlag(OperationConstant.TWO);
        return this.residentialFeign.getListByCondition(residentialDto);
    }
//    public ResultBean<Organization> findResidentialListByConditionOld(OrgDto orgDto){
//        Account onLineUser = this.securityServiceInterface.getOnLineUser();
//        orgDto.setPosition(onLineUser.getOrgPosition());
//        orgDto.setFlag(OperationConstant.TWO);
//        return new ResultBean<>(ResultEnum.SUCCESS,this.orgFeign.selectListByCondition(orgDto));
//    }

    /**
     * 功能描述: 根据位置查询小区以上机构
     * @param orgDto 机构业务对象
     * @return ResultBean<Organization>
     *
     *
     */
    @GetMapping(value = "/findOrgListByCondition")
    @Security(token = EstateSecurityToken.ESTATE_AGENCY_MANAGE,format = DataFormatEnum.JSON)
    public ResultBean<Organization> findOrgListByCondition(OrgDto orgDto){
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        if (orgDto.getOrgPosition() == null){
            orgDto.setPosition(onLineUser.getOrgPosition());
        }
        if (orgDto.getFlag() == null){
            orgDto.setFlag(OperationConstant.ONE);
        }
        return new ResultBean<>(ResultEnum.SUCCESS,this.orgFeign.selectListByCondition(orgDto));
    }

    /**
     * 获取所有的物业公司（直接跳过权限控制）
     * @param orgDto
     * @return
     */
    @GetMapping(value = "/getAllEstateOrgList")
    @Security(token = EstateSecurityToken.ESTATE_AGENCY_MANAGE,format = DataFormatEnum.JSON)
    public ResultBean<Organization> getAllEstateOrgList(OrgDto orgDto){
        orgDto.setPosition("0/1/");
        orgDto.setOrgType(OperationConstant.THREE);//物业（除去广告、内部机构类型）
        orgDto.setFlag(OperationConstant.ONE);//（除去小区、部门类型）
        return new ResultBean<>(ResultEnum.SUCCESS,this.orgFeign.selectListByCondition(orgDto));
    }

    /**
     * 功能描述: 根据位置查询所有社区机构
     * @param orgDto 机构业务对象
     * @return ResultBean<Organization>
     *
     *
     */
    @GetMapping(value = "/findAgencyListByCondition")
    @Security(format = DataFormatEnum.JSON)
    public ResultBean<Organization> findAgencyListByCondition(OrgDto orgDto){
//        if(null != orgDto.getPid()){
//            Organization organization = this.orgFeign.getOrgById(orgDto.getPid());
//            orgDto.setPosition(organization.getPosition());
//        }else{
//            Account onLineUser = this.securityServiceInterface.getOnLineUser();
//            orgDto.setPosition(onLineUser.getOrgPosition());
//        }
        orgDto.setFlag(OperationConstant.THREE);
        return new ResultBean<>(ResultEnum.SUCCESS,this.orgFeign.selectListByCondition(orgDto));
    }

    /**
     * 功能描述:导入社区
     * @param flag 0 社区
     * @return ModelAndView
     *
     *
     */
    @RequestMapping(value = "/indexImportExcel/{flag}")
    @Security(token = EstateSecurityToken.ESTATE_AGENCY_IMPORT,format = DataFormatEnum.VIEW)
    public ModelAndView indexImportExcel(@PathVariable(value = "flag")String flag) {
        if (null == flag){
            return new ModelAndView("common/404");
        }
        ModelAndView modelAndView = new ModelAndView("common/import-excel");
        modelAndView.addObject("flag",flag);
        return modelAndView;
    }


}
