package com.bonus.bracelet.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.bonus.bracelet.mapper.DeviceMapper;
import com.bonus.bracelet.service.IDeviceService;
import com.bonus.common.core.constant.BusinessConstants;
import com.bonus.common.core.utils.ExcelStyleUtil;
import com.bonus.common.core.web.controller.BaseController;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.core.web.page.TableDataInfo;
import com.bonus.common.entity.bracelet.BraceletParamsDto;
import com.bonus.common.entity.bracelet.exportVo.DeviceExportVo;
import com.bonus.common.entity.bracelet.vo.*;
import com.bonus.common.log.annotation.SysLog;
import com.bonus.common.log.enums.OperaType;
import com.bonus.common.security.annotation.RequiresPermissions;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * DeviceController
 */
@RestController
@RequestMapping("/device/")
@Slf4j
public class DeviceController extends BaseController {

    @Resource(name = "IDeviceService")
    private IDeviceService deviceservice;

    @Resource(name = "DeviceMapper")
    private DeviceMapper deviceMapper;
    /**
     * 展示设备列表
     * @param data
     * @return
     */
    @GetMapping("list")
    @SysLog(title = "设备管理", businessType = OperaType.QUERY,  module = "基础管理->设备管理", details = "查询设备列表")
    public TableDataInfo list(DeviceVo data) {
        startPage();
        List<DeviceVo> list = deviceservice.getDeviceLists(data);
        return getDataTable(list);
    }

    /**
     * 根据设备id获取详细信息
     */
    @RequiresPermissions("bracelet:device:query")
    @GetMapping(value = "/{deviceId}")
    public AjaxResult getInfo(@PathVariable Integer deviceId) {
        return deviceservice.selectDeviceById(deviceId);
    }

    /**
     * 新增设备信息
     * @param vo
     * @return
     */
    @PostMapping("addDevice")
    @SysLog(title = "设备管理", businessType = OperaType.INSERT,  module = "基础管理->设备管理", details = "新增设备")
    public AjaxResult addDevice(@Validated @RequestBody DeviceVo vo) {
        return deviceservice.addDevice(vo);
    }

    /**
     * 新增设备属性信息
     * @param request
     * @param file
     * @param params
     * @return
     */
    @PostMapping("addAttribute")
    @SysLog(title = "设备管理", businessType = OperaType.INSERT,  module = "基础管理->设备管理", details = "新增设备属性")
    public AjaxResult addAttribute(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file, String params) {
        return deviceservice.addAttribute(file,params);
    }

    /**
     * 修改设备信息
     * @param vo
     * @return
     */
    @PostMapping("editDevice")
    @SysLog(title = "设备管理", businessType = OperaType.UPDATE, module = "基础管理->设备管理", details = "修改设备")
    public AjaxResult editDevice(@Validated @RequestBody DeviceVo vo) {
        return deviceservice.editDevice(vo);
    }
    /**
     * 删除设备
     */

    @PostMapping("delDevice")
    @SysLog(title = "设备管理", businessType = OperaType.UPDATE,module = "基础管理->设备管理",details = "删除设备")
    public AjaxResult delDevice(@RequestBody DeviceVo vo) {
            return deviceservice.deleteDeviceById(vo.getDeviceId());

    }

    /**
     * 设备属性列表
     * @param data
     * @return
     */
    @GetMapping("listDeviceAttribute")
    @SysLog(title = "设备管理", businessType = OperaType.QUERY,  module = "基础管理->设备管理", details = "查询设备属性列表")
    public TableDataInfo listDeviceAttribute(AttributeVo data) {
        startPage();
        List<AttributeVo> list = deviceservice.getDeviceAttributeLists(data);
        return getDataTable(list);
    }

    /**
     * 根据id获取设备属性
     * @param dto
     * @return
     */
    @PostMapping("getAttributeInfo")
    public AjaxResult getAttributeInfo(@RequestBody AttributeVo dto) {
        return deviceservice.getAttributeInfo(dto);
    }

    /**
     * 修改设备属性信息
     * @param request
     * @param file
     * @param params
     * @return
     */
    @PostMapping("editAttribute")
    @SysLog(title = "设备管理", businessType = OperaType.INSERT,logType = 0,module = "基础管理->设备管理",details ="修改设备属性" )
    public AjaxResult editAttribute(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file, String params) {
        return deviceservice.editAttribute(file, params);
    }

    /**
     * 删除设备属性
     */

    @PostMapping("delDeviceAttribute")
    @SysLog(title = "设备管理", businessType = OperaType.UPDATE,module = "基础管理->设备管理",details = "删除设备属性")
    public AjaxResult delDeviceAttribute(@RequestBody AttributeVo vo) {
        return deviceservice.delDeviceAttribute(vo.getId());

    }

    @GetMapping("exportDeviceSome")
    public void exportDeviceSome(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "ids") String ids) {
        try {
            List<DeviceExportVo> deviceExportVoList = new ArrayList<>();
            String[] idAll = ids.split(",");
            List<DeviceVo> deviceLists = deviceMapper.getDeviceSomeLists(idAll);
            for (int i = 0; i < deviceLists.size(); i++) {
                DeviceExportVo exportVo = new DeviceExportVo();
                if(deviceLists.get(i).getLyType()==0){
                    String name = deviceMapper.getDeviceLyName(deviceLists.get(i).getLyId());
                    deviceLists.get(i).setLyName(name);
                }else if(deviceLists.get(i).getLyType()==1){
                    String name = deviceMapper.getDeviceLyNameTemp(deviceLists.get(i).getLyId());
                    deviceLists.get(i).setLyName(name);
                }
                DeviceVo vo = deviceLists.get(i);
                BeanUtils.copyProperties(vo, exportVo);
                exportVo.setId((i + 1) + "");
                exportVo.setDeviceName(vo.getDeviceName());
                exportVo.setDeviceTypeName(vo.getDeviceTypeName());
                exportVo.setDeviceCode(vo.getDeviceCode());
                exportVo.setLyName(vo.getLyName());
                exportVo.setDeviceStatus(vo.getDeviceStatus() == BusinessConstants.TYPE3 ? "在用" : vo.getDeviceStatus() == BusinessConstants.TYPE ? "未用" : "其他");
                deviceExportVoList.add(exportVo);
            }
            ExportParams exportParams = new ExportParams("设备", "设备", ExcelType.XSSF);
            exportParams.setStyle(ExcelStyleUtil.class);
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, DeviceExportVo.class, deviceExportVoList);
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode("设备" + ".xlsx", "UTF-8"));
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.close();
            workbook.close();
        } catch (Exception e) {
            log.error(e.toString(), e);
        }
    }
}
