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.entity.DispatchTask;
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.device.api.feigns.DeviceFeign;
import com.sptg.estate.api.constant.EstateSecurityToken;
import com.sptg.estate.api.dto.AccessRecordsDto;
import com.sptg.estate.api.dto.GuestAuthorizeDto;
import com.sptg.estate.api.entity.AccessRecords;
import com.sptg.estate.api.entity.GuestAuthorize;
import com.sptg.estate.api.feigns.AccessRecordsFeign;
import com.sptg.estate.api.feigns.GuestAuthorizeFeign;
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 lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * title: GuestAuthorizeController
 * package: com.sptg.gateway.controller.estate
 * description: 访客授权记录 控制器
 *
 *             
 *                 
 */
@RequestMapping("/estate/guestAuthorize")
@RestController
@RequiredArgsConstructor
public class GuestAuthorizeController {

    private final OrgFeign orgFeign;
    private final GuestAuthorizeFeign guestAuthorizeFeign;
    private final SecurityServiceInterface<Account> securityServiceInterface;
    private final SysOperationLogFeign sysOperationLogFeign;
    private final DeviceFeign deviceFeign;
    private final AccessRecordsFeign accessRecordsFeign;


    /**
     * 功能描述:访客授权记录页面初始化
     * @return ModelAndView
     *             
     *                       
     */
    @GetMapping("/index")
    @Security(token = EstateSecurityToken.ESTATE_GUEST_AUTHORIZE_MANAGE,format = DataFormatEnum.VIEW)
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView("estate/guest-authorize-manage");
        return modelAndView;
    }

    /**
     * 功能描述:访客授权记录列表查询
     * @param dto 访客授权记录业务对象（含查询条件）
     * @param page 分页条件
     * @return ResultBean<Page<GuestAuthorize>>
     *             
     *                       
     */
    @GetMapping(value = "/showGuestAuthorizeList")
    @Security(token = EstateSecurityToken.ESTATE_GUEST_AUTHORIZE_MANAGE,format = DataFormatEnum.JSON)
    public ResultBean<Page<GuestAuthorize>> showGuestAuthorizeList(GuestAuthorizeDto dto, Page<GuestAuthorize> page) {
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        Organization userOrg = this.orgFeign.getOrgById(onLineUser.getOrgId());
        if (userOrg.getOrgType() == OperationConstant.THREE){
            //物业
            dto.setEstatePosition(onLineUser.getOrgPosition());
        }else{
            //机构
            dto.setOrgPosition(onLineUser.getOrgPosition());
        }
        dto.setPage(page);
        Page<GuestAuthorize> resultPage = this.guestAuthorizeFeign.showGuestAuthorizeList(dto);
        return new ResultBean<>(ResultEnum.SUCCESS,resultPage);
    }

    /**
     * 功能描述:密码失效
     * @param g 访客授权记录业务对象
     * @return ResultBean<Boolean>
     *             
     *                       
     */
    @PostMapping(value = "/updateGuestAuthorizeEnableType")
    @Security(token = EstateSecurityToken.ESTATE_GUEST_AUTHORIZE_INVALID,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> updateGuestAuthorizeEnableType(GuestAuthorize g){
        if ( null == g || null == g.getId()){
            //  参数异常
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        g.setEnableType(OperationConstant.ONE);
        ResultBean<Boolean> resultBean=this.guestAuthorizeFeign.updateGuestAuthorizeEnableType(g);
        if(null != resultBean.getData() && resultBean.getData()){
            GuestAuthorize guestAuthorize = this.guestAuthorizeFeign.findGuestAuthorizeById(Long.valueOf(g.getId()));
            //密码删除动作
            DispatchTask dispatchTask = new DispatchTask();
            dispatchTask.setXqId(guestAuthorize.getResidentialId());
            dispatchTask.setUnitId(guestAuthorize.getUnitId());
            dispatchTask.setData(guestAuthorize);
            Map<String,String> logMap = new HashMap<>();
            //小区
            if (!StringUtils.isEmpty(guestAuthorize.getResidentialName())){
                logMap.put("xqName",guestAuthorize.getResidentialName());
            }else {
                logMap.put("xqName",null);
            }
            //单元
            if (!StringUtils.isEmpty(guestAuthorize.getUnitName())){
                logMap.put("unitName",guestAuthorize.getUnitName());
            }else {
                logMap.put("unitName",null);
            }
            //房间
            if (!StringUtils.isEmpty(guestAuthorize.getRoomName())){
                logMap.put("roomName",guestAuthorize.getRoomName());
            }else {
                logMap.put("roomName",null);
            }
            //用户名
            if (!StringUtils.isEmpty(guestAuthorize.getUserName())){
                logMap.put("userName",guestAuthorize.getUserName());
            }else {
                logMap.put("userName",null);
            }
            //密码
            if (null != guestAuthorize.getPassword()){
                logMap.put("password",guestAuthorize.getPassword().toString());
            }else {
                logMap.put("password",null);
            }
            //有效期开始时间
            SimpleDateFormat format = new SimpleDateFormat();
            if (null != guestAuthorize.getBeginDate()){
                logMap.put("beginTime",format.format(guestAuthorize.getBeginDate()));
            }else {
                logMap.put("beginTime",null);
            }
            //有效期结束时间
            if (null != guestAuthorize.getEndDate()){
                logMap.put("endTime",format.format(guestAuthorize.getEndDate()));
            }else {
                logMap.put("endTime",null);
            }
            this.deviceFeign.removeOpenDoorPwd(dispatchTask,logMap);
            Account onLineUser = this.securityServiceInterface.getOnLineUser();
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ESTATE_GUEST_AUTHORIZE_MANAGE, SysLogConstant.ALTER_EVENT,
                    WebUtils.getIp(),"更新访客授权状态",guestAuthorize,onLineUser);
            sysOperationLogFeign.info(sysOperationLog);
            /*------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    @RequestMapping("/accessRecords/{id}")
    @Security(token = EstateSecurityToken.ESTATE_GUEST_AUTHORIZE_RECORDS)
    public ModelAndView accessRecords(@PathVariable(value = "id") Long id){
        ModelAndView modelAndView = new ModelAndView("estate/guest-authorize-records");
        modelAndView.addObject("id",id);
        return modelAndView;
    }

    @GetMapping("/showAccessRecordsList")
    @Security(token = EstateSecurityToken.ESTATE_GUEST_AUTHORIZE_RECORDS,format = DataFormatEnum.JSON)
    public ResultBean<Page<AccessRecords>> showAccessRecordsList(AccessRecordsDto accessRecordsDto, Page<AccessRecords> page){
        ResultBean<Page<AccessRecords>> pageResultBean;
        GuestAuthorize guestAuthorize = guestAuthorizeFeign.findGuestAuthorizeById(accessRecordsDto.getGuestAuthorizeId());
        accessRecordsDto.setOpenDoorType(OperationConstant.ONE);
        accessRecordsDto.setPage(page);
        if (null != guestAuthorize.getPassword()){
            accessRecordsDto.setAccessCardNo(guestAuthorize.getPassword().toString());
        }
        if (null != guestAuthorize.getResidentialId()){
            accessRecordsDto.setResidentialId(guestAuthorize.getResidentialId());
        }
        if (null != guestAuthorize.getBeginDate()){
            accessRecordsDto.setBeginDate(guestAuthorize.getBeginDate());
        }
        if (null != guestAuthorize.getEndDate()){
            accessRecordsDto.setEndDate(guestAuthorize.getEndDate());
        }
        pageResultBean = accessRecordsFeign.getAccessRecordsList(accessRecordsDto);
        if (pageResultBean.getData().getRecords().size() > 0){
            pageResultBean.getData().getRecords().forEach(accessRecords -> {
                accessRecords.setResidentialName(guestAuthorize.getResidentialName());
                accessRecords.setUnitName(guestAuthorize.getUnitName());
                accessRecords.setRoomName(guestAuthorize.getRoomName());
            });
        }
        return pageResultBean;
    }
}
