package com.sptg.estate.biz.controller;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
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.device.api.entity.Device;
import com.sptg.estate.api.dto.AccessCardDto;
import com.sptg.estate.api.entity.AccessCard;
import com.sptg.estate.api.feigns.AccessCardFeign;
import com.sptg.estate.api.vo.DevicesAccessPushVO;
import com.sptg.estate.biz.service.AccessCardServiceInterface;
import io.lettuce.core.dynamic.annotation.Param;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * title: UserCardController
 * package: com.sptg.estate.biz.controller
 * description: 门禁卡 控制器
 *
 *
 *
 */
@RestController
public class AccessCardController implements AccessCardFeign {

    private final AccessCardServiceInterface accessCardServiceInterface;

    @Autowired
    public AccessCardController(AccessCardServiceInterface accessCardServiceInterface) {
        this.accessCardServiceInterface = accessCardServiceInterface;
    }

    @Override
    @PostMapping(value = "/accessCard/showAccessCardList")
    public ResultBean<Page<AccessCard>> showAccessCardList(@RequestBody AccessCardDto accessCardDto) {
        return this.accessCardServiceInterface.showAccessCardList(accessCardDto);
    }

    @Override
    @PostMapping(value = "/accessCard/showCardList")
    public ResultBean<Page<AccessCard>> showCardList(@RequestBody AccessCardDto accessCardDto){
        return this.accessCardServiceInterface.showCardList(accessCardDto);
    }

    @Override
    @PostMapping(value = "/accessCard/addAccessCard")
    public ResultBean<Boolean> addAccessCard(@RequestBody AccessCardDto accessCardDto) {
        return this.accessCardServiceInterface.addAccessCard(accessCardDto);
    }

    /**
     * 批量下发导入的门禁卡
     * @param accessCardDtoList 住户卡业务对象
     * @return
     */
    @Override
    @PostMapping(value = "/accessCard/addAccessCardBatch")
    public ResultBean<Boolean> pushAccessCardBatch(@RequestBody List<AccessCardDto> accessCardDtoList) {
        return this.accessCardServiceInterface.pushAccessCardBatch(accessCardDtoList);
    }

    @Override
    @GetMapping(value = "/accessCard/findAccessCardById/{id}")
    public AccessCard findAccessCardById(@PathVariable(value = "id") Long id) {
        return this.accessCardServiceInterface.findAccessCardById(id);
    }

    @Override
    @PostMapping(value = "/accessCard/updateAccessCard")
    public ResultBean<Boolean> updateAccessCard(@RequestBody AccessCardDto accessCardDto) {
        return this.accessCardServiceInterface.updateAccessCard(accessCardDto);
    }

    @Override
    @PostMapping(value = "/accessCard/deleteAccessCard")
    public ResultBean<Boolean> deleteAccessCard(@RequestBody AccessCardDto accessCardDto) {
        return this.accessCardServiceInterface.deleteAccessCard(accessCardDto);
    }

    @Override
    @PostMapping(value = "/accessCard/deleteCardList")
    public ResultBean<Boolean> deleteCardList(@RequestBody AccessCardDto accessCardDto) {
        try {
            return this.accessCardServiceInterface.deleteCardList(accessCardDto);
        } catch (Exception e) {
            if(StringUtils.isBlank(e.getMessage())){
                return new ResultBean<>(ResultEnum.ERROR);
            }else{
                return  new ResultBean<>("500",e.getMessage());
            }
        }
    }

    @Override
    @PostMapping(value = "/accessCard/findAccessCardByCondition")
    public List<AccessCard> findAccessCardByCondition( @RequestBody AccessCardDto accessCardDto) {
        return this.accessCardServiceInterface.findAccessCardByCondition(accessCardDto);
    }

    @Override
    @PostMapping(value = "/accessCard/findAccessCardListByCardNo")
    public List<AccessCard> getAccessCardListByCardNo(@RequestBody AccessCardDto accessCardDto){
        return this.accessCardServiceInterface.getAccessCardListByCardNo(accessCardDto);
    }

    @Override
    @PostMapping(value = "/accessCard/getAccessCardListByCardIds")
    public List<AccessCard> getAccessCardListByCardIds(@RequestBody AccessCardDto accessCardDto) {
        List<String> ids = accessCardDto.getIds();
        Assert.notEmpty(ids, "请勾选门禁卡删除");
        List<Long> collect = ids.stream().map(id -> Long.parseLong(id)).collect(Collectors.toList());
        return this.accessCardServiceInterface.selectBatchIds(collect);
    }

    @Override
    @PostMapping(value = "/accessCard/pagingQuery")
    public Page<AccessCard> pagingQuery(@RequestBody PageBean<AccessCard, Device> pageBean) {
        Wrapper<AccessCard> wrapper = new EntityWrapper<>();
        //  过滤已删除的卡号
        wrapper.notIn("i_status", OperationConstant.MINUS_ONE);
        //  过滤已过期的卡号
        wrapper.gt("t_end_date",new Date());
        //  获取此设备的服务人群卡号（该单元或小区下的住户或服务人员）
        Device device = pageBean.getDto();
        String sql = "( s_org_position like {0} or (i_type = 4 and l_residential_id = {1} ))";
        //  获取该小区的服务人员卡号
        wrapper.and(sql,device.getOrgPosition() + "%",device.getXqId());
        return this.accessCardServiceInterface.selectPage(pageBean,wrapper);
    }

    @Override
    @PostMapping(value = "/accessCard/enable/pagingQuery")
    public Page<AccessCard> enablePagingQuery(@RequestBody PageBean<AccessCard, Device> pageBean) {
        Wrapper<AccessCard> wrapper = new EntityWrapper<>();
        wrapper.notIn("i_status", OperationConstant.MINUS_ONE);
        wrapper.eq("i_card_enable", OperationConstant.ONE);
        wrapper.gt("t_end_date",new Date());
        Device device = pageBean.getDto();
        String sql = "( s_org_position like {0} or (i_type = 4 and l_residential_id = {1} ))";
        wrapper.and(sql,device.getOrgPosition() + "%",device.getXqId());
        return this.accessCardServiceInterface.selectPage(pageBean,wrapper);
    }
    @Override
    @PostMapping(value = "/accessCard/addOrUpdateUserCard")
    public ResultBean<Boolean> addOrUpdateUserCard(@RequestBody AccessCardDto accessCardDto) {
        return this.accessCardServiceInterface.addOrUpdateUserCard(accessCardDto);
    }


    /**
     * 门禁卡新增或编辑(只保存卡设置，不下发到设备)
     * @param accessCardDto 门禁卡业务对象
     * @return
     */
    @Override
    @PostMapping(value = "/accessCard/simpleAddOrUpdateUserCard")
    public ResultBean<AccessCardDto> simpleAddOrUpdateUserCard(@RequestBody AccessCardDto accessCardDto) {
        return this.accessCardServiceInterface.simpleAddOrUpdateUserCard(accessCardDto);
    }

    /**
     * 功能描述:执行下发门禁卡（启用或者禁用）
     * @param devicesAccessPushVO 住户门禁卡下发设备对象
     * @return ResultBean<Boolean>
     *
     *
     */
    @Override
    @PostMapping("/accessCard/sendAccessUserCard")
    public ResultBean<Boolean> sendAccessUserCard(@RequestBody DevicesAccessPushVO devicesAccessPushVO){
        return this.accessCardServiceInterface.sendAccessUserCard(devicesAccessPushVO);
    }

    @Override
    @PostMapping(value = "/accessCard/getAccessCardByUserIdAndType")
    public List<AccessCard> getAccessCardByUserIdAndType(@RequestBody AccessCardDto accessCardDto) {
        return this.accessCardServiceInterface.getAccessCardByUserIdAndType(accessCardDto.getUserId(),accessCardDto.getType());
    }

    @Override
    @PostMapping(value = "/accessCard/findListByPosition")
    public ResultBean<AccessCard> findListByPosition(@RequestBody AccessCardDto accessCardDto) {
        return this.accessCardServiceInterface.findListByPosition(accessCardDto);
    }

    @Override
    @PostMapping(value = "/accessCard/importAccessCardList")
    public ResultBean<Boolean> importAccessCardList(@RequestBody List<AccessCard> list) {
        return this.accessCardServiceInterface.importAccessCardList(list);
    }

    @Override
    @GetMapping(value = "/accessCard/getByOldId/{oldId}")
    public AccessCard getByOldId(@PathVariable(value = "oldId") String oldId) {
        Wrapper<AccessCard> wrapper = new EntityWrapper<>();
        wrapper.eq("old_id",oldId);
        return this.accessCardServiceInterface.selectOne(wrapper);
    }

    @Override
    @GetMapping(value = "/accessCard/getCardByCardNo/{cardNo}")
    public AccessCard getCardByCardNo(@PathVariable(value = "cardNo") String cardNo) {
        Wrapper<AccessCard> wrapper = new EntityWrapper<>();
        wrapper.eq("s_card_no",cardNo);
        wrapper.eq("i_status",OperationConstant.ZERO);
        return this.accessCardServiceInterface.selectOne(wrapper);
    }

    @Override
    @PostMapping(value = "/accessCard/getListByCardNoAndDate")
    public List<AccessCard> getListByCardNoAndDate(@RequestBody AccessCardDto accessCardDto) {
        Wrapper<AccessCard> wrapper = new EntityWrapper<>();
        wrapper.eq("i_status",OperationConstant.ZERO);
        //根据机构
        wrapper.like(StringUtils.isNotBlank(accessCardDto.getOrgPosition()),"s_org_position", accessCardDto.getOrgPosition(), SqlLike.RIGHT);
        //根据物业
        wrapper.like(StringUtils.isNotBlank(accessCardDto.getEstatePosition()),"s_estate_position", accessCardDto.getEstatePosition(), SqlLike.RIGHT);
        //根据卡号
        wrapper.like(accessCardDto.getCardNo() != null,"s_card_no",accessCardDto.getCardNo(), SqlLike.DEFAULT);
        //根据有效期
        wrapper.ge(accessCardDto.getBeginDate() != null,"t_begin_date",accessCardDto.getBeginDate());
        wrapper.le(accessCardDto.getEndDate() != null,"t_end_date",accessCardDto.getEndDate());

        if (null != accessCardDto.getType()){
            wrapper.eq("i_type",accessCardDto.getType());
        }
        return this.accessCardServiceInterface.selectList(wrapper);
    }

    @Override
    @PostMapping("/accessCard/updateAccessCardByCardNo")
    public ResultBean<Boolean> updateAccessCardByCardNo(@RequestBody AccessCardDto accessCardDto){
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("s_card_no",accessCardDto.getCardNo());
        wrapper.eq("l_residential_id",accessCardDto.getResidentialId());
        return new ResultBean<>(ResultEnum.SUCCESS,this.accessCardServiceInterface.update(accessCardDto,wrapper));
    }

    @Override
    @GetMapping("/accessCard/updateBlackCard/{id}")
    public ResultBean<Boolean> updateBlackCard(@PathVariable("id") Long id){
        return this.accessCardServiceInterface.updateBlackCard(id);
    }

    @Override
    @GetMapping("/accessCard/cancelBlackCard/{id}")
    public ResultBean<Boolean> cancelBlackCard(@PathVariable("id") Long id){
        return this.accessCardServiceInterface.cancelBlackCard(id);
    }

    @Override
    @PostMapping("/accessCard/updateAccessCardById")
    public ResultBean<Boolean> updateAccessCardById(@RequestBody AccessCard accessCard){
        return this.accessCardServiceInterface.updateAccessCardById(accessCard);
    }
    @Override
    @PostMapping("/accessCard/findAccessCardByUserIdAndUserName")
    public List<AccessCard> findAccessCardByUserIdAndUserName(@RequestBody AccessCardDto accessCardDto){
        Assert.isTrue(StringUtils.isNotEmpty(accessCardDto.getUserId()),"userId不能为空");
        Assert.isTrue(StringUtils.isNotEmpty(accessCardDto.getUserName()),"userName不能为空");
        return this.accessCardServiceInterface.findAccessCardByUserIdAndUserName(accessCardDto.getUserId(), accessCardDto.getUserName());
    }
}
