package com.sptg.device.biz.controller;

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.dto.FlowCardDto;
import com.sptg.device.api.entity.Device;
import com.sptg.device.api.entity.FlowCard;
import com.sptg.device.api.entity.FlowCardDevice;
import com.sptg.device.api.feigns.FlowCardDeviceFeign;
import com.sptg.device.api.feigns.FlowCardFeign;
import com.sptg.device.biz.service.DeviceServiceInterface;
import com.sptg.device.biz.service.FlowCardDeviceServiceInterface;
import com.sptg.device.biz.service.FlowCardServiceInterface;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * title: DeviceController
 * package: com.sptg.device.biz.controller
 * description: 流量卡控制器
 *
 *                  
 *                 
 */
@RestController
@RequiredArgsConstructor
public class FlowCardController implements FlowCardFeign {

    private final FlowCardServiceInterface flowCardServiceInterface;
    private final DeviceServiceInterface deviceServiceInterface;
    private final FlowCardDeviceFeign flowCardDeviceFeign;
    private final RedisTemplate<String,String> redisTemplate;
    /**
     * 设备缓存名称
     */
    private final static String DEVICE_CACHE_NAME = "sptg:device";

    /**
     * 功能描述: 分页查询流量卡列表
     * @param pageBean 分页条件
     * @return ResultBean<Page>
     *
     *
     */
    @Override
    @PostMapping(value = "/flowCard/pagingQuery")
    public ResultBean<Page<FlowCard>> pagingQuery(@RequestBody PageBean<FlowCard,FlowCardDto> pageBean) {
        Page<FlowCard> flowCardPage = this.flowCardServiceInterface.pagingQuery(pageBean);
        return new ResultBean<>(ResultEnum.SUCCESS,flowCardPage);
    }

    /**
     * 添加卡
     * @param dto 卡实体类
     * @return
     */
    @Override
    @PostMapping(value = "/flowCard/add")
    public ResultBean<Boolean> add(@RequestBody FlowCardDto dto) {
        dto.setStatus(OperationConstant.ZERO);
        dto.setCardStatus(OperationConstant.ZERO);
        dto.setCreateDate(new Date());
        boolean result = this.flowCardServiceInterface.insert(dto);
        return new ResultBean<>(ResultEnum.SUCCESS,result);
    }

    /**
     * 修改卡
     * @param dto 卡实体类
     * @return
     */
    @Override
    @PostMapping(value = "/flowCard/edit")
    public ResultBean<Boolean> edit(@RequestBody FlowCardDto dto) {
        FlowCard flowCard = this.flowCardServiceInterface.selectById(dto.getId());
        Assert.notNull(flowCard,"该流量卡不存在");
        //  权限校验
        if (!flowCard.getOrgPosition().startsWith(dto.getOrgPosition())){
            return new ResultBean<>(ResultEnum.FORBIDDEN);
        }
        boolean result = this.flowCardServiceInterface.updateById(dto);
        return new ResultBean<>(ResultEnum.SUCCESS,result);
    }

    @Override
    @PostMapping(value = "/flowCard/getById")
    public FlowCard getById(@RequestBody FlowCardDto dto){
        FlowCard flowCard = this.flowCardServiceInterface.selectById(dto.getId());
        Assert.notNull(flowCard,"流量卡不存在");
        //  权限校验
        if (!flowCard.getOrgPosition().startsWith(dto.getOrgPosition())){
            return null;
        }
        return flowCard;
    }

    @Override
    @GetMapping(value = "/flowCard/getById/{id}")
    public FlowCard getById(@PathVariable(value = "id")Long id) {
        return this.flowCardServiceInterface.selectById(id);
    }

    @Override
    @PostMapping(value = "/flowCard/delete")
    public ResultBean<Boolean> delete(@RequestBody FlowCardDto dto) {
        FlowCard flowCard = this.flowCardServiceInterface.selectById(dto.getId());
        Assert.notNull(flowCard,"流量卡不存在");
        //  权限校验
        if (!flowCard.getOrgPosition().startsWith(dto.getOrgPosition())){
            return new ResultBean<>(ResultEnum.FORBIDDEN);
        }
        //删除
        flowCard.setStatus(OperationConstant.MINUS_ONE);
        boolean result = this.flowCardServiceInterface.updateById(flowCard);
        return new ResultBean<>(ResultEnum.SUCCESS,result);
    }

    /**
     * 流量卡绑定设备
     * @param dto 卡实体类
     * @return
     */
    @Override
    @PostMapping(value = "/flowCard/bind")
    public ResultBean<Boolean> bind(@RequestBody FlowCardDto dto) {
        FlowCard flowCard = this.flowCardServiceInterface.selectById(dto.getId());
        Device device = this.deviceServiceInterface.selectById(dto.getDeviceId());
        Assert.notNull(flowCard,"该流量卡不存在");
        Assert.notNull(device,"该设备不存在");
        Assert.isTrue(device.getFlowCardId() == null && flowCard.getDeviceId() == null,"该设备或流量卡已有绑定关系，请点击更换绑定");
        //更新卡绑定状态
        flowCard.setCardStatus(OperationConstant.ONE);
        flowCard.setDeviceId(dto.getDeviceId());
        boolean fb = this.flowCardServiceInterface.updateById(flowCard);
        device.setFlowCardId(dto.getId());
        boolean db = this.deviceServiceInterface.updateById(device);
        if (fb && db){
            return new ResultBean<>(ResultEnum.SUCCESS, true);
        }
        return new ResultBean<>(ResultEnum.ERROR,false);
    }

    /**
     * 流量卡取消绑定设备
     * @param dto 卡实体类
     * @return
     */
    @Override
    @PostMapping(value = "/flowCard/reBind")
    public ResultBean<Boolean> reBind(@RequestBody FlowCardDto dto) {
        FlowCard flowCard = this.flowCardServiceInterface.selectById(dto.getId());
        Assert.notNull(flowCard,"该流量卡不存在");
        Device device = this.deviceServiceInterface.selectById(dto.getDeviceId());
        Assert.notNull(device,"该设备不存在");
        //  权限校验
        if (!flowCard.getOrgPosition().startsWith(dto.getOrgPosition())){
            return new ResultBean<>(ResultEnum.FORBIDDEN);
        }
        /*//创建查询条件
        FlowCardDevice condition = new FlowCardDevice();
        condition.setDeviceId(dto.getId());
        condition.setDeviceId(dto.getDeviceId());
        FlowCardDevice flowCardDevice = this.flowCardDeviceFeign.getOne(condition);
        Assert.notNull(flowCardDevice,"该记录不存在");
        ResultBean<Boolean> resultBean = this.flowCardDeviceFeign.delete(flowCardDevice);*/
        if (flowCard.getDeviceId() != null && device.getFlowCardId() != null){
            //更新卡绑定状态
            Wrapper<FlowCard> flowCardWrapper = new EntityWrapper<>();
            flowCardWrapper.eq("l_id",flowCard.getId());
            String flowCardSql = "l_device_id = null,i_card_status = 0";
            boolean fb = this.flowCardServiceInterface.updateForSet(flowCardSql,flowCardWrapper);
            Wrapper<Device> deviceWrapper = new EntityWrapper<>();
            deviceWrapper.eq("l_id",device.getId());
            String deviceSql = "l_flow_card_id = null";
            boolean db = this.deviceServiceInterface.updateForSet(deviceSql,deviceWrapper);
            if (db){
                //删除缓存
                this.redisTemplate.opsForHash().delete(DEVICE_CACHE_NAME, device.getId().toString());
                if (fb){
                    return new ResultBean<>(ResultEnum.SUCCESS, true);

                }
            }
        }
        return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY,false);
    }

    /**
     * 流量卡更换绑定设备
     * @param dto 卡实体类
     * @return ResultBean<Boolean>
     */
    @Override
    @PostMapping(value = "/flowCard/updateBind")
    public ResultBean<Boolean> updateBind(@RequestBody FlowCardDto dto) {
        FlowCard flowCard = this.flowCardServiceInterface.selectById(dto.getId());
        Assert.notNull(flowCard,"该流量卡不存在");
        Device device = this.deviceServiceInterface.selectById(dto.getDeviceId());
        Assert.notNull(device,"该设备不存在");
//        //  权限校验
//        if (!flowCard.getOrgPosition().startsWith(dto.getOrgPosition())){
//            return new ResultBean<>(ResultEnum.FORBIDDEN);
//        }
        //更新卡绑定状态
        //设备是否有原来绑定的卡
        if (device.getFlowCardId() != null){
            FlowCard original = this.flowCardServiceInterface.selectById(device.getFlowCardId());
            original.setDeviceId(null);
            if (!this.flowCardServiceInterface.updateAllColumnById(original)){
                return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY,false);
            };
        }
        flowCard.setCardStatus(OperationConstant.ONE);
        flowCard.setDeviceId(dto.getDeviceId());
        boolean fb = this.flowCardServiceInterface.updateById(flowCard);
        device.setFlowCardId(dto.getId());
        boolean db = this.deviceServiceInterface.updateById(device);
        if (fb && db){
            return new ResultBean<>(ResultEnum.SUCCESS, true);
        }
        return new ResultBean<>(ResultEnum.PARAMETER_ANOMALY,false);
    }

    /**
     * 获取一个流量卡-用于验证
     * @param dto
     * @return
     */
    @Override
    @PostMapping(value = "/flowCard/getOneFlowCard")
    public FlowCard getOneFlowCard(@RequestBody FlowCardDto dto) {
        return flowCardServiceInterface.getOneFlowCard(dto);
    }

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

}
