package com.sptg.gateway.controller.estate;

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.constant.SysLogConstant;
import com.sptg.common.core.util.JsonUtils;
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.ApplyUserDto;
import com.sptg.estate.api.entity.ApplyUser;
import com.sptg.estate.api.feigns.*;
import com.sptg.gateway.controller.permissions.DictManageController;
import com.sptg.permissions.api.entity.Account;
import com.sptg.permissions.api.entity.ApiLog;
import com.sptg.permissions.api.entity.Dict;
import com.sptg.permissions.api.entity.Organization;
import com.sptg.permissions.api.feigns.ConfFeign;
import com.sptg.permissions.api.feigns.DictFeign;
import com.sptg.permissions.api.feigns.OrgFeign;
import com.sptg.permissions.api.feigns.SysApiLogFeign;
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 lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;

/**
 * title: ApplyUserController
 * package: com.sptg.estate.biz.security
 * description: 住户认证管理--控制器
 *
 *
 *
 */
@RestController
@RequestMapping("/apply/user")
@RequiredArgsConstructor
@Slf4j
public class ApplyUserController {

    private final ApplyUserFeign applyUserFeign;
    private final SecurityServiceInterface<Account> securityServiceInterface;
    private final SysOperationLogFeign sysOperationLogFeign;
    private final ConfFeign confFeign;
    private final OrgFeign orgFeign;

    private final UnitFeign unitFeign;
    private final RoomFeign roomFeign;
    private final ResidentialFeign residentialFeign;
    private final DictFeign dictFeign;
    private final GridEstateFeign gridEstateFeign;
    /**
     * 功能描述:住户认证管理页面
     * @param
     * @return
     *
     *
     */
    @GetMapping("/index")
    @Security(token = EstateSecurityToken.APPLY_USER_MANAGE,format = DataFormatEnum.VIEW)
    public ModelAndView index(@Param("checkState") Integer checkState){
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        ModelAndView modelAndView = new ModelAndView("estate/apply-user-manage");
        modelAndView.addObject("checkState", checkState);
        modelAndView.addObject("onLineUser",onLineUser);
        return modelAndView;
    }

    /**
     * 查询住户认证列表(分页)
     * @param applyUserDto 查询条件参数
     * @param page 分页参数
     * @return
     *
     *
     */
    @PostMapping(value = "/showApplyUserList")
    @Security(token = EstateSecurityToken.APPLY_USER_MANAGE,format = DataFormatEnum.JSON)
    public ResultBean<Page<ApplyUser>> showApplyUserList(ApplyUserDto applyUserDto, Page<ApplyUser> page){
        //当前
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        Organization userOrg = this.orgFeign.getOrgById(onLineUser.getOrgId());
        if(applyUserDto.getSelectTreeId()==null ||  null == applyUserDto.getSelectTreeType()) {
            if (userOrg.getOrgType() == OperationConstant.THREE){
                //物业账号
                applyUserDto.setEstatePosition(onLineUser.getOrgPosition());
            }else{
                //机构账号
                applyUserDto.setOrgPosition(onLineUser.getOrgPosition());
            }
        }else{
            //1 机构 2 小区 3社区机构
            Organization organization = this.orgFeign.getOrgById(applyUserDto.getSelectTreeId());
            if(applyUserDto.getSelectTreeType() <= OperationConstant.THREE){
                if (applyUserDto.getSelectTreeType() == OperationConstant.ONE){
                    if (organization.getOrgType() == OperationConstant.THREE){
                        //物业
                        applyUserDto.setEstatePosition(organization.getPosition());
                    }else{
                        //机构
                        applyUserDto.setOrgPosition(organization.getPosition());
                    }
                }
                if (applyUserDto.getSelectTreeType() == OperationConstant.TWO){
                    //小区
                    //物业账号
                    if (userOrg.getOrgType() == OperationConstant.THREE) {
                        applyUserDto.setEstatePosition(this.residentialFeign.findResidentialById(organization.getId()).getEstatePosition());
                    } else{
                        //机构账号
                        applyUserDto.setOrgPosition(organization.getPosition());
                    }
                }
            }
            //4 单元
            if(applyUserDto.getSelectTreeType() == OperationConstant.FOUR){
                if (userOrg.getOrgType() == OperationConstant.THREE){
                    applyUserDto.setEstatePosition(this.unitFeign.findUnitById(applyUserDto.getSelectTreeId()).getEstatePosition());
                }else{
                    applyUserDto.setOrgPosition(this.unitFeign.findUnitById(applyUserDto.getSelectTreeId()).getOrgPosition());
                }
            }
            //5 房间
            if(applyUserDto.getSelectTreeType() == OperationConstant.FIVE){
                if (userOrg.getOrgType() == OperationConstant.THREE){
                    applyUserDto.setEstatePosition(this.roomFeign.findRoomById(applyUserDto.getSelectTreeId()).getEstatePosition());
                }else{
                    applyUserDto.setOrgPosition(this.roomFeign.findRoomById(applyUserDto.getSelectTreeId()).getOrgPosition());
                }
            }
        }
        applyUserDto.setPage(page);
        return this.applyUserFeign.showApplyUserList(applyUserDto);
    }

    /**
     * 功能描述:认证审核页面
     * @param id 申请记录Id 必填
     * @return ModelAndView
     *
     *
     */
    @GetMapping("/checkView/{id}")
    @Security(token = EstateSecurityToken.APPLY_USER_MANAGE,format = DataFormatEnum.VIEW)
    public ModelAndView checkView(@PathVariable(value = "id")Long id){
        ApplyUser applyUser = this.applyUserFeign.getApplyUserById(id);
        ModelAndView modelAndView = new ModelAndView("estate/apply-user-check");
        modelAndView.addObject("applyUser", applyUser);
        modelAndView.addObject("fastDfsServer",this.confFeign.getFileServerHost());
        List<Dict> sexDict = this.dictFeign.getByCode("sex").getList();
        List<Dict> userTypeDict = this.dictFeign.getByCode("userType").getList();
        List<Dict> nationalityDict = this.dictFeign.getByCode("nationality").getList();
        modelAndView.addObject("sexDict",sexDict);
        modelAndView.addObject("userTypeDict",userTypeDict);
        modelAndView.addObject("nationalityDict",nationalityDict);
        return modelAndView;
    }

    /**
     * 功能描述:审核
     * @param applyUser{
     *                 id : 1  记录id,
     *                 checkState : 1  审核状态,
     *                 checkOpinion :  审核意见--审核不通过时有值
     *          }
     * @return ModelAndView
     *
     *
     */
    @PostMapping("/updateCheckState")
    @Security(token = EstateSecurityToken.APPLY_USER_AUDIT,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> updateCheckState(ApplyUser applyUser){
        log.warn("============================小程序小程序/后台(/apply/user/updateCheckState)请求数据==============================");
        log.warn(JsonUtils.objectToJson(applyUser));
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        //审核人类型：1-业主，2-后台
        ApplyUser oldObj = this.applyUserFeign.getApplyUserById(applyUser.getId());
        applyUser.setOperatorType(OperationConstant.TWO);
        applyUser.setOperatorName(onLineUser.getUserName());
        ResultBean<Boolean> resultBean = this.applyUserFeign.updateCheckState(applyUser);

        if(resultBean.getData()!=null && resultBean.getData()){
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.APPLY_USER_MANAGE, SysLogConstant.ALTER_EVENT,
                    WebUtils.getIp(),applyUser,onLineUser,oldObj,applyUser);
            sysOperationLogFeign.info(sysOperationLog);

            /*---------------------------------------------------人脸下发到设备----------------------------------------------------*/

            /*------------------------------------------------------------------------------------------------------------------*/
            /*---------------------------------------------------推送到网格--------------------------------------------------------*/
            ApplyUser newObj = this.applyUserFeign.getApplyUserById(applyUser.getId());
            ResultBean<String> stringResultBean = this.gridEstateFeign.gridUserPush(newObj);

            if(stringResultBean !=null &&stringResultBean.getData()!=null&&stringResultBean.getData().equals("操作成功")){
                SysOperationLog sysOperationLog1=new SysOperationLog("推送住户审核数据到网格成功", SysLogConstant.ADD_EVENT,
                        WebUtils.getIp(),applyUser,onLineUser,newObj,applyUser);
                sysOperationLogFeign.info(sysOperationLog1);
            }else{
                SysOperationLog sysOperationLog1=new SysOperationLog("推送住户审核数据到网格失败", SysLogConstant.ADD_EVENT,
                        WebUtils.getIp(),applyUser,onLineUser,applyUser);
                sysOperationLogFeign.info(sysOperationLog1);
            }
            return new ResultBean<>(ResultEnum.SUCCESS);
            /*------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    /**
     * 功能描述:详情
     * @param id 记录id
     * @return ModelAndView
     *
     *
     */
    @GetMapping("/detail/{id}")
    @Security(token = EstateSecurityToken.APPLY_USER_MANAGE,format = DataFormatEnum.VIEW)
    public ModelAndView detail(@PathVariable(value = "id")Long id){
        ApplyUser applyUser = this.applyUserFeign.getApplyUserById(id);
        ModelAndView modelAndView = new ModelAndView("estate/apply-user-detail");
        modelAndView.addObject("applyUser", applyUser);
        modelAndView.addObject("fastDfsServer",this.confFeign.getFileServerHost());
        List<Dict> sexDict = this.dictFeign.getByCode("sex").getList();
        List<Dict> userTypeDict = this.dictFeign.getByCode("userType").getList();
        List<Dict> nationalityDict = this.dictFeign.getByCode("nationality").getList();
        modelAndView.addObject("sexDict",sexDict);
        modelAndView.addObject("userTypeDict",userTypeDict);
        modelAndView.addObject("nationalityDict",nationalityDict);
        return modelAndView;
    }
}
