package com.mosty.bkzx.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mosty.base.utils.Constant;
import com.mosty.base.utils.DateUtils;
import com.mosty.base.model.dto.bkzx.TbBkClInsertDto;
import com.mosty.base.model.dto.bkzx.TbBkClJudgeDto;
import com.mosty.base.model.entity.bkzx.TbBkCl;
import com.mosty.base.model.query.bkzx.TbBkClSearchDto;
import com.mosty.bkzx.mapper.TbBkClMapper;
import com.mosty.bkzx.remote.TbBaseAdaptRemoteService;
import com.mosty.bkzx.service.TbBkClService;
import com.mosty.bkzx.sjjs.client.HttpClient;
import com.mosty.bkzx.sjjs.domain.ResponseStatusList;
import com.mosty.bkzx.sjjs.entity.MotorVehic;
import com.mosty.common.base.exception.BusinessException;
import com.mosty.common.base.util.StringUtils;
import com.mosty.common.token.UserInfo;
import com.mosty.common.token.UserInfoManager;
import com.mosty.common.util.PermissionsUtil;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * @author dw
 * @since 2022/7/13
 * 布控车辆服务-实现
 **/
@AllArgsConstructor
@Service
public class TbBkClServiceImpl extends ServiceImpl<TbBkClMapper, TbBkCl>
        implements TbBkClService {

    private final TbBaseAdaptRemoteService tbBaseAdaptRemoteService;

    @Override
    public int addEntity(TbBkClInsertDto dto) {
        // 查询是否有重复的数据
        TbBkCl clItem = this.baseMapper.selectOne(
                new LambdaQueryWrapper<TbBkCl>()
                        .eq(TbBkCl::getXtSjzt, "1")
                        .eq(TbBkCl::getCphm, dto.getCphm())
                        .eq(TbBkCl::getCplxdm, dto.getCplxdm())
                        .last(" limit 1")
        );
        if (clItem != null) {
            throw new BusinessException("该车辆已经存在，请修改布控状态或重新录入");
        }
        UserInfo user = UserInfoManager.get();
        // 计算布控天数
        int bkts = 0;
        try {
            bkts = DateUtils.daysBetween(dto.getBkkssj(), dto.getBkjssj());
        } catch (ParseException e) {
            e.printStackTrace();
            throw new BusinessException("时间格式转换异常");
        }
        TbBkCl Cl = new TbBkCl();
        BeanUtils.copyProperties(dto, Cl);
        Cl.setBkts(bkts);
        Cl.setShzt("0");
        Cl.setBkzt("0");
        Cl.setXtSjly("1");
        Cl.setSqrid(String.valueOf(user.getUserId()));
        Cl.setSqrsfzh(user.getIdEntityCard());
        Cl.setSqrxm(user.getUserName());
        Cl.setSsbm(user.getDeptName());
        Cl.setSsbmdm(String.valueOf(user.getDeptId()));
        Cl.setSfqsbkcg("0");
        Cl.setSfqsebkcg("0");
        return this.baseMapper.insert(Cl);
    }

    @Override
    public IPage<TbBkCl> getPageList(TbBkClSearchDto dto) {
//        UserInfo userInfo = UserInfoManager.get();
//        PermissionsUtil.queryWrapperUtil(qw, userInfo);

        dto.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(dto.getSsbmdm(), null));
        QueryWrapper<TbBkCl> qw = new QueryWrapper<>();
        IPage<TbBkCl> page = this.baseMapper.selectPage(
                new Page<>(dto.getPageNum(), dto.getPageSize()),
                qw.lambda()
                        .eq(StringUtils.isNotBlank(dto.getCplxdm()), TbBkCl::getCplxdm, dto.getCplxdm())
                        .eq(StringUtils.isNotBlank(dto.getBkjb()), TbBkCl::getBkjb, dto.getBkjb())
                        .eq(StringUtils.isNotBlank(dto.getShzt()), TbBkCl::getShzt, dto.getShzt())
                        .eq(StringUtils.isNotBlank(dto.getBkzt()), TbBkCl::getBkzt, dto.getBkzt())
                        .like(StringUtils.isNotBlank(dto.getCphm()), TbBkCl::getCphm, dto.getCphm())
                        .likeRight(StringUtils.isNotBlank(dto.getSsbmdm()), TbBkCl::getSsbmdm, dto.getSsbmdm())
                        .orderByDesc(TbBkCl::getXtCjsj)
        );
        // 查询状态是否过期
        List<TbBkCl> ClList = page.getRecords();
        ClList.forEach(item -> {
            if ("1".equals(item.getBkzt())) {
                if (new Date().getTime() >= item.getBkjssj().getTime()) {
                    item.setBkzt("2");
                    this.baseMapper.updateById(item);
                }
            }
        });
        page.setRecords(ClList);
        return page;
    }

    @Override
    public TbBkCl getInfo(String id) {
        return this.baseMapper.selectById(id);
    }

    @Override
    public int editCar(TbBkClInsertDto dto) {
        // 查询是否有重复的数据
        TbBkCl clItem = this.baseMapper.selectOne(
                new LambdaQueryWrapper<TbBkCl>()
                        .eq(TbBkCl::getXtSjzt, "1")
                        .eq(TbBkCl::getCphm, dto.getCphm())
                        .eq(TbBkCl::getCplxdm, dto.getCplxdm())
                        .last(" limit 1")
                        .ne(TbBkCl::getId, dto.getId())
        );
        if (clItem != null) {
            throw new BusinessException("该车辆已经存在，请修改布控状态或重新录入");
        }
        UserInfo user = UserInfoManager.get();
        // 计算布控天数
        int bkts = 0;
        try {
            bkts = DateUtils.daysBetween(dto.getBkkssj(), dto.getBkjssj());
        } catch (ParseException e) {
            e.printStackTrace();
            throw new BusinessException("时间格式转换异常");
        }
        TbBkCl Cl = this.getInfo(dto.getId());
        BeanUtils.copyProperties(dto, Cl);
        Cl.setBkts(bkts);
        Cl.setShzt("0");
        Cl.setBkzt("0");
        Cl.setSqrid(String.valueOf(user.getUserId()));
        Cl.setSqrsfzh(user.getIdEntityCard());
        Cl.setSqrxm(user.getUserName());
        Cl.setSsbm(user.getDeptName());
        Cl.setSsbmdm(user.getDeptCode());
        return this.baseMapper.updateById(Cl);
    }

    @Override
    public int delCar(List<String> ids) {
        return this.baseMapper.deleteBatchIds(ids);
    }

    @Override
    public int endBk(String id) {
        TbBkCl Cl = this.baseMapper.selectById(id);
        if (Cl != null) {
            Cl.setBkzt("2");
            if (org.apache.commons.lang3.StringUtils.isNotBlank(Cl.getBkid())) {
                HttpClient.delMotor(Cl.getBkid(), Cl.getBkkid());
            }
            return this.baseMapper.updateById(Cl);
        }
        return 0;
    }

    @Override
    public int startBk(String id) {
        TbBkCl Cl = this.baseMapper.selectById(id);
        // 查看布控时间是否过期
        if (Cl != null) {
            if (new Date().getTime() >= Cl.getBkjssj().getTime()) {
                throw new BusinessException("布控结束时间已过，请重新修改布控时间！！");
            }

            if (org.apache.commons.lang3.StringUtils.isNotBlank(Cl.getBkid())) {
                HttpClient.delMotor(Cl.getBkid(), Cl.getBkkid());
            }
            Cl.setBkzt("0");
            Cl.setShzt("0");
            return this.baseMapper.updateById(Cl);
        }
        return 0;
    }

    @Override
    public int judge(TbBkClJudgeDto dto) {
        TbBkCl cl = this.baseMapper.selectById(dto.getId());
        if (cl == null) {
            throw new BusinessException("布控车辆信息不存在");
        }
        cl.setShzt(dto.getShzt());
        if ("1".equals(dto.getShzt())) {
            if (cl.getBkjssj().getTime() <= new Date().getTime() + 60 * 60 * 1000) {
                throw new BusinessException("布控结束时间不正确，请确保结束时间在1小时之后！");
            }
            cl.setBkzt("1");
        } else if ("2".equals(dto.getShzt())) {
            cl.setBkzt("3");
        }
        cl.setShsm(StringUtils.isBlank(dto.getShsm()) ? "审核通过" : dto.getShsm());
        UserInfo userInfo = UserInfoManager.get();
        cl.setShryid(String.valueOf(userInfo.getUserId()));
        cl.setShrybm(userInfo.getDeptName());
        cl.setShrybmdm(String.valueOf(userInfo.getDeptId()));
        cl.setShryxm(userInfo.getUserName());

        if (cl.getShzt().equals("1")) {
            //向大华布控推送成员
            MotorVehic motorVehic = new MotorVehic();
            motorVehic.setPlateClass(cl.getCplxdm());
            motorVehic.setPlateNo(cl.getCphm());
            //调用大华布控添加车辆
            //设置布控库车辆id 和 设置布控库
            String faceId = cl.getBkkid() + "07" + String.valueOf((int) ((Math.random() * 9 + 1) * 10000));
            motorVehic.setMotorVehicleID(faceId);
            motorVehic.setTabID(cl.getBkkid());
            String faces = HttpClient.insertMotor(motorVehic);
            if (org.apache.commons.lang3.StringUtils.isNotBlank(faces)) {
                ResponseStatusList responseStatusList = JSONObject.parseObject(faces, ResponseStatusList.class);
                if (null != responseStatusList && responseStatusList.getResponseStatusListObject().getResponseStatusObject().get(0).getStatusCode().equals("0")) {
                    //保存布控库车辆id
                    cl.setBkid(faceId);
                }
            }
        } else {
            if (org.apache.commons.lang3.StringUtils.isNotBlank(cl.getBkid())) {
                HttpClient.delMotor(cl.getBkid(), cl.getBkkid());
            }
        }

        return this.baseMapper.updateById(cl);
    }
}
