package com.zd.laboratory.controller;

import cn.hutool.core.util.StrUtil;
import com.zd.common.core.domain.per.PerFun;
import com.zd.common.core.domain.per.PerPrefix;
import com.zd.common.core.utils.FileConfigUtils;
import com.zd.common.core.utils.UrlFormatUtils;
import com.zd.common.core.utils.poi.ExcelUtil;
import com.zd.common.core.web.controller.BaseController;
import com.zd.common.core.web.domain.ResultData;
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.LabSafeBook;
import com.zd.laboratory.service.ILabSafeBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 实验室安全制度Controller
 *
 * @author liubo
 * @date 2021-11-19
 */
@RestController
@Api(tags = "【实验室安全制度】")
@RequestMapping("/safe_book")
public class LabSafeBookController extends BaseController {
    @Autowired
    private ILabSafeBookService labSafeBookService;

    @Autowired
    private FileConfigUtils fileConfigUtils;
    /**
     * 查询实验室安全制度列表
     */
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_SAFEBOOK + PerFun.LIST)
    @GetMapping("/list")
    @ApiOperation(value = "查询实验室安全制度列表")
    public TableDataInfo<LabSafeBook> list(LabSafeBook labSafeBook) {
        startPage();
        List<LabSafeBook> list = labSafeBookService.selectLabSafeBookList(labSafeBook);
        Optional.ofNullable(list).ifPresent(a->{
            Map<String, String> safe_type = DictUtils.getDictCacheMap("safe_type");
            a.forEach(b->{
                if(safe_type.containsKey(b.getType()))
                {
                    b.setTypeLable(safe_type.get(b.getType()));
                }
                else
                {
                    b.setTypeLable(StrUtil.EMPTY);
                }
            });
        });
        return getDataTable(list);
    }

    /**
     * 一体机查询实验室安全制度列表（不分页）
     *
     * @return
     */
    @GetMapping("/queryOption")
    @ApiOperation(value = "查询实验室安全制度列表")
    public List<LabSafeBook> queryOption(LabSafeBook labSafeBook, HttpServletRequest request) {
        List<LabSafeBook> list = labSafeBookService.selectLabSafeBookList(labSafeBook);
        String baseUrl=request.getServerName() ;

        Optional.ofNullable(list).ifPresent(a->{
            Map<String, String> safe_type = DictUtils.getDictCacheMap("safe_type");
            a.forEach(b->{
                if(StringUtils.isNotBlank(b.getContent())){
                    String url=fileConfigUtils.getRemoteUrl()+ File.separator+b.getContent();
                    if(baseUrl.contains("192.168")){
                        url=fileConfigUtils.getLocalUrl()+ File.separator+b.getContent();
                    }

                    url= UrlFormatUtils.getHttpsORHttpUrl(url);
                    b.setContent(url);
                }
                if(safe_type.containsKey(b.getType()))
                {
                    b.setTypeLable(safe_type.get(b.getType()));
                }
                else
                {
                    b.setTypeLable(StrUtil.EMPTY);
                }
            });
        });
        return list;
    }

    /**
     * 导出实验室安全制度列表
     */
    @ApiOperation(value = "导出实验室安全制度列表")
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_SAFEBOOK + PerFun.EXPORT)
    @Log(title = "实验室安全制度", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, LabSafeBook labSafeBook) throws IOException {
        List<LabSafeBook> list = labSafeBookService.selectLabSafeBookList(labSafeBook);
        ExcelUtil<LabSafeBook> util = new ExcelUtil<LabSafeBook>(LabSafeBook.class);
        util.exportExcel(response, list, "实验室安全制度数据");
    }

    /**
     * 小程序二维码 查询数据详情 并记录count
     */
    @ApiOperation(value = "二维码 查询数据详情 并记录count")
    @GetMapping(value = "/lookUp/{id}")
    public ResultData<LabSafeBook> lookUp(@PathVariable("id") Long id) {
        LabSafeBook safeBook = labSafeBookService.selectLabSafeBookById(id);
        if(safeBook != null){
            safeBook.setScanCount(safeBook.getScanCount() + 1);
            labSafeBookService.updateLabSafeBook(safeBook);
        }
        return ResultData.success(safeBook);
    }

    /**
     * 获取实验室安全制度详细信息
     */
    @ApiOperation(value = "获取实验室安全制度详细信息")
//    @PreAuthorize(hasPermi = "laboratory:safe_book:query")
    @GetMapping(value = "/{id}")
    public ResultData<LabSafeBook> getInfo(@PathVariable("id") Long id, HttpServletRequest request) {
        // TODO: 2022/3/25  基于内外网访问先做成这个样子，后期优化
        //String baseUrl=request.getServerName();
        String baseUrl=request.getHeader("X-Real-IP");
        String baseUrls=request.getHeader("X-Forwarded-For");
        logger.info("X-Real-IP:"+baseUrl+"  "+"X-Forwarded-For:"+baseUrls);
        LabSafeBook labSafeBook=labSafeBookService.selectLabSafeBookById(id);
        String url="";
        if(baseUrl.contains("192.168")){
            url=fileConfigUtils.getLocalUrl()+labSafeBook.getContent();
        }else{
            url=fileConfigUtils.getRemoteUrl()+labSafeBook.getContent();
        }
        url= UrlFormatUtils.getHttpsORHttpUrl(url);
        labSafeBook.setContent(url);
        return ResultData.success(labSafeBook);
    }

    /**
     * 新增实验室安全制度
     */
    @ApiOperation(value = "新增实验室安全制度")
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_SAFEBOOK + PerFun.ADD)
    @Log(title = "实验室安全制度", businessType = BusinessType.INSERT)
    @PostMapping
    public ResultData add(@RequestBody LabSafeBook labSafeBook) {
        return ResultData.result(labSafeBookService.insertLabSafeBook(labSafeBook));
    }

    /**
     * 修改实验室安全制度
     */
    @ApiOperation(value = "修改实验室安全制度")
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_SAFEBOOK + PerFun.EDIT)
    @Log(title = "实验室安全制度", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResultData edit(@RequestBody LabSafeBook labSafeBook) {
        return ResultData.result(labSafeBookService.updateLabSafeBook(labSafeBook));
    }

    /**
     * 删除实验室安全制度
     */
    @ApiOperation(value = "删除实验室安全制度")
    @PreAuthorize(hasPermi = PerPrefix.LABORATORY_SAFEBOOK + PerFun.REMOVE)
    @Log(title = "实验室安全制度", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public ResultData remove(@PathVariable Long[] ids) {
        return ResultData.result(labSafeBookService.deleteLabSafeBookByIds(ids));
    }
}
