package com.zd.bottle.controller;

import cn.hutool.core.collection.CollUtil;
import com.zd.bottle.domain.UseRecord;
import com.zd.bottle.dto.UseRecordDto;
import com.zd.bottle.service.UseRecordService;
import com.zd.bottle.vo.AirAmount;
import com.zd.bottle.vo.UseRecordVo;
import com.zd.bottle.vo.WebUseRecordVo;
import com.zd.common.core.domain.per.PerFun;
import com.zd.common.core.domain.per.PerPrefix;
import com.zd.common.core.utils.DateUtils;
import com.zd.common.core.utils.SecurityUtils;
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 io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 使用记录表 前端控制器
 * </p>
 *
 * @author hanson
 * @since 2022-09-08
 */
@RestController
@Api(tags = "【使用记录表】")
@RequestMapping("/useRecord")
public class UseRecordController extends BaseController<UseRecord> {
    @Resource
    private UseRecordService useRecordService;

    private static final String ORDER_BY_DESC="descending";

    /**
     * 查询使用记录列表(学生端)
     */
    @GetMapping("/list")
    @ApiOperation(value = "查询使用记录列表")
    public TableDataInfo<UseRecordVo> list(UseRecord useRecord) {
        startPage("use_time",ORDER_BY_DESC);
        useRecord.setUserId(SecurityUtils.getUserId());
        List<UseRecord> records =useRecordService.getList(useRecord);
        TableDataInfo<UseRecord> dataTable = getDataTable(records);
        TableDataInfo<UseRecordVo> info = new TableDataInfo<>();
        if (CollUtil.isNotEmpty(records)) {
            BeanUtils.copyProperties(dataTable, info);
            List<UseRecordVo> recordVos = useRecordService.getListVo(records);
            info.setRows(recordVos);
        }
        return info;
    }


    /**
     * 查询使用记录列表(管理端)
     */
    @PreAuthorize(hasPermi = PerPrefix.BOTTLE_USERECORDADMIN + PerFun.LIST)
    @GetMapping("/listByAdmin")
    @ApiOperation(value = "查询使用记录列表")
    public TableDataInfo<UseRecordVo> listByAdmin(UseRecord useRecord) {
        startPage("use_time",ORDER_BY_DESC);
        List<UseRecord> records =useRecordService.getList(useRecord);
        TableDataInfo<UseRecord> dataTable = getDataTable(records);
        TableDataInfo<UseRecordVo> info = new TableDataInfo<>();
        if (CollUtil.isNotEmpty(records)) {
            BeanUtils.copyProperties(dataTable, info);
            List<UseRecordVo> recordVos = useRecordService.getListVo(records);
            info.setRows(recordVos);
        }
        return info;
    }

    /**
     * 信息统计查询使用记录列表
     * @param storageId 库存主ID
     * @return 集合对象
     */
    @GetMapping("/bottle/list/{storageId}")
    @ApiOperation(value = "信息统计查询使用记录列表")
    public List<UseRecordVo> bottleList(@PathVariable Long storageId) {
        return useRecordService.getBottleInfoByStorageId(storageId);
    }

    /**
     * 导出使用记录列表(学生端)
     */
    @ApiOperation(value = "导出使用记录列表")
    @Log(title = "使用记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UseRecord useRecord) throws IOException {
        useRecord.setUserId(SecurityUtils.getUserId());
        List<UseRecord> records =useRecordService.getList(useRecord);
        List<UseRecordVo> info = new ArrayList<>();
        if (CollUtil.isNotEmpty(records)) {
            info = useRecordService.getListVo(records);
            info.forEach(i-> {
                BigDecimal afterUse = i.getAfterUse();
                i.setBeforeUseValue(i.getBeforeUse().stripTrailingZeros().toPlainString()+"MPa");
                if (afterUse!=null){
                    i.setAfterUseValue(afterUse.stripTrailingZeros().toPlainString()+"MPa");
                }
            });
        }
        ExcelUtil<UseRecordVo> util = new ExcelUtil<>(UseRecordVo.class);
        util.exportExcel(response, info, "使用记录数据" + DateUtils.getDate());
    }


    /**
     * 导出使用记录列表(管理端)
     */
    @PreAuthorize(hasPermi = PerPrefix.BOTTLE_USERECORDADMIN + PerFun.EXPORT)
    @ApiOperation(value = "导出使用记录列表")
    @Log(title = "使用记录", businessType = BusinessType.EXPORT)
    @PostMapping("/exportByAdmin")
    public void exportByAdmin(HttpServletResponse response, UseRecord useRecord) throws IOException {
        List<UseRecord> records =useRecordService.getList(useRecord);
        List<UseRecordVo> info = new ArrayList<>();
        if (CollUtil.isNotEmpty(records)) {
            info = useRecordService.getListVo(records);
            info.forEach(i-> {
                BigDecimal afterUse = i.getAfterUse();
                i.setBeforeUseValue(i.getBeforeUse().stripTrailingZeros().toPlainString()+"MPa");
                if (afterUse!=null){
                    i.setAfterUseValue(afterUse.stripTrailingZeros().toPlainString()+"MPa");
                }
            });
        }
        ExcelUtil<UseRecordVo> util = new ExcelUtil<>(UseRecordVo.class);
        util.exportExcel(response, info, "使用记录数据" + DateUtils.getDate());
    }

    /**
     * 管理端端获取使用记录详细信息(学生端)
     */
    @ApiOperation(value = "管理端端获取使用记录详细信息")
    @GetMapping(value = "/bottle/{id}")
    public ResultData<WebUseRecordVo> getBottleInfo(@PathVariable("id") Long id) {
        return ResultData.success(useRecordService.getBottleInfo(id));
    }

    /**
     * 管理端端获取使用记录详细信息(管理端)
     */
    @PreAuthorize(hasPermi = PerPrefix.BOTTLE_USERECORDADMIN + PerFun.QUERY)
    @ApiOperation(value = "管理端端获取使用记录详细信息")
    @GetMapping(value = "/bottleByAdmin/{id}")
    public ResultData<WebUseRecordVo> getBottleInfoByAdmin(@PathVariable("id") Long id) {
        return ResultData.success(useRecordService.getBottleInfo(id));
    }

    /**
     * 信息统计管理端端获取气瓶使用记录详细信息
     */
    @ApiOperation(value = "信息统计管理端端获取气瓶使用记录详细信息")
    @GetMapping(value = "/bottle/record/{storageId}")
    public ResultData<WebUseRecordVo> getBottleRecord(@PathVariable("storageId") Long storageId) {
        return ResultData.success(useRecordService.getBottleRecord(storageId));
    }

    /**
     * 出入库信息统计
     */
    @ApiOperation(value = "出入库信息统计")
    @GetMapping(value = "/calcRepertory")
    public ResultData<List<AirAmount>> calcRepertory(String airName) {
        return ResultData.success(useRecordService.calcRepertory(airName));
    }

    /**
     * 用气量信息统计
     */
    @ApiOperation(value = "用气量信息统计")
    @GetMapping(value = "/calcAmount")
    public ResultData<List<AirAmount>> calcAmount(String airName) {
        return ResultData.success(useRecordService.calcAmount(airName));
    }

    /**
     * 用气申请统计
     */
    @ApiOperation(value = "用气申请统计")
    @GetMapping(value = "/calcApply")
    public ResultData<List<AirAmount>> calcApply(String airName) {
        return ResultData.success(useRecordService.calcApply(airName));
    }

    /**
     * 新增使用登记
     * value 说明：
     * 1：正常状态
     * 2：气瓶余量接近安全值
     * 3：用户没有用气资格
     * 4：气瓶正在使用中
     */
    @ApiOperation(value = "新增使用登记")
    @PreAuthorize(hasPermi = PerPrefix.BOTTLE_USERECORDADMIN + PerFun.ADD)
    @Log(title = "新增使用登记", businessType = BusinessType.INSERT)
    @PostMapping
    public ResultData<Integer> add(@RequestBody UseRecordDto recordDto) {
        return ResultData.success(useRecordService.add(recordDto));
    }

    /**
     * 归还登记
     */
    @ApiOperation(value = "归还登记")
    @PreAuthorize(hasPermi = PerPrefix.BOTTLE_USERECORDADMIN + PerFun.EDIT)
    @Log(title = "归还登记", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResultData<Boolean> edit(@RequestBody UseRecord useRecord) {
        return ResultData.result(useRecordService.updateUseRecord(useRecord));
    }

    /**
     * 领用气瓶-学生端
     * value 说明：
     * 1：正常状态
     * 2：气瓶余量接近安全值
     * 3：用户没有用气资格
     * 4：气瓶正在使用中
     */
    @ApiOperation(value = "领用气瓶-学生端")
    @Log(title = "领用气瓶-学生端", businessType = BusinessType.INSERT)
    @PostMapping("/student")
    public ResultData<Integer> addStudent(@RequestBody UseRecordDto recordDto) {
        return ResultData.success(useRecordService.add(recordDto));
    }

    /**
     * 归还登记-学生端
     */
    @ApiOperation(value = "归还登记-学生端")
    @Log(title = "归还登记-学生端", businessType = BusinessType.UPDATE)
    @PostMapping("/editStudent")
    public ResultData<Boolean> editStudent(@RequestBody UseRecord useRecord) {
        return ResultData.result(useRecordService.updateUseRecord(useRecord));
    }

    /***
     * 查询使用记录(学生端)
     */
    @ApiOperation(value = "查询使用记录")
    @GetMapping(value = "/getUseDetails")
    public TableDataInfo<UseRecord> getUseDetails(UseRecord useRecord) {
        startPage("create_time",ORDER_BY_DESC);
        useRecord.setUserId(SecurityUtils.getUserId());
        List<UseRecord> records =useRecordService.getList(useRecord);
        return getDataTable(records);
    }


    /***
     * 查询使用记录(管理端)
     */
    @PreAuthorize(hasPermi = PerPrefix.BOTTLE_USERECORDADMIN + PerFun.LISTDETAIL)
    @ApiOperation(value = "查询使用记录")
    @GetMapping(value = "/getUseDetailsByAdmin")
    public TableDataInfo<UseRecord> getUseDetailsByAdmin(UseRecord useRecord) {
        startPage("create_time",ORDER_BY_DESC);
        List<UseRecord> records =useRecordService.getList(useRecord);
        return getDataTable(records);
    }

    /**
     * 当前登录人的气瓶使用记录
     */
    @ApiOperation(value = "当前登录人的气瓶使用记录")
    @GetMapping(value = "/getUseDetailsByUserId")
    public TableDataInfo<UseRecord> getUseDetailsByUserId(UseRecord useRecord) {
        startPage();
        List<UseRecord> list =  useRecordService.getByUserId(useRecord);
        return getDataTable(list);
    }

    /***
     * 查询某个气瓶的使用记录汇总
     */
    @ApiOperation(value = "查询某个气瓶的使用记录汇总")
    @GetMapping(value = "/getUseDetailsByStorageId")
    public TableDataInfo<UseRecord> getUseDetailsByStorageId(UseRecord useRecord) {
        startPage();
        List<UseRecord> list =  useRecordService.getByStorageId(useRecord.getStorageId());
        return getDataTable(list);
    }
}
