package com.hc.web.controller.browser.back;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.hc.business.dto.UserInvoiceDto;
import com.hc.business.model.UserInvoices;
import com.hc.business.service.UserInvoicesService;
import com.hc.core.utils.result.Result;
import com.hc.web.config.ExcelWidthStyleStrategy;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;


/**
 * 用户发票表(UserInvoices)表控制层
 *
 * @author java
 * @since 2020-12-02 10:50:41
 */

@RestController
@RequestMapping("/new/api/back/userInvoices")
public class BackUserInvoicesController {

    /**
     * 服务对象
     */
    private final UserInvoicesService userInvoicesService;

    @Value("${setting.downloadPath}")
    public String downloadPath;
    public BackUserInvoicesController(UserInvoicesService userInvoicesService) {
        this.userInvoicesService = userInvoicesService;
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "依据主键获取 UserInvoices", response = Result.class)
    public Result selectBackUserInvoices(@PathVariable("id") Integer id) {
        return Result.success(this.userInvoicesService.queryById(id));
    }

    @PostMapping("/insert")
    @ApiOperation(value = "新增 UserInvoices", response = Result.class)
    public Result addBackUserInvoices(@Valid @RequestBody UserInvoices userInvoices) {
        return Result.success(userInvoicesService.insert(userInvoices));
    }

    @PutMapping("/update")
    @ApiOperation(value = "修改 UserInvoices", response = Result.class)
    public Result updateBackUserInvoices(@RequestBody UserInvoices userInvoices) {
        return Result.success(userInvoicesService.update(userInvoices));
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "依据主键删除 UserInvoices", response = Result.class)
    public Result deleteBackUserInvoices(@PathVariable("id") Integer id) {
        return Result.success(userInvoicesService.deleteById(id));
    }

    @GetMapping("/list")
    @ApiOperation(value = "获取列表(分页)", response = Result.class)
    public Result listBackUserInvoices(@RequestParam(defaultValue = "0") Integer page,
                                       @RequestParam(defaultValue = "0") Integer size) {
        return Result.success(userInvoicesService.queryAllByLimit(page, size));
    }

    @GetMapping("/list2")
    @ApiOperation(value = "获取专票，只查询专票 列表(分页)", response = Result.class)
    public Result listBackUserInvoices2(@ApiParam(value = "订单号") @RequestParam(required = false) String orderNo,
                                       @ApiParam(value = "创建时间开始毫秒时间戳，默认3个月") @RequestParam(required = false) Long begin,
                                       @ApiParam(value = "创建时间结束毫秒时间戳，默认3个月") @RequestParam(required = false) Long end,
                                       @RequestParam(defaultValue = "0") Integer page,
                                       @RequestParam(defaultValue = "0") Integer size) {
        return Result.success(userInvoicesService.queryAllInvoices(page, size,  orderNo,  begin, end));
    }

    @GetMapping("/queryAllInvoices")
    @ApiOperation(value = "专票-按查询条件全部导出", response = Result.class)
    public Result queryAllInvoices(@ApiParam(value = "订单号") @RequestParam(required = false) String orderNo,
                                       @ApiParam(value = "创建时间开始毫秒时间戳，默认3个月") @RequestParam(required = false) Long begin,
                                       @ApiParam(value = "创建时间结束毫秒时间戳，默认3个月") @RequestParam(required = false) Long end) {

        // 上传的文件将保存在项目运行目录下的 uploadFile 文件夹
        String realPath = downloadPath;

        // 并且在 uploadFile 文件夹中通过日期对上传的文件归类保存
        // 比如：/uploadFile/2019/06/06/32091e5f-c9e9-4506-9567-43e724f1fe37.png
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        String format = sdf.format(new Date());
        File folder = new File(realPath + format);
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }

        PageInfo pageInfo = this.userInvoicesService.queryAllInvoices(1, 50000,  orderNo,  begin, end);
        List<UserInvoiceDto> dataList   = pageInfo.getList();
        // 对上传的文件重命名，避免文件重名
        String newName = format + UUID.randomUUID() + "专票-全部导出.xlsx";
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(realPath + newName);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        List<String> strList = Arrays.asList("createTime", "orderStatus", "userMobile");
        EasyExcel.write(outputStream, UserInvoiceDto.class).excludeColumnFieldNames(strList).registerWriteHandler(new ExcelWidthStyleStrategy()).sheet("专票-全部导出").doWrite(dataList);
        return Result.success("/jxjyfile/" + newName);
    }

    @GetMapping("/user/{userId}")
    @ApiOperation(value = "获取用户发票信息", response = Result.class)
    public Result queryDetailByUserId(@ApiParam(value = "用户id") @PathVariable("userId") Integer userId) {
        return Result.success(userInvoicesService.queryDetailByUserId(userId));
    }

    @GetMapping("/class/{classId}")
    @ApiOperation(value = "获取班次发票信息", response = Result.class)
    public Result queryDetailByClassId(@ApiParam(value = "班次id") @PathVariable("classId") Integer classId) {
        return Result.success(userInvoicesService.queryByClassId(classId));
    }

    @GetMapping("/status")
    @ApiOperation(value = "获取用户发票信息", response = Result.class)
    public Result queryDetailByStatus(@ApiParam(value = "状态") @RequestParam Integer status) {
        return Result.success(userInvoicesService.queryByStatus(status));
    }


}