package com.ruoyi.web.controller.system;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.ValidGroup;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
//import com.ruoyi.common.utils.poi.ExcelUtil;
//import com.ruoyi.ss.device.domain.DeviceBO;
//import com.ruoyi.ss.device.domain.DeviceQuery;
//import com.ruoyi.ss.device.domain.dto.DeviceBatchUpdateModelDTO;
//import com.ruoyi.ss.device.domain.vo.DeviceVO;
//import com.ruoyi.ss.device.service.DeviceAssembler;
//import com.ruoyi.ss.device.service.DeviceService;
//import com.ruoyi.ss.suit.domain.enums.SuitTimeUnit;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.ss.device.domain.DeviceBO;
import com.ruoyi.ss.device.domain.DeviceQuery;
import com.ruoyi.ss.device.domain.dto.DeviceBatchUpdateModelDTO;
import com.ruoyi.ss.device.domain.dto.PlacementDTO;
import com.ruoyi.ss.device.domain.vo.DeviceVO;
import com.ruoyi.ss.device.service.DeviceAssembler;
import com.ruoyi.ss.device.service.DeviceService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 设备Controller
 *
 */
@RestController
@RequestMapping("/system/device")
public class DeviceController extends BaseController
{
    @Autowired
    private DeviceService deviceService;

    @Autowired
    private DeviceAssembler deviceAssembler;

    /**
     * 查询设备列表
     */
    @PreAuthorize("@ss.hasPermi('system:device:list')")
    @GetMapping("/list")
    public TableDataInfo list(DeviceQuery smDevice)
    {
        startPage();
        List<DeviceVO> list = deviceService.selectSmDeviceList(smDevice);
        deviceService.pullDeviceInfoList(list);
//        deviceAssembler.assembleRealServiceRate(list);
//        deviceAssembler.assemblePlacementStatus(list, smDevice.getPlacementStatus());
        deviceAssembler.assembleEquipment(list);
        return getDataTable(list);
    }


    /**
     * ids查询设备列表
     */
    @PreAuthorize("@ss.hasPermi('system:device:list')")
    @GetMapping("/listByIds/{ids}")
    public AjaxResult listByIds(@PathVariable Long[] ids)
    {
        List<DeviceVO> list = deviceService.selectByIds(Arrays.asList(ids));
        return success(list);
    }

    /**
     * 导出设备列表
     */
    @PreAuthorize("@ss.hasPermi('system:device:export')")
    @Log(title = "设备", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DeviceQuery smDevice)
    {
        List<DeviceVO> list = deviceService.selectSmDeviceList(smDevice);
        ExcelUtil<DeviceVO> util = new ExcelUtil<DeviceVO>(DeviceVO.class);
        util.exportExcel(response, list, "设备数据");
    }

    /**
     * 获取设备详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:device:query')")
    @GetMapping(value = "/{deviceId}")
    public AjaxResult getInfo(@PathVariable("deviceId") Long deviceId) {
        DeviceVO device = deviceService.selectById(deviceId);
        deviceAssembler.assembleEquipment(device);
        return success(device);
    }

    /**
     * 新增设备
     */
    @PreAuthorize("@ss.hasPermi('system:device:add')")
    @Log(title = "设备", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody @Validated({ValidGroup.Create.class}) DeviceBO data)
    {
        data = data.filterCreate();
        return toAjax(deviceService.insertSmDevice(data));
    }

    /**
     * 修改设备
     */
    @PreAuthorize("@ss.hasPermi('system:device:edit')")
    @Log(title = "设备", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody @Validated({ValidGroup.Update.class}) DeviceBO data)
    {
        data = data.filterUpdate();
        return toAjax(deviceService.updateSmDevice(data));
    }

//    /**
//     * 删除设备
//     */
//    @PreAuthorize("@ss.hasPermi('system:device:remove')")
//    @Log(title = "设备", businessType = BusinessType.DELETE)
//	@DeleteMapping("/{deviceIds}")
//    public AjaxResult remove(@PathVariable Long[] deviceIds)
//    {
//        return toAjax(deviceService.deleteSmDeviceByDeviceIds(deviceIds));
//    }

    @ApiOperation("逻辑删除设备")
    @PreAuthorize("@ss.hasPermi('system:device:remove')")
    @Log(title = "设备", businessType = BusinessType.LOGIC_DELETE)
    @DeleteMapping("/{deviceIds}")
    public AjaxResult logicDel(@PathVariable List<Long> deviceIds)
    {
        return toAjax(deviceService.logicDel(deviceIds));
    }

    @ApiOperation("刷新设备信息")
    @Log(title = "设备", businessType = BusinessType.UPDATE)
    @GetMapping("/{deviceId}/refreshIot")
    public AjaxResult syncIot(@PathVariable @ApiParam("设备id") Long deviceId) {
        deviceService.pullDeviceInfo(Collections.singletonList(deviceId));
        return success();
    }

    @ApiOperation("绑定SN码")
    @PreAuthorize("@ss.hasPermi('system:device:bindSn')")
    @Log(title = "设备", businessType = BusinessType.UPDATE)
    @PutMapping("/{deviceId}/bindSn/{sn}")
    public AjaxResult bindSn(@PathVariable @ApiParam("设备ID") Long deviceId, @PathVariable @ApiParam("SN") String sn) {
        return success(deviceService.bindSn(deviceId, sn));
    }

//    @PreAuthorize("@ss.hasPermi('system:device:addTime')")
//    @Log(title = "设备充值时长", businessType = BusinessType.OTHER)
//    @PutMapping("/addTime/{deviceId}")
//    public AjaxResult addTime(@PathVariable @ApiParam("设备id") Long deviceId,
//                              @ApiParam("时长") @RequestParam Long amount,
//                              @ApiParam("时长单位") @RequestParam(required = false, defaultValue = "3") String timeUnit) {
//        SuitTimeUnit unit = SuitTimeUnit.getByValue(timeUnit);
//        if (unit == null) {
//            return error("非法的时长单位");
//        }
//        return toAjax(deviceService.addTimeByUser(deviceId, amount * unit.getConversion(), true, "管理员手动充值时长"));
//    }

    @PreAuthorize("@ss.hasPermi('system:device:addEle')")
    @Log(title = "设备充值电量", businessType = BusinessType.OTHER)
    @PutMapping("/addEle/{deviceId}")
    public AjaxResult addEle(@ApiParam("设备id") @PathVariable Long deviceId,
                             @ApiParam("电量（度）") @RequestParam BigDecimal amount) {
        return toAjax(deviceService.addEle(deviceId, amount, true, "管理员手动充值电量"));
    }

    @ApiOperation("设备时长归零")
    @PreAuthorize("@ss.hasPermi('system:device:reset')")
    @Log(title = "设备时长归零", businessType = BusinessType.OTHER)
    @PutMapping("/{deviceId}/reset")
    public AjaxResult reset(@PathVariable @ApiParam("设备id") Long deviceId) {
        return toAjax(deviceService.resetTimeWithBill(deviceId, true));
    }

    @PreAuthorize("@ss.hasPermi('system:device:resetEle')")
    @Log(title = "设备清空电量", businessType = BusinessType.OTHER)
    @PutMapping("/{deviceId}/resetEle")
    public AjaxResult resetEle(@PathVariable @ApiParam("设备id") Long deviceId) {
        return toAjax(deviceService.resetEleWithBill(deviceId, true));
    }

    @ApiOperation("设备开关")
    @PreAuthorize("@ss.hasPermi('system:device:switch')")
    @Log(title = "设备", businessType = BusinessType.OTHER)
    @PutMapping("/{deviceId}/switch")
    public AjaxResult switchDevice(@PathVariable Long deviceId, @RequestParam Boolean open) {
        return toAjax(deviceService.switchDevice(deviceId, open,false,"管理员开关设备",false));
    }

    @ApiOperation("重启设备")
    @PreAuthorize("@ss.hasPermi('system:device:switch')")
    @Log(title = "设备", businessType = BusinessType.REBOOT)
    @PutMapping("/{deviceId}/reboot")
    public AjaxResult reboot(@PathVariable Long deviceId) {
        DeviceVO deviceVO = deviceService.selectById(deviceId);
        return toAjax(deviceService.reboot(deviceVO,"后台管理员操作"));
    }

    @ApiOperation("设备批量修改型号")
    @PreAuthorize("@ss.hasPermi('system:device:edit')")
    @Log(title = "设备", businessType = BusinessType.UPDATE)
    @PutMapping("/batchUpdateModel")
    public AjaxResult batchUpdateModel(@RequestBody @Validated DeviceBatchUpdateModelDTO dto) {
        return success(deviceService.batchUpdateModel(dto));
    }

    @ApiOperation("解除设备绑定商户")
    @PreAuthorize("@ss.hasPermi('system:device:unbind')")
    @Log(title = "设备", businessType = BusinessType.OTHER)
    @DeleteMapping("/{deviceId}/unbind")
    public AjaxResult unbind(@PathVariable @ApiParam("设备id") Long deviceId) {
        return toAjax(deviceService.unbind(deviceId));
    }

    @ApiOperation("修改服务费")
    @PreAuthorize("@ss.hasPermi('system:device:edit')")
    @Log(title = "设备", businessType = BusinessType.UPDATE)
    @PutMapping("/updateServiceRate")
    public AjaxResult updateServiceRate(@RequestBody @Validated DeviceVO data) {
        return toAjax(deviceService.updateServiceRate(data));
    }

    @PreAuthorize("@ss.hasPermi('system:device:unbindAgent')")
    @Log(title = "设备解绑代理商", businessType = BusinessType.OTHER)
    @DeleteMapping("/{deviceId}/unbindAgent")
    public AjaxResult unbindAgent(@PathVariable @ApiParam("设备id") Long deviceId) {
        return toAjax(deviceService.unbindAgent(deviceId));
    }

    @PreAuthorize("@ss.hasPermi('system:device:bindMch')")
    @Log(title = "设备绑定商户", businessType = BusinessType.OTHER)
    @PutMapping("/{deviceId}/bindMch")
    public AjaxResult bindMch(@PathVariable @ApiParam("设备id") Long deviceId, @RequestParam Long mchId) {
        return AjaxResult.success("操作成功", deviceService.bindMch(deviceId, mchId));
    }

    @PreAuthorize("@ss.hasPermi('system:device:binAgent')")
    @Log(title = "设备绑定代理商", businessType = BusinessType.OTHER)
    @PutMapping("/{deviceId}/bindAgent")
    public AjaxResult bindAgent(@PathVariable @ApiParam("设备id") Long deviceId, @RequestParam Long agentId, @RequestParam BigDecimal agentServiceRate) {
        return toAjax(deviceService.bindAgent(deviceId, agentId, agentServiceRate));
    }

    /**
     * 投放设备
     */
    @PostMapping("/placement")
    public AjaxResult placementDevice(@RequestBody PlacementDTO dto) {
        logger.info("投放设备：【dto={}】", JSON.toJSONString(dto));
        return toAjax(deviceService.placementDevice(dto));
    }

    /**
     * 下架设备
     */
    @ApiOperation("下架设备")
    @PostMapping("/{deviceId}/offline")
    public AjaxResult offline(@PathVariable("deviceId") Long deviceId) {
        logger.info("下架设备：【deviceId={}】", deviceId);
        return toAjax(deviceService.offline(deviceId));
    }

}
