package cn.hanghui.outapi.platform.tenant.controller;

import cn.hanghui.outapi.platform.common.config.log.Log;
import cn.hanghui.outapi.platform.common.entity.rest.RestCode;
import cn.hanghui.outapi.platform.common.entity.rest.RestResponse;
import cn.hanghui.outapi.platform.common.entity.rest.RestResult;
import cn.hanghui.outapi.platform.common.utils.AppTokenUtil;
import cn.hanghui.outapi.platform.common.utils.EnumUtils;
import cn.hanghui.outapi.platform.tenant.entity.config.device.template.DeviceTemplateDto;
import cn.hanghui.outapi.platform.tenant.entity.config.device.template.DeviceTemplateLessVo;
import cn.hanghui.outapi.platform.tenant.entity.config.device.template.DeviceTemplateSearch;
import cn.hanghui.outapi.platform.tenant.entity.config.device.template.DeviceTemplateVo;
import cn.hanghui.outapi.platform.tenant.entity.dto.*;
import cn.hanghui.outapi.platform.tenant.entity.enums.*;
import cn.hanghui.outapi.platform.tenant.service.DeviceTemplateService;
import cn.hanghui.outapi.platform.tenant.service.TenantService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@Slf4j
@Api(tags = "商户、设备管理")
@RestController
@RequestMapping("/api/v1/tenant")
@AllArgsConstructor(onConstructor_ = @Autowired)
public class TenantController {

    private TenantService tenantService;
    private final DeviceTemplateService deviceTemplateService;

    /**
     * 获取商户列表
     *
     * @param dto
     * @return JSONObject
     */
    @ApiOperation("获取商户信息")
    @PostMapping("/list")
    public RestResult<List<TenantVo>> list(@RequestBody TenantDto dto) {
        //TB人脸终端
        List<String> tokens = AppTokenUtil.getTokens();
        if (dto == null || dto.getToken() == null || "".equals(dto.getToken().trim()) || !tokens.contains(dto.getToken().trim())) {
            return RestResult.error(RestCode.FORBIDDEN.getMsg());
        }
        if (dto == null || dto.getSn() == null || "".equals(dto.getSn().trim())) {
            return RestResult.error("设备编号不能为空");
        }
        return tenantService.list(dto);
    }

    @ApiOperation(value = "添加商户")
    @PostMapping("/add")
    @Log(tag = LogTagEnum.TENANT,title = "添加/编辑服务商平台",businessTypeEnum = BusinessTypeEnum.INSERT_UPDATE)
    public RestResult<Boolean> addApply(@RequestBody TenantReqDto dto) {
        return tenantService.add(dto);
    }

    @ApiOperation(value = "删除商户")
    @GetMapping("/del/{id}")
    @Log(tag = LogTagEnum.TENANT,title = "删除服务商平台",businessTypeEnum = BusinessTypeEnum.DELETE)
    public RestResult<Boolean> del(@PathVariable(value = "id") @ApiParam(value = "id", required = true) Long id) {
        return tenantService.del(id);
    }

    @ApiOperation(value = "启用商户三方授权")
    @PostMapping("/auth/{id}")
    public RestResult<Boolean> auth(@PathVariable(value = "id") @ApiParam(value = "id", required = true) Long id) {
        return tenantService.opeAuth(id, Boolean.TRUE);
    }

    @ApiOperation(value = "停用商户三方授权")
    @PostMapping("/auth/cancel/{id}")
    public RestResult<Boolean> authCancel(@PathVariable(value = "id") @ApiParam(value = "id", required = true) Long id) {
        return tenantService.opeAuth(id, Boolean.FALSE);
    }

    @ApiOperation(value = "查询商户列表（分页）")
    @PostMapping("/page")
    public RestResult<IPage<TenantVo>> pageApply(@RequestBody TenantReqDto dto) {

        return tenantService.page(dto);
    }

    @ApiOperation(value = "(内部服务调用)添加或删除设备 已弃用")
    @Deprecated
    @PostMapping("/sn/deviceWhiteList")
    public RestResult<Boolean> opDevice(@RequestBody DeviceDto dto) {
        return tenantService.opDevice(dto);
    }

    @ApiOperation(value = "添加或编辑设备")
    @PostMapping("/sn/add")
    @Log(tag = LogTagEnum.HHFACE,title = "添加/编辑设备",businessTypeEnum = BusinessTypeEnum.INSERT_UPDATE)
    public RestResult<Boolean> addDevice(@Valid @RequestBody DeviceDto dto) {
        return tenantService.addDevice(dto);
    }

    @ApiOperation(value = "设备调用-根据sn修改配置信息")
    @PostMapping("/sn/op/config")
    public RestResult<Boolean> deviceOpConfig(@RequestBody DeviceOpConfigDto dto) {
        log.info("--->设备调用-根据sn修改配置信息入参:{}", JSONObject.toJSONString(dto));
        //TB人脸终端
        List<String> tokens = AppTokenUtil.getTokens();
        if (dto == null || dto.getToken() == null || "".equals(dto.getToken().trim()) || !tokens.contains(dto.getToken().trim())) {
            return RestResult.error(RestCode.FORBIDDEN.getMsg());
        }
        return tenantService.deviceOpConfig(dto);
    }


    @ApiOperation(value = "授权")
    @PostMapping("/sn/auth/{deviceId}")
    @Log(tag = LogTagEnum.HHFACE,title = "设备授权",businessTypeEnum = BusinessTypeEnum.AUTH)
    public RestResult<Boolean> deviceAuth(@PathVariable(value = "deviceId") @ApiParam(value = "deviceId", required = true) Long deviceId) {
        return tenantService.opeDeviceAuth(deviceId, Boolean.TRUE);
    }

    @ApiOperation(value = "取消授权")
    @PostMapping("/sn/auth/cancel/{deviceId}")
    @Log(tag = LogTagEnum.HHFACE,title = "设备取消授权",businessTypeEnum = BusinessTypeEnum.CANCEL_AUTH)
    public RestResult<Boolean> deviceAuthCancel(@PathVariable(value = "deviceId") @ApiParam(value = "deviceId", required = true) Long deviceId) {
        return tenantService.opeDeviceAuth(deviceId, Boolean.FALSE);
    }

    @ApiOperation(value = "删除设备")
    @PostMapping("/sn/del/{deviceId}")
    @Log(tag = LogTagEnum.HHFACE,title = "删除设备",businessTypeEnum = BusinessTypeEnum.DELETE)
    public RestResult<Boolean> deviceDel(@PathVariable(value = "deviceId") @ApiParam(value = "deviceId", required = true) Long deviceId) {
        return tenantService.deviceDel(deviceId);
    }

    @ApiOperation(value = "查询设备列表（分页）")
    @PostMapping("/sn/page")
    public RestResult<IPage<DeviceVo>> pageApply(@RequestBody DeviceDto dto) {
        return tenantService.snPage(dto);
    }

    /**
     * 获取商户列表（无需授权）
     *
     * @return JSONObject
     */
    @ApiOperation("获取商户列表")
    @PostMapping("/inner/list")
    public RestResult innerList() {
        return tenantService.innerList();
    }

    @ApiOperation(value = "获取设备编号列表")
    @PostMapping("/sn/list")
    public RestResult<List<String>> snlist() {
        return tenantService.snlist();
    }


    @ApiOperation("设备模版-新增/编辑")
    @PostMapping("template/edit")
    @ApiOperationSupport(order = 100)
    @Log(tag = LogTagEnum.HHFACE,title = "新增/编辑模版",businessTypeEnum = BusinessTypeEnum.INSERT_UPDATE)
    public RestResult<Boolean> edit(@RequestBody @Valid DeviceTemplateDto dto) {
        return RestResponse.ok(deviceTemplateService.edit(dto));
    }

    @ApiOperation("设备模版列表")
    @GetMapping("template/list")
    @ApiOperationSupport(order = 110)
    public RestResult<List<DeviceTemplateLessVo>> deviceTemplateList() {
        return RestResponse.ok(deviceTemplateService.deviceTemplateList());
    }

    @ApiOperation("设备模版列表(分页)")
    @PostMapping("template/page")
    @ApiOperationSupport(order = 120)
    public RestResult<IPage<DeviceTemplateVo>> deviceTemplatePage(@RequestBody @Valid DeviceTemplateSearch dto) {
        return RestResponse.ok(deviceTemplateService.deviceTemplatePage(dto));
    }

    @ApiOperation("设备模版-删除")
    @DeleteMapping("template/{deviceTemplateId}")
    @ApiOperationSupport(order = 130)
    @Log(tag = LogTagEnum.HHFACE,title = "删除模版",businessTypeEnum = BusinessTypeEnum.DELETE)
    public RestResult<Boolean> templateDelete(@PathVariable(value = "deviceTemplateId") Long deviceTemplateId) {
        return RestResponse.ok(deviceTemplateService.deviceTemplateDelete(deviceTemplateId));
    }

    @ApiOperation("设备模版-模版详情")
    @GetMapping("template/detail")
    @ApiOperationSupport(order = 140)
    public RestResult<DeviceTemplateVo> templateDetail(@RequestParam(value = "deviceTemplateId") Long deviceTemplateId) {
        return RestResponse.ok(deviceTemplateService.templateDetail(deviceTemplateId));
    }

    @ApiOperation(value = "获取身份证阅读器")
    @GetMapping("/sn/getIdCardReaderBrand")
    public RestResult<List<Map<String, String>>> idCardReaderBrandEnum() {
        return RestResult.ok(EnumUtils.enumToListMap(IdCardReaderBrandEnum.class));
    }

    @ApiOperation(value = "获取二维码读头品牌")
    @GetMapping("/sn/getQrCodeReaderBrandEnum")
    public RestResult<List<Map<String, String>>> getQrCodeReaderBrandEnum() {
        return RestResult.ok(EnumUtils.enumToListMap(QrCodeReaderBrandEnum.class));
    }
    @ApiOperation(value = "获取阅读器品牌")
    @GetMapping("/getReaderBrandEnum")
    public RestResult<List<Map<String, String>>> getReaderBrandEnum() {
        return RestResult.ok(EnumUtils.enumToListMap(ReaderBrandEnum.class));
    }


    @ApiOperation(value = "获取失败记录推送类型")
    @GetMapping("/sn/getPushFailedRecordTypeEnum")
    public RestResult<List<Map<String, String>>> getPushFailedRecordTypeEnum() {
        return RestResult.ok(EnumUtils.enumToListMap(PushFailedRecordTypeEnum.class));
    }

}
