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.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.AccessCardDto;
import com.sptg.estate.api.entity.*;
import com.sptg.estate.api.feigns.*;
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 feign.Param;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * title: AccessCardController
 * package: com.sptg.gateway.controller.estate
 * description: 卡管理 控制器
 *
 *
 *
 */
@RestController
@RequestMapping("/estate/accessCard")
@RequiredArgsConstructor
public class AccessCardController {

    private final AccessCardFeign accessCardFeign;
    private final OrgFeign orgFeign;
    private final ResidentialFeign residentialFeign;
    private final UnitFeign unitFeign;
    private final RoomFeign roomFeign;
    private final SecurityServiceInterface<Account> securityServiceInterface;
    private final SysOperationLogFeign sysOperationLogFeign;
    private final UserFeign userFeign;

    /**
     * 功能描述:卡管理页面初始化
     * @return ModelAndView
     *
     *
     */
    @GetMapping("/index")
    @Security(token = EstateSecurityToken.ESTATE_ACCESS_CARD_MANAGE,format = DataFormatEnum.VIEW)
    public ModelAndView index(){
        return new ModelAndView("estate/access-card-manage");
    }


    /**
     * 功能描述:卡管理列表查询
     * @param accessCardDto 卡管理业务对象
     * @return ResultBean<Page<AccessCard>>
     *
     *
     */
    @GetMapping(value = "/showAccessCardList")
    @Security(token = EstateSecurityToken.ESTATE_ACCESS_CARD_MANAGE,format = DataFormatEnum.JSON)
    public ResultBean<Page<AccessCard>> showAccessCardList(AccessCardDto accessCardDto, Page<AccessCard> page) {
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        Organization userOrg = this.orgFeign.getOrgById(onLineUser.getOrgId());
        if(null == accessCardDto.getSelectTreeId() || null == accessCardDto.getSelectTreeType()) {
            if (userOrg.getOrgType() == OperationConstant.THREE){
                //物业账号
                accessCardDto.setEstatePosition(onLineUser.getOrgPosition());
            }else{
                //机构账号
                accessCardDto.setOrgPosition(onLineUser.getOrgPosition());
            }
        }else{
            //选中的对象
            Organization organization = this.orgFeign.getOrgById(accessCardDto.getSelectTreeId());
            //1 机构 2 小区 3社区机构
            if(accessCardDto.getSelectTreeType() <= OperationConstant.THREE){
                if (accessCardDto.getSelectTreeType() == OperationConstant.ONE){
                    if (organization.getOrgType() == OperationConstant.THREE){
                        //物业
                        accessCardDto.setEstatePosition(organization.getPosition());
                    }else{
                        //机构
                        accessCardDto.setOrgPosition(organization.getPosition());
                    }
                }else if (accessCardDto.getSelectTreeType() == OperationConstant.TWO) {
                    //小区
                    if (userOrg.getOrgType() == OperationConstant.THREE){
                        //物业账号
                        accessCardDto.setEstatePosition(this.residentialFeign.findResidentialById(organization.getId()).getEstatePosition());
                    }else {
                        //机构账号
                        accessCardDto.setOrgPosition(this.residentialFeign.findResidentialById(organization.getId()).getEstatePosition());
                    }
                }else{
                    //社区机构
                }
            }
            //4 单元
            if(accessCardDto.getSelectTreeType() == OperationConstant.FOUR){
                if (userOrg.getOrgType() == OperationConstant.THREE){
                    //物业账号
                    accessCardDto.setEstatePosition(this.unitFeign.findUnitById(accessCardDto.getSelectTreeId()).getEstatePosition());
                }else{
                    //机构账号
                    accessCardDto.setOrgPosition(this.unitFeign.findUnitById(accessCardDto.getSelectTreeId()).getOrgPosition());
                }
            }
            //5 房间
            if(accessCardDto.getSelectTreeType() == OperationConstant.FIVE){
                if (userOrg.getOrgType() == OperationConstant.THREE){
                    //物业账号
                    accessCardDto.setEstatePosition(this.roomFeign.findRoomById(accessCardDto.getSelectTreeId()).getEstatePosition());
                }else{
                    //机构账号
                    accessCardDto.setOrgPosition(this.roomFeign.findRoomById(accessCardDto.getSelectTreeId()).getOrgPosition());
                }
            }
        }
        accessCardDto.setPage(page);
        return this.accessCardFeign.showAccessCardList(accessCardDto);
    }

    /**
     * 功能描述:新增页面初始化
     * @return ModelAndView
     *
     *
     */
    @GetMapping(value = "/add/{selectTreeId}/{selectTreeType}")
    @Security(token = EstateSecurityToken.ESTATE_ACCESS_CARD_ADD,format = DataFormatEnum.VIEW)
    public ModelAndView add(@PathVariable(value = "selectTreeId")String selectTreeId,@PathVariable(value = "selectTreeType")String selectTreeType){
        if("null".equals(selectTreeId) || "null".equals(selectTreeType)){
            return new ModelAndView("estate/access-card-add");
        }
        AccessCard accessCard = new AccessCard();
        //小区
        if(OperationConstant.TWO == Integer.parseInt(selectTreeType)){
            Residential residential = this.residentialFeign.findResidentialById(Long.parseLong(selectTreeId));
            accessCard.setType(OperationConstant.THREE);
            accessCard.setResidentialId(residential.getId());
            accessCard.setResidentialName(residential.getName());
        }
        //单元
        if(OperationConstant.FOUR == Integer.parseInt(selectTreeType)){
            Unit unit = this.unitFeign.findUnitById(Long.parseLong(selectTreeId));
            accessCard.setType(OperationConstant.TWO);
            accessCard.setUnitId(unit.getId());
            accessCard.setUnitName(unit.getName());
            accessCard.setResidentialId(unit.getResidentialId());
            accessCard.setResidentialName(unit.getResidentialName());
        }
        //房间
        if(OperationConstant.FIVE == Integer.parseInt(selectTreeType)){
            Room room = this.roomFeign.findRoomById(Long.valueOf(selectTreeId));
            accessCard.setType(OperationConstant.ONE);
            accessCard.setRoomId(room.getId());
            accessCard.setRoomName(room.getName());
            accessCard.setUnitId(room.getUnitId());
            accessCard.setUnitName(room.getUnitName());
            accessCard.setResidentialId(room.getResidentialId());
            accessCard.setResidentialName(room.getResidentialName());
        }
        ModelAndView  modelAndView = new ModelAndView("estate/access-card-add");
        modelAndView.addObject("accessCard",accessCard);
        modelAndView.addObject("selectTreeId",selectTreeId);
        modelAndView.addObject("flag",selectTreeType);
        return modelAndView;
    }

    /**
     * 功能描述:保存出入卡
     * @param accessCardDto 出入卡业务对象
     * @return ResultBean<Boolean>
     *
     *
     */
    @PostMapping(value = "/addAccessCard")
    @Security(token = EstateSecurityToken.ESTATE_ACCESS_CARD_ADD,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> addAccessCard(AccessCardDto accessCardDto){
        if(null == accessCardDto.getType() || null == accessCardDto.getResidentialId()){
            //  参数异常
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        Account onLineUser = this.securityServiceInterface.getOnLineUser();
        accessCardDto.setCreateAccountId(onLineUser.getId());
        List<AccessCard> list = this.accessCardFeign.getAccessCardListByCardNo(accessCardDto);
        if (list.size() > 0){
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        ResultBean<Boolean> resultBean=this.accessCardFeign.addAccessCard(accessCardDto);
        if(null != resultBean.getData() && resultBean.getData()){
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ESTATE_ACCESS_CARD_MANAGE, SysLogConstant.ADD_EVENT,
                    WebUtils.getIp(),accessCardDto,onLineUser,accessCardDto);
            sysOperationLogFeign.info(sysOperationLog);
            /*------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    /**
     * 功能描述: 编辑页面初始化
     * @param id 必填
     * @return ModelAndView
     *
     *
     */
    @GetMapping(value = "/edit/{id}")
    @Security(token = EstateSecurityToken.ESTATE_ACCESS_CARD_UPDATE,format = DataFormatEnum.VIEW)
    public ModelAndView edit(@PathVariable(value = "id")Long id){
        AccessCard accessCard =  this.accessCardFeign.findAccessCardById(id);
        if (null == accessCard){
            //  没有找到要修改的卡
            return new ModelAndView("common/404");
        }
        ModelAndView  modelAndView = new ModelAndView("estate/access-card-edit");
        modelAndView.addObject("accessCard",accessCard);
        return modelAndView;
    }

    /**
     * 功能描述:编辑出入卡
     * @param accessCardDto 出入卡业务对象
     * @return ResultBean<Boolean>
     *
     *
     */
    @PostMapping(value = "/updateAccessCard")
    @Security(token = EstateSecurityToken.ESTATE_ACCESS_CARD_UPDATE,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> updateAccessCard(AccessCardDto accessCardDto){
        if ( null == accessCardDto || null == accessCardDto.getId()){
            //  参数异常
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        AccessCard oldObj = this.accessCardFeign.findAccessCardById(accessCardDto.getId());
        ResultBean<Boolean> resultBean=this.accessCardFeign.updateAccessCard(accessCardDto);
        if(null != resultBean.getData() && resultBean.getData()){
            Account onLineUser = this.securityServiceInterface.getOnLineUser();
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            AccessCard newObj = this.accessCardFeign.findAccessCardById(accessCardDto.getId());
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ESTATE_ACCESS_CARD_MANAGE, SysLogConstant.ALTER_EVENT,
                    WebUtils.getIp(),accessCardDto,onLineUser,oldObj,newObj);
            sysOperationLogFeign.info(sysOperationLog);
            /*------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    /**
     * 功能描述:删除出入卡
     * @param accessCardDto 出入卡业务对象
     * @return ResultBean<Boolean>
     *
     *
     */
    @PostMapping(value = "/deleteAccessCard")
    @Security(token = EstateSecurityToken.ESTATE_ACCESS_CARD_DELETE,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> deleteAccessCard(AccessCardDto accessCardDto){
        if ( null == accessCardDto || null == accessCardDto.getId()){
            //  参数异常
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        AccessCard oldObj = this.accessCardFeign.findAccessCardById(accessCardDto.getId());
        ResultBean<Boolean> resultBean=this.accessCardFeign.deleteAccessCard(accessCardDto);
        if(null != resultBean.getData() && resultBean.getData()){
            Account onLineUser = this.securityServiceInterface.getOnLineUser();
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ESTATE_ACCESS_CARD_MANAGE, SysLogConstant.DELETE_EVENT,
                    WebUtils.getIp(),accessCardDto,onLineUser,oldObj);
            sysOperationLogFeign.info(sysOperationLog);
            /*------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    /**
     * 功能描述:批量删除卡
     * @param ids id集合
     * @return ResultBean<Boolean>
     *
     *
     */
    @PostMapping(value = "/deleteCardList")
    @Security(token = EstateSecurityToken.ESTATE_ACCESS_CARD_DELETE,format = DataFormatEnum.JSON)
    public ResultBean<Boolean> deleteCardList(@RequestBody List<String> ids){
        if (null == ids || ids.size() <=0){
            //  参数异常
            return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY);
        }
        AccessCardDto accessCardDto = new AccessCardDto();
        accessCardDto.setIds(ids);
        ResultBean<Boolean> resultBean = this.accessCardFeign.deleteCardList(accessCardDto);
        if(null != resultBean.getData() && resultBean.getData()){
            Account onLineUser = this.securityServiceInterface.getOnLineUser();
            /*---------------------------------------------------记录日志--------------------------------------------------------*/
            SysOperationLog sysOperationLog=new SysOperationLog(SysLogMenuConstant.ESTATE_ACCESS_CARD_MANAGE, SysLogConstant.DELETE_EVENT,
                    WebUtils.getIp(),accessCardDto,onLineUser);
            sysOperationLogFeign.info(sysOperationLog);
            /*------------------------------------------------------------------------------------------------------------------*/
        }
        return resultBean;
    }

    /**
     * 功能描述:导入卡管理
     * @param flag 6 住户卡
     * @return ModelAndView
     *
     *
     */
    @RequestMapping(value = "/indexImportExcel/{flag}")
    @Security(token = EstateSecurityToken.ESTATE_ACCESS_CARD_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;
    }

    /**
     * 功能描述:导出卡管理
     * @param response
     *
     *
     */
    @RequestMapping(value = "/exportAccessCard")
    @Security(token = EstateSecurityToken.ESTATE_ACCESS_CARD_EXPORT)
    public void exportAccessCard(HttpServletResponse response) {
        try {
            response.sendRedirect("/common/excel/exportExcel/9");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *根据门禁卡号码查询卡信息
     * @param accessCardDto
     * @return
     */
    @RequestMapping(value = "/getAccessCardByCardNo")
    @Security(token = EstateSecurityToken.ESTATE_ACCESS_CARD_MANAGE,format = DataFormatEnum.JSON)
    public ResultBean<AccessCard> getAccessCardByCardNo(AccessCardDto accessCardDto){
        accessCardDto.setCardNo(accessCardDto.getCardNo());
        accessCardDto.setResidentialId(accessCardDto.getResidentialId());
        List<AccessCard> cardList = this.accessCardFeign.getAccessCardListByCardNo(accessCardDto);
        AccessCard accessCard = null;
        if (cardList != null && cardList.size() > 0){
            accessCard = cardList.get(0);
        }
        return new ResultBean<>(ResultEnum.SUCCESS,accessCard);
    }

    /**
     * 不记名登记转记名登记
     * @param cardNo
     * @return
     */
    @GetMapping(value = "/realNameRegIndex/{cardNo}/{residentialId}")
    @Security(token = EstateSecurityToken.ESTATE_ACCESS_CARD_UPDATE)
    public ModelAndView realNameRegIndex(@PathVariable(value = "cardNo") String cardNo, @PathVariable(value = "residentialId") Long residentialId){
        ModelAndView modelAndView = new ModelAndView("estate/real-name-registration");
        modelAndView.addObject("cardNo",cardNo);
        modelAndView.addObject("residentialId",residentialId);
        return modelAndView;
    }

    @PostMapping(value = "/realNameReg")
    public ResultBean<Boolean> realNameReg(@Param("userId") Long userId, @Param("cardNo") String cardNo, @Param("residentialId") Long residentialId){
        ResultBean<Boolean> bean = null;
        AccessCardDto accessCardDto = new AccessCardDto();
        accessCardDto.setType(OperationConstant.ZERO);
        accessCardDto.setUserId(userId.toString());
        accessCardDto.setResidentialId(residentialId);
        List<AccessCard> accessCardList = accessCardFeign.getAccessCardByUserIdAndType(accessCardDto);
        //size > 0 修改用户原本绑定的卡号
        if (accessCardList.size() > 0) {
            AccessCard accessCard = accessCardList.get(0);
            accessCard.setCardNo("");
            AccessCardDto dto = new AccessCardDto();
            BeanUtils.copyProperties(accessCard, dto);
            bean = accessCardFeign.updateAccessCard(dto);
        }
        if (accessCardList.size() == 0 || bean.getData()) {
            AccessCardDto cardDto = new AccessCardDto();
            cardDto.setResidentialId(residentialId);
            cardDto.setCardNo(cardNo);
            List<AccessCard> cardList = accessCardFeign.getAccessCardListByCardNo(cardDto);
            if (cardList.size() > 0){
                AccessCard card = cardList.get(0);
                User user = userFeign.findUserById(userId);
                card.setUserId(userId.toString());
                card.setUserName(user.getName());
                card.setUnitId(user.getUnitId());
                card.setUnitName(user.getUnitName());
                card.setRoomId(user.getRoomId());
                card.setRoomName(user.getRoomName());
                card.setType(OperationConstant.ZERO);
                AccessCardDto dto = new AccessCardDto();
                BeanUtils.copyProperties(card,dto);
                bean = accessCardFeign.updateAccessCardByCardNo(dto);
            }else {
                return new ResultBean<>(ResultEnum.ERROR);
            }
        }
        return bean;
//        if (accessCardList.size() > 0){
//            AccessCard accessCard = accessCardList.get(0);
//            accessCard.setCardNo("");
//            AccessCardDto dto = new AccessCardDto();
//            BeanUtils.copyProperties(accessCard,dto);
//            ResultBean<Boolean> b = accessCardFeign.updateAccessCard(dto);
//            if (b.getData()){
//                AccessCardDto cardDto = new AccessCardDto();
//                cardDto.setResidentialId(residentialId);
//                cardDto.setCardNo(cardNo);
//                List<AccessCard> cardList = accessCardFeign.getAccessCardListByCardNo(cardDto);
//                if (cardList.size() > 0){
//                    AccessCard card = cardList.get(0);
//                    User user = userFeign.findUserById(userId);
//                    card.setUserId(userId.toString());
//                    card.setUserName(user.getName());
//                    card.setUnitId(user.getUnitId());
//                    card.setUnitName(user.getUnitName());
//                    card.setRoomId(user.getRoomId());
//                    card.setRoomName(user.getRoomName());
//                    AccessCardDto accessCardDto1 = new AccessCardDto();
//                    BeanUtils.copyProperties(card,accessCardDto1);
//                    bean = accessCardFeign.updateAccessCard(accessCardDto1);
//                }else {
//                    return new ResultBean<>(ResultEnum.ERROR);
//                }
//            }else {
//                return new ResultBean<>(ResultEnum.ERROR);
//            }
//        }else {
//            //直接绑定用户
//            AccessCardDto cardDto = new AccessCardDto();
//            cardDto.setResidentialId(residentialId);
//            cardDto.setCardNo(cardNo);
//            List<AccessCard> cardList = accessCardFeign.getAccessCardListByCardNo(cardDto);
//            if (cardList.size() > 0){
//                AccessCard card = cardList.get(0);
//                User user = userFeign.findUserById(userId);
//                card.setUserId(userId.toString());
//                card.setUserName(user.getName());
//                card.setUnitId(user.getUnitId());
//                card.setUnitName(user.getUnitName());
//                card.setRoomId(user.getRoomId());
//                card.setRoomName(user.getRoomName());
//                AccessCardDto accessCardDto1 = new AccessCardDto();
//                BeanUtils.copyProperties(card,accessCardDto1);
//                bean = accessCardFeign.updateAccessCard(accessCardDto1);
//            }else {
//                return new ResultBean<>(ResultEnum.ERROR);
//            }
//        }
//        return bean;
    }
}
