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

import com.alibaba.excel.EasyExcel;
import com.hc.business.dto.OrderRefundAllDto;
import com.hc.business.model.OrderRefund;
import com.hc.business.model.OrderRefundStatus;
import com.hc.business.service.OrderRefundService;
import com.hc.core.utils.enums.InfoEnum;
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;

/**
 * 退费订单记录表(OrderRefund)表控制层
 *
 * @author makejava
 * @since 2024-01-20 11:50:55
 */

@RestController
@RequestMapping("/new/api/back/orderRefund")
public class BackOrderRefundController {

    /**
     * 服务对象
     */
    private final OrderRefundService orderRefundService;

    @Value("${setting.downloadPath}")
    public String downloadPath;

    public BackOrderRefundController(OrderRefundService orderRefundService) {
        this.orderRefundService = orderRefundService;
    }

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

    @PostMapping("/insert")
    @ApiOperation(value = "新增 OrderRefund", response = Result.class)
    public Result addOrderRefund(@Valid @RequestBody OrderRefund orderRefund) {
        return Result.success(orderRefundService.insert(orderRefund));
    }

    @PutMapping("/update")
    @ApiOperation(value = "修改 OrderRefund", response = Result.class)
    public Result updateOrderRefund(@RequestBody OrderRefund orderRefund) {
        return Result.success(orderRefundService.update(orderRefund));
    }

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

    @GetMapping("/listOrderRefund")
    @ApiOperation(value = "获取 退费单列表(分页)", response = Result.class)
    public Result listOrderRefund(@ApiParam(value = "订单号") @RequestParam(required = false) String orderNo,
                                  @ApiParam(value = "订单id") @RequestParam(required = false) Integer orderId,
                                  @ApiParam(value = "班次id") @RequestParam(required = false) Integer classId,
                                  @ApiParam(value = "状态0审核中(新退费订单)，1拒绝，2通过，3处理完毕 4已处理订单（2通过，3处理完毕） 5（1拒绝，2通过） null查全部") @RequestParam(required = false) Integer status,
                                  @ApiParam(value = "支付类型0123，支付宝，微信，微信移动端，线下汇款 null查全部") @RequestParam(required = false) Integer payType,
                                  @ApiParam(value = "创建时间开始毫秒时间戳，默认3个月") @RequestParam(required = false) Long begin,
                                  @ApiParam(value = "创建时间结束毫秒时间戳，默认3个月") @RequestParam(required = false) Long end,
                                  @RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "20") Integer size) {
        return Result.success(orderRefundService.queryAll(page, size, orderId, orderNo, status, payType, classId, begin, end));
    }


    //状态0123审核中，拒绝，通过，处理完毕
    @PutMapping("/updateOrderRefundStatus")
    @ApiOperation(value = "修改退费单状态", response = Result.class)
    public Result updateOrderRefundStatus(@RequestBody OrderRefundStatus orderRefund) {
        OrderRefund entity = this.orderRefundService.queryById(orderRefund.getRefundId());
        if (entity != null) {
            entity.setStatus(orderRefund.getStatus());
            if (orderRefund.getStatus() == 1 || orderRefund.getStatus() == 2) {
                entity.setYewuNote(orderRefund.getRemark());
                entity.setYewuTime(System.currentTimeMillis());
            } else if (orderRefund.getStatus() == 2) {
                {
                    entity.setFincalNote(orderRefund.getRemark());
                    entity.setFincalTime(System.currentTimeMillis());
                }
            }
            return Result.success(orderRefundService.update(entity));
        } else {
            return Result.info(InfoEnum.NULL_PARAMETER);
        }
    }

    @GetMapping("/queryAllExport")
    @ApiOperation(value = "财务退费导出", response = Result.class)
    public Result queryAllExport(@ApiParam(value = "订单号") @RequestParam(required = false) String orderNo,
                                 @ApiParam(value = "订单id") @RequestParam(required = false) Integer orderId,
                                 @ApiParam(value = "班次id") @RequestParam(required = false) Integer classId,
                                 @ApiParam(value = "状态0审核中(新退费订单)，1拒绝，2通过，3处理完毕 4已处理订单（2通过，3处理完毕） 5（1拒绝，2通过） null查全部") @RequestParam(required = false) Integer status,
                                 @ApiParam(value = "支付类型0123，支付宝，微信，微信移动端，线下汇款 null查全部") @RequestParam(required = false) Integer payType,
                                 @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();
        }

        List<OrderRefundAllDto> dataList = this.orderRefundService.queryHighAll(orderId, orderNo, status, payType, classId, begin, end);
        // 对上传的文件重命名，避免文件重名
        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("payType", "payTime", "refundTime", "fincalTime","yewuTime",  "syncStatus","invoicesNo","invoicesBank","status");
        EasyExcel.write(outputStream, OrderRefundAllDto.class).excludeColumnFieldNames(strList).registerWriteHandler(new ExcelWidthStyleStrategy()).sheet("财务退费导出").doWrite(dataList);
        return Result.success("/jxjyfile/" + newName);
    }
}
