package com.xinelu.manage.controller.nursestationitem;


import com.xinelu.common.annotation.Log;
import com.xinelu.common.constant.Constants;
import com.xinelu.common.core.controller.BaseController;
import com.xinelu.common.core.domain.AjaxResult;
import com.xinelu.common.core.page.TableDataInfo;
import com.xinelu.common.custominterface.Insert;
import com.xinelu.common.custominterface.Update;
import com.xinelu.common.enums.BusinessType;
import com.xinelu.common.exception.ServiceException;
import com.xinelu.common.utils.poi.ExcelUtil;
import com.xinelu.manage.domain.nursestationitem.NurseStationItem;
import com.xinelu.manage.dto.nursestationitem.NurseStationItemDTO;
import com.xinelu.manage.dto.nursestationitem.NurseStationItemImportDTO;
import com.xinelu.manage.service.nursestationitem.INurseStationItemService;
import com.xinelu.manage.vo.nursestationitem.NurseStationItemVO;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ResourceUtils;
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.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * 护理站护理项目Controller
 *
 * @author ljh
 * @date 2022-09-02
 */
@RestController
@RequestMapping("/system/stationItem")
public class NurseStationItemController extends BaseController {
    @Resource
    private INurseStationItemService nurseStationItemService;

    /**
     * 查询护理站护理项目列表
     */
    @PreAuthorize("@ss.hasPermi('system:stationItem:list')")
    @GetMapping("/list")
    public TableDataInfo list(NurseStationItem nurseStationItem) {
        List<NurseStationItemVO> list = nurseStationItemService.selectNurseStationItemList(nurseStationItem);
        return getDataTable(list);
    }

    /**
     * 导出护理站护理项目列表
     */
    @PreAuthorize("@ss.hasPermi('system:stationItem:export')")
    @Log(title = "护理站护理项目", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, NurseStationItem nurseStationItem) {
        List<NurseStationItemVO> list = nurseStationItemService.selectNurseStationItemList(nurseStationItem);
        ExcelUtil<NurseStationItemVO> util = new ExcelUtil<>(NurseStationItemVO.class);
        util.exportExcel(response, list, "护理站护理项目数据");
    }

    /**
     * 获取护理站护理项目详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:stationItem:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(nurseStationItemService.selectNurseStationItemById(id));
    }

    /**
     * 新增护理站护理项目
     */
    @PreAuthorize("@ss.hasPermi('system:stationItem:add')")
    @Log(title = "护理站护理项目", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated(Insert.class) @RequestBody NurseStationItemDTO nurseStationItemDTO) {
        return nurseStationItemService.insertNurseStationItem(nurseStationItemDTO);
    }

    /**
     * 修改护理站护理项目
     */
    @PreAuthorize("@ss.hasPermi('system:stationItem:edit')")
    @Log(title = "护理站护理项目", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@Validated(Update.class) @RequestBody NurseStationItemDTO nurseStationItemDTO) {
        return nurseStationItemService.updateNurseStationItem(nurseStationItemDTO);
    }

    /**
     * 删除护理站护理项目
     */
    @PreAuthorize("@ss.hasPermi('system:stationItem:remove')")
    @Log(title = "护理站护理项目", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return nurseStationItemService.deleteNurseStationItemByIds(ids);
    }

    /**
     * 护理项目上下架
     */
    @PostMapping("/updateShelfStatus")
    public AjaxResult updateShelfStatus(Long id, String shelfStatus) {
        if (Objects.isNull(id)) {
            return AjaxResult.error("护理项目为空！");
        }
        if (StringUtils.isBlank(shelfStatus)) {
            return AjaxResult.error("上架状态为空！");
        }
        return nurseStationItemService.updateShelfStatus(id, shelfStatus);
    }

    /**
     * 导入护理站项目
     */
    @PreAuthorize("@ss.hasPermi('system:stationItem:importStationItem')")
    @Log(title = "导入护理站项目信息", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        //判断excel里面是否有数据/文件格式
        if (Objects.isNull(file) || StringUtils.isBlank(file.getOriginalFilename())) {
            return AjaxResult.error("请选择所需要导入的文件！");
        }
        //获取文件名
        String fileName = file.getOriginalFilename();
        if (!fileName.endsWith(Constants.XLSX) && !fileName.endsWith(Constants.XLS)) {
            return AjaxResult.error("导入文件格式不正确，请导入xlsx或xls格式的文件！");
        }
        ExcelUtil<NurseStationItemImportDTO> util = new ExcelUtil<>(NurseStationItemImportDTO.class);
        List<NurseStationItemImportDTO> list = util.importExcel(file.getInputStream());
        return nurseStationItemService.importData(list);
    }

    /**
     * 下载导入模板
     */
    @Log(title = "下载导入模板", businessType = BusinessType.IMPORT)
    @PostMapping("/downloadTemplate")
    public void download(@RequestParam(value = "fileType") String fileType, HttpServletResponse res) throws IOException {
        if (StringUtils.isBlank(fileType)) {
            throw new ServiceException("请选择文件类型！");
        }
        File file = null;
        if (fileType.equals(Constants.NURSE_STATION_ITEM_TEMPLATE)) {
            file = ResourceUtils.getFile("classpath:template/护理站项目基本信息导入模板.xlsx");
        }
        if (fileType.equals(Constants.NURSE_STATION_CONSUMABLE)) {
            file = ResourceUtils.getFile("classpath:template/护理耗材基本信息导入模板.xlsx");
        }
        if (Objects.isNull(file)) {
            throw new ServiceException("下载导入模板文件失败，请联系管理员！");
        }
        res.setCharacterEncoding("UTF-8");
        res.setHeader("Content-Disposition", "inline;filename=" + fileType + ".txt");
        res.setContentType("text/plain;UTF-8");
        ServletOutputStream os = res.getOutputStream();
        byte[] bytes = FileUtils.readFileToByteArray(file);
        os.write(bytes);
        os.flush();
        os.close();
    }
}