package com.zd.laboratory.controller;

import com.zd.common.core.domain.per.PerFun;
import com.zd.common.core.domain.per.PerPrefix;
import com.zd.common.core.utils.poi.ExcelUtil;
import com.zd.common.core.web.controller.BaseController;
import com.zd.common.core.web.domain.AjaxResult;
import com.zd.common.core.web.page.TableDataInfo;
import com.zd.common.log.annotation.Log;
import com.zd.common.log.enums.BusinessType;
import com.zd.common.security.annotation.PreAuthorize;
import com.zd.common.security.utils.DictUtils;
import com.zd.laboratory.domain.LabAbnormal;
import com.zd.laboratory.domain.vo.LabAbnormalVO;
import com.zd.laboratory.service.ILabAbnormalService;
import com.zd.laboratory.socket.command.Symbol;
import com.zd.laboratory.socket.service.SocketService;
import com.zd.system.api.domain.SysDictData;
import com.zd.system.api.domain.SysUserTeaCherByExport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 异常设备Controller
 *
 * @author zd
 * @date 2021-09-07
 */
@RestController
@RequestMapping("/abnormal")
public class LabAbnormalController extends BaseController {
    @Autowired
    private ILabAbnormalService labAbnormalService;
    @Autowired
    private SocketService socketService;

    @GetMapping("/send")
    public AjaxResult send(int num, String deviceNum, int type) {

        if(type == 1){
            return socketService.sendCommand(Symbol.order.control, deviceNum, Symbol.command.open, num);
        }else {
            return socketService.sendCommand(Symbol.order.control, deviceNum, Symbol.command.close, num);
        }
    }

    @GetMapping("/sendALL")
    public void sendALL(String deviceNum, int type) {

        /*if(type == 1){
            for (int i = 1; i < 5; i++) {
                socketService.sendCommand(Symbol.order.control, deviceNum, Symbol.command.open, i);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }else {
            for (int i = 1; i < 5; i++) {
                socketService.sendCommand(Symbol.order.control, deviceNum, Symbol.command.close, i);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }*/
    }

    @PostMapping("/sendData")
    public void sendData(@RequestBody Map<String, String> params) {

        socketService.setSensorData(params.get("data"));
    }


    /**
     * 查询异常设备列表
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_ABNORMAL + PerFun.LIST)
    @GetMapping("/list")
    public TableDataInfo list(LabAbnormalVO labAbnormal) {
        startPage();
        List<LabAbnormalVO> list = labAbnormalService.selectLabAbnormalList(labAbnormal);
        return getDataTable(list);
    }


    /**
     * 查询设备列表
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_ABNORMAL + PerFun.LIST)
    @GetMapping("/getEquipmentList")
    public TableDataInfo getEquipmentList(LabAbnormalVO labAbnormal) {
        startPage();
        List<LabAbnormalVO> list = labAbnormalService.getEquipmentList(labAbnormal);
        return getDataTable(list);
    }

    /**
     * 导出异常设备列表
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_ABNORMAL + PerFun.EXPORT)
    @Log(title = "异常设备", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, LabAbnormalVO labAbnormal) throws IOException {
        List<LabAbnormalVO> list = labAbnormalService.getEquipmentList(labAbnormal);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<SysDictData> dictList = DictUtils.getDictCache("equipment_category");
        Optional.ofNullable(list).filter(a->a.size()>0).orElseGet(Collections::emptyList).stream().forEach(a->{
            String dateString = formatter.format(a.getLastAbnormalTime());
            a.setLastAbnormalTimeStr(dateString);
            a.getHardwareOperateName();
            String dictLabel = Optional.ofNullable(dictList).filter(b->b.size()>0).orElseGet(Collections::emptyList).stream().filter(b->b.getDictValue().equals(a.getEquipmentType()+"")).map(b->b.getDictLabel()).findFirst().orElse("");
            a.setTypeStr(dictLabel+"-"+a.getHardwareTypeName());
        });
//        ExcelUtil<LabAbnormalVO> util = new ExcelUtil<LabAbnormalVO>(LabAbnormalVO.class);
//        util.exportExcel(response, list, "异常设备数据");
        ExcelUtil<LabAbnormalVO> util = new ExcelUtil<LabAbnormalVO>(LabAbnormalVO.class);
        //本地日期,不包括时分秒
        LocalDate nowDate = LocalDate.now();
        util.exportExcel(response, list, "异常设备数据", null, "异常设备导出数据表"+nowDate);
    }

    /**
     * 获取异常设备详细信息
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_ABNORMAL + PerFun.QUERY)
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(labAbnormalService.selectLabAbnormalById(id));
    }

    /**
     * 新增异常设备
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_ABNORMAL + PerFun.ADD)
    @Log(title = "异常设备", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LabAbnormal labAbnormal) {
        return toAjax(labAbnormalService.insertLabAbnormal(labAbnormal));
    }

    /**
     * 修改异常设备
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_ABNORMAL + PerFun.EDIT)
    @Log(title = "异常设备", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LabAbnormal labAbnormal) {
        return toAjax(labAbnormalService.updateLabAbnormal(labAbnormal));
    }

    /**
     * 删除异常设备
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_ABNORMAL + PerFun.REMOVE)
    @Log(title = "异常设备", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(labAbnormalService.deleteLabAbnormalByIds(ids));
    }

    /**
     * 删除设备和异常信息
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_ABNORMAL + PerFun.REMOVE)
    @DeleteMapping("/delEquipment")
    public AjaxResult delEquipment(LabAbnormalVO labAbnormal) {
        return toAjax(labAbnormalService.delEquipment(labAbnormal));
    }

    /**
     * 获取设备统计异常信息
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_ABNORMAL + PerFun.QUERY)
    @GetMapping(value = "/getAbnormalCount")
    public AjaxResult getAbnormalCount(LabAbnormalVO labAbnormal) {
        return AjaxResult.success(labAbnormalService.getAbnormalCount(labAbnormal));
    }
}
