/*
 * Author: wangjian
 * 生成controller
 */
package com.tofly.gpsboot.controller.maintain;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.api.AppClient;
import com.tofly.api.UserClent;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.log.annotation.ToFlyAppLog;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.gpsboot.common.Constant;
import com.tofly.gpsboot.service.maintain.MobileDeviceService;
import com.tofly.pojo.User;
import com.tofly.pojo.maintain.MobileDevice;
import com.tofly.pojo.maintain.dto.MobileDeviceDto;
import com.tofly.pojo.maintain.vo.MobileDeviceVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 移动设备信息表
 *
 * @author wangzhun
 * @date Mon May 16 00:00:00 CST 2022
 */
@RestController
@AllArgsConstructor
@RequestMapping("/mobiledevice")
@Api(tags = "移动设备信息表接口")
public class MobileDeviceController {

    private  MobileDeviceService mobileDeviceService;
    private  AppClient appClient;
    private  UserClent userClent;

    /**
     * 分页查询
     *
     * @param page 分页对象
     * @return
     */
    @GetMapping("/page")
    @ApiOperation(value = "分页查询")
    public ResultRespone<Page<MobileDeviceVo>> getMobileDevicePage(Page page, @ModelAttribute MobileDeviceDto mobileDeviceDto) {

        MobileDevice mobileDevice = JSON.parseObject(JSON.toJSONString(mobileDeviceDto), MobileDevice.class);
        List<String> auditList = new ArrayList<>();
        if (StringUtils.isNotBlank(mobileDeviceDto.getAuditQuery())) {
            auditList = Arrays.asList(mobileDeviceDto.getAuditQuery().split(Constant.CSV));

        }
        List<String> statusList = new ArrayList<>();
        if (StringUtils.isNotBlank(mobileDeviceDto.getStatus())) {
            statusList = Arrays.asList(mobileDevice.getStatus().split(Constant.CSV));
            mobileDevice.setStatus(null);
        }
        List<String> appVersion;
        int versionFlag = 1;
        String currentVersion = null;
        if (StringUtils.isNotBlank(mobileDeviceDto.getAppVersionNew())) {
            currentVersion = appClient.getNewVersion("2");


            System.out.println(currentVersion);
            appVersion = Arrays.asList(mobileDeviceDto.getAppVersionNew().split(Constant.CSV));
            if (appVersion.contains("1") && appVersion.size() == 1) {
                //只查询当前
                versionFlag = 2;
            } else if (appVersion.contains("1") && appVersion.size() > 1) {
                //查询当前和历史
                versionFlag = 3;
            } else if (!appVersion.contains("1") && appVersion.size() > 0) {
                //只查询历史
                versionFlag = 4;
            }
        }

        LambdaQueryWrapper<MobileDevice> wrapper = Wrappers.query(mobileDevice).<MobileDevice>lambda()
                .like(StringUtils.isNotBlank(mobileDeviceDto.getQueryLike()), MobileDevice::getName, mobileDeviceDto.getQueryLike())
                .or()
                .like(StringUtils.isNotBlank(mobileDeviceDto.getQueryLike()), MobileDevice::getMeid, mobileDeviceDto.getQueryLike())
                .in(auditList != null && auditList.size() > 0, MobileDevice::getAuditStataus, auditList)
                .in(statusList != null && statusList.size() > 0, MobileDevice::getStatus, statusList)
                .eq(versionFlag == 2, MobileDevice::getAppVersion, currentVersion)
                .ne(versionFlag == 4, MobileDevice::getAppVersion, currentVersion)
                .orderByDesc(MobileDevice::getCreateTime);
        Page page1 = mobileDeviceService.page(page, wrapper);
        page1.setRecords(mobileDeviceService.viewConversion(page1.getRecords()));

        return ResultRespone.success(page1);
    }


    /**
     * 通过id查询移动设备信息表
     *
     * @param id id
     * @return ResultRespone
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long")
    })
    public ResultRespone<MobileDeviceVo> getById(@PathVariable("id") Long id) {
        MobileDevice byId = mobileDeviceService.getById(id);
        MobileDeviceVo mobileDeviceVo = mobileDeviceService.entityToVo(byId);

        return ResultRespone.success(mobileDeviceVo);
    }

    /**
     * 新增移动设备信息表
     *
     * @param mobileDevice 移动设备信息表
     * @return ResultRespone
     */
    @ToFlyAppLog(title = "新增移动设备信息表")
    @ApiOperation(value = "新增移动设备信息表")
    @PostMapping
    public ResultRespone save(@RequestBody MobileDevice mobileDevice) {
        mobileDeviceService.checkHasRegister(mobileDevice);
        //web 端新增 默认已审核
        mobileDevice.setAuditStataus("1");
        mobileDevice.setCreateTime(new Date());
        return ResultRespone.success(mobileDeviceService.save(mobileDevice));
    }

    @ToFlyAppLog(title = "移动设备信息审核")
    @ApiOperation(value = "移动设备信息审核")
    @GetMapping("/deviceAudit")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "多个以, 分割", required = true, dataType = "String"),
            @ApiImplicitParam(name = "auditStatus", value = "0 未审核 1 审核通过", required = true, dataType = "String")
    })
    public ResultRespone deviceAudit(String ids, String auditStatus) {

        List<String> idList = Arrays.asList(ids.split(Constant.CSV));
        return ResultRespone.success(mobileDeviceService.update(Wrappers.<MobileDevice>lambdaUpdate()
                .in(MobileDevice::getId, idList).set(MobileDevice::getAuditStataus, auditStatus)));
    }

    /**
     * 修改移动设备信息表
     *
     * @param mobileDevice 移动设备信息表
     * @return ResultRespone
     */
    @ToFlyAppLog(title = "修改移动设备信息表")
    @ApiOperation(value = "修改移动设备信息表")
    @PutMapping
    public ResultRespone updateById(@RequestBody MobileDevice mobileDevice) {
        mobileDeviceService.checkHasRegister(mobileDevice);

        MobileDevice old = mobileDeviceService.getById(mobileDevice.getId());
        //如果状态为已审核
        if ("1".equals(mobileDevice.getAuditStataus())) {
            if (!old.getUserUserId().equals(mobileDevice.getUserUserId())) {
                old.setStatus("0");
                mobileDeviceService.updateById(old);
                mobileDevice.setStatus("1");
                mobileDevice.setId(null);
                mobileDeviceService.save(mobileDevice);
            } else {
                mobileDeviceService.updateById(mobileDevice);
            }
        } else {
            mobileDeviceService.updateById(mobileDevice);
        }
        return ResultRespone.success(true);
    }

    /**
     * 通过id删除移动设备信息表
     *
     * @param id id
     * @return ResultRespone
     */
    @ToFlyAppLog(title = "通过id删除移动设备信息表")
    @ApiOperation(value = "通过ID删除移动设备信息表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long")
    })
    @DeleteMapping("/{id}")
    public ResultRespone removeById(@PathVariable Long id) {
        return ResultRespone.success(mobileDeviceService.removeById(id));
    }

    /**
     * 通过id批量删除移动设备信息表
     *
     * @param ids id
     * @return ResultRespone
     */
    //   @ToFlyAppLog(title="通过id批量删除移动设备信息表" )
    @ApiOperation(value = "通过ID批量删除移动设备信息表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "批量删除，多个id以逗号隔开", required = true, dataType = "String")
    })
    @DeleteMapping("/deleteByIds")
    public ResultRespone removeById(String ids) {
        return ResultRespone.success(mobileDeviceService.removeByIds(Arrays.asList(ids.split(","))));
    }

    @ToFlyAppLog(title = "app设备注册")
    @ApiOperation(value = "app设备注册")
    @PostMapping("/register")
    public ResultRespone deviceRegister(@RequestBody MobileDeviceDto mobileDeviceDto) {
        MobileDevice device = JSON.parseObject(JSON.toJSONString(mobileDeviceDto), MobileDevice.class);
        device.setDataSource("app");
        Long userId = SecurityUtils.getUserId();
        User result = userClent.getById(userId).getResult();
        device.setUserUserId(userId);
        device.setUseDeptId(result.getDepartmentId());
        device.setDevicePhone(result.getPhone());
        device.setCreateTime(new Date());
        mobileDeviceService.save(device);
        return ResultRespone.success();
    }

    @ApiOperation(value = "验证设备是否注册")
    @GetMapping("/registerCheck")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "meid", value = "meid", required = true, dataType = "String")
    })
    public ResultRespone registerCheck(String meid) {
        Long userUserId = SecurityUtils.getUserId();
        int countUser = mobileDeviceService.count(Wrappers.<MobileDevice>lambdaQuery()
                .eq(MobileDevice::getUserUserId, userUserId)
                .ne(MobileDevice::getMeid, meid)
                .eq(MobileDevice::getStatus, "1")
        );
        Assert.isTrue(countUser == 0, "该用户已绑定其它设备，请先解绑");


        //该设备是否存在绑定信息
        int count = mobileDeviceService.count(Wrappers.<MobileDevice>lambdaQuery()
                .eq(MobileDevice::getMeid, meid)
                .eq(MobileDevice::getStatus, "1")
        );

        if (count > 0) {
            //判断该账号是否是绑定的当前用户
            int count2 = mobileDeviceService.count(Wrappers.<MobileDevice>lambdaQuery()
                    .eq(MobileDevice::getUserUserId, userUserId)
                    .eq(MobileDevice::getStatus, "1")
                    .eq(MobileDevice::getMeid, meid));
            if (count2 == 0) {
                throw new ToflyDeniedException("当前设备已绑定其它用户，请联系管理员解绑");
            }
            int count1 = mobileDeviceService.count(Wrappers.<MobileDevice>lambdaQuery()
                    .eq(MobileDevice::getMeid, meid)
                    .eq(MobileDevice::getStatus, "1")
                    .eq(MobileDevice::getUserUserId, userUserId)
                    .eq(MobileDevice::getAuditStataus, "1"));
            if (count1 > 0) {
                return ResultRespone.success(Boolean.TRUE);
            } else {
                throw new ToflyDeniedException("当前设备未审核，请联系管理员审核");
            }

        } else {
            return ResultRespone.success(Boolean.FALSE);
        }

    }


    @ApiOperation(value = "获取移动设备使用人员列表")
    @GetMapping("/getMobileDeviceUseUser")
    public ResultRespone getMobileDeviceUseUser() {

        return ResultRespone.success(mobileDeviceService.findMobileUser(null));
    }

    @ApiOperation(value = "更新状态(解绑 将状态更新为历史)")
    @GetMapping("/updateStatusById")
    public ResultRespone updateStatusById(Long id, String status) {
        MobileDevice byId = mobileDeviceService.getById(id);
        byId.setStatus(status);
        return ResultRespone.success(mobileDeviceService.updateById(byId));
    }


}
