package com.xinelu.manage.controller.nursestation;


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.dto.nursestation.NurseStationDTO;
import com.xinelu.manage.dto.nursestation.NurseStationImportDTO;
import com.xinelu.manage.service.nursestation.INurseStationService;
import com.xinelu.manage.vo.nursestation.NurseStationSysUserVO;
import com.xinelu.manage.vo.nursestation.NurseStationVO;
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/station")
public class NurseStationController extends BaseController {
    @Resource
    private INurseStationService nurseStationService;

    /**
     * 查询护理站信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:station:list')")
    @GetMapping("/list")
    public TableDataInfo list(NurseStationVO nurseStation) {
        startPage();
        List<NurseStationVO> list = nurseStationService.selectNurseStationList(nurseStation);
        return getDataTable(list);
    }

    /**
     * 导出护理站信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:station:export')")
    @Log(title = "护理站信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, NurseStationVO nurseStation) {
        List<NurseStationVO> list = nurseStationService.selectNurseStationList(nurseStation);
        ExcelUtil<NurseStationVO> util = new ExcelUtil<>(NurseStationVO.class);
        util.exportExcel(response, list, "护理站信息数据");
    }

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

    /**
     * 新增护理站信息
     */
    @PreAuthorize("@ss.hasPermi('system:station:add')")
    @Log(title = "护理站信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated(Insert.class) @RequestBody NurseStationDTO nurseStation) {
        return nurseStationService.insertNurseStation(nurseStation);
    }

    /**
     * 修改护理站信息
     */
    @PreAuthorize("@ss.hasPermi('system:station:edit')")
    @Log(title = "护理站信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@Validated(Update.class) @RequestBody NurseStationDTO nurseStation) {
        return nurseStationService.updateNurseStation(nurseStation);
    }

    /**
     * 删除护理站信息
     */
    @PreAuthorize("@ss.hasPermi('system:station:remove')")
    @Log(title = "护理站信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return nurseStationService.deleteNurseStationByIds(ids);
    }


    /**
     * 头像图片上传
     */
    @PostMapping("/updateNurseStationHeads")
    public AjaxResult updateNurseStationHeads(@RequestParam("file") MultipartFile multipartFile, @RequestParam(value = "type") String type) throws Exception {
        if (Objects.isNull(multipartFile) || StringUtils.isBlank(multipartFile.getOriginalFilename())) {
            return AjaxResult.error("当前文件不存在，无法上传！");
        }
        if (multipartFile.getOriginalFilename().contains(Constants.EMPTY)) {
            return AjaxResult.error("当前文件名含有空格，请先去除空格在上传！");
        }
        if (StringUtils.isBlank(type)) {
            return AjaxResult.error("请选择所要上传的路径类型！");
        }
        return nurseStationService.updateNurseStationHeads(multipartFile, type);
    }


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

    /**
     * 查询护理站信息列表
     */
    @GetMapping("/getSysDictNurseTypeCode")
    public List<NurseStationVO> getSysDictNurseTypeCode(NurseStationVO nurseStation) {
        return nurseStationService.getSysDictNurseTypeCode(nurseStation);
    }

    /**
     * 护理站基本信息模板 护理人员基本信息导入模板
     *
     * @param fileType 文件类型
     * @param res      http请求
     **/
    @RequestMapping("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)) {
            file = ResourceUtils.getFile("classpath:template/护理站基本信息模板.xlsx");
        }
        if (fileType.equals(Constants.NURSE_STATION_PERSON)) {
            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();
    }


    /**
     * 查询护理站信息列表
     */
    @GetMapping("/getNurseStationType")
    public AjaxResult getNurseStationType(String nurseTypeCode) {
        return nurseStationService.getNurseStationType(nurseTypeCode);
    }

    /**
     * 查询护理站信息列表
     */
    @GetMapping("/nurseStationByUserId")
    public AjaxResult nurseStationByUserId(NurseStationSysUserVO sysUser) {
        return nurseStationService.getNurseStationByUserId(sysUser);
    }

    /**
     * 护理站生成二维码
     *
     * @param nurseStationId 护理站id
     * @return 邀请码图片地址
     */
    @PostMapping("/nurseStationCode")
    public AjaxResult nurseStationCode(Long nurseStationId) {
        if (Objects.isNull(nurseStationId)) {
            return AjaxResult.error("护理站id不能为空！");
        }
        return nurseStationService.nurseStationCode(nurseStationId);
    }
}
