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

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.hc.business.dto.OrdersDto;
import com.hc.business.model.OrderStatus;
import com.hc.business.model.Orders;
import com.hc.business.service.AliPayService;
import com.hc.business.service.OrdersService;
import com.hc.core.utils.enums.InfoEnum;
import com.hc.core.utils.result.Result;
import com.hc.core.utils.tool.ResultUtils;
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.util.StringUtils;
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.*;


/**
 * 订单表(Orders)表控制层
 *
 * @author java
 * @since 2020-11-26 16:46:48
 */

@RestController
@RequestMapping("/new/api/back/orders")
public class BackOrdersController {

    /**
     * 服务对象
     */
    private final OrdersService ordersService;

    private final AliPayService aliPayService;

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

    public BackOrdersController(OrdersService ordersService, AliPayService aliPayService) {
        this.ordersService = ordersService;
        this.aliPayService = aliPayService;
    }

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

    @PostMapping("/insert")
    @ApiOperation(value = "新增 Orders", response = Result.class)
    public Result addBackOrders(@Valid @RequestBody Orders orders) {
        return Result.success(ordersService.insert(orders));
    }

    @PutMapping("/update")
    @ApiOperation(value = "修改 Orders", response = Result.class)
    public Result updateBackOrders(@RequestBody Orders orders) {
        return Result.success(ordersService.update(orders));
    }

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

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

    @GetMapping("/class/list")
    @ApiOperation(value = "依据班次id 获取 Orders列表(分页)", response = Result.class)
    public Result listBackOrdersByClassId(@ApiParam(value = "班次id") @RequestParam Integer classId,
                                          @RequestParam(defaultValue = "0") Integer page,
                                          @RequestParam(defaultValue = "0") Integer size) {
        return Result.success(ordersService.queryAllByClassId(page, size, classId));
    }

    @GetMapping("/className")
    @ApiOperation(value = "依据班次名称 获取 Orders列表(分页)", response = Result.class)
    public Result listBackOrdersByClassName(@ApiParam(value = "班次名称") @RequestParam String className,
                                            @RequestParam(defaultValue = "0") Integer page,
                                            @RequestParam(defaultValue = "0") Integer size) {
        return Result.success(ordersService.queryAllByClassName(page, size, className));
    }

    @GetMapping("/status/list")
    @ApiOperation(value = "依据状态 获取 Orders列表(分页)", response = Result.class)
    public Result listBackOrdersByStatus(@ApiParam(value = "状态") @RequestParam Integer status,
                                         @RequestParam(defaultValue = "0") Integer page,
                                         @RequestParam(defaultValue = "0") Integer size) {
        return Result.success(ordersService.queryAllByStatus(page, size, status));
    }

    @GetMapping("/list/userInvoices")
    @ApiOperation(value = "获取 发票 Orders列表(分页)", response = Result.class)
    public Result listBackOrdersByUserInvoicesId(@ApiParam(value = "发票id") @RequestParam Integer userInvoicesId) {
        return Result.success(ordersService.queryByUserInvoicesId(userInvoicesId));
    }

    @GetMapping("/create/no")
    @ApiOperation(value = "创建一条订单编号", response = Result.class)
    public Result createOrderNo() {
        return Result.success(ordersService.createOrderNo());
    }

    @GetMapping("/count")
    @ApiOperation(value = "获取 订单金额统计数据", response = Result.class)
    public Result queryOrderCount() {
        return Result.success(ordersService.queryUserCount());
    }

    @GetMapping("/count/no")
    @ApiOperation(value = "获取 订单数量统计数据", response = Result.class)
    public Result queryOrderCountNo() {
        return Result.success(ordersService.countOrderTotal());
    }

    @GetMapping("/no")
    @ApiOperation(value = "依据订单编号获取 Orders", response = Result.class)
    public Result selectBackOrders(@ApiParam(value = "订单编号") @RequestParam String orderNo) {
        return Result.success(this.ordersService.queryByOrderNo(orderNo.trim()));
    }

    @GetMapping("/queryAllOrders")
    @ApiOperation(value = "查询订单管理", response = Result.class)
    public Result queryAllOrders(@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部分退费 null查全部") @RequestParam(required = false) Integer status,
                                   @ApiParam(value = "支付类型0123，0支付宝，1微信，2微信移动端，3线下汇款 null查全部") @RequestParam(required = false) Integer payType,
                                   @ApiParam(value = "审核结果：1通过2拒绝0审核中 null全部(根据remark是否有值判断是否拒绝有值表示拒绝)") @RequestParam(required = false) Integer checkFlag,
                                   @ApiParam(value = "付款单位") @RequestParam(required = false) String payCompany,
                                   @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(this.ordersService.queryAllOrders(page, size, orderId, orderNo, status, payType, classId,checkFlag,payCompany, begin, end));
    }

    @GetMapping("/queryAllOrdersExport")
    @ApiOperation(value = "订单-全部导出", response = Result.class)
    public Result queryAllOrdersExport(@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部分退费 null查全部") @RequestParam(required = false) Integer status,
                                 @ApiParam(value = "支付类型0123，0支付宝，1微信，2微信移动端，3线下汇款 null查全部") @RequestParam(required = false) Integer payType,
                                 @ApiParam(value = "审核结果：1通过2拒绝0审核中 null全部(根据remark是否有值判断是否拒绝有值表示拒绝)") @RequestParam(required = false) Integer checkFlag,
                                 @ApiParam(value = "付款单位") @RequestParam(required = false) String payCompany,
                                 @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.ordersService.queryAllOrders(1, 50000, orderId, orderNo, status, payType, classId,checkFlag,payCompany, begin, end);
        List<OrdersDto> 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("ordersId", "userId", "classId", "orderStatus", "type", "price", "createTime");
        EasyExcel.write(outputStream, OrdersDto.class).excludeColumnFieldNames(strList).registerWriteHandler(new ExcelWidthStyleStrategy()).sheet("订单-全部导出").doWrite(dataList);
        return Result.success("/jxjyfile/" + newName);
    }

    //状态0123审核中，拒绝，通过，处理完毕
    @PutMapping("/updateOrdertatus")
    @ApiOperation(value = "修改订单状态（线下汇款，后台处理通过和拒绝）", response = Result.class)
    public Result updateOrdertatus(@RequestBody OrderStatus orderStatus) {
        Orders entity = this.ordersService.queryById(orderStatus.getOrderId());
        if (entity != null) {

            //通过
            if(orderStatus.getCheckFlag()==1)
            {
                String outTradeNo =entity.getOrderNo();
                String tradeNo = ResultUtils.getUUID();
                String tradeStatus = "TRADE_SUCCESS";
                aliPayService.returnNotifyUrlInfo(outTradeNo, tradeNo, tradeStatus);
                //变更订单状态
                return Result.success();
            }
            else if(orderStatus.getCheckFlag()==2)//拒绝
            {
                if(!StringUtils.hasText(orderStatus.getRemark()))
                {
                    return Result.info(InfoEnum.NULL_PARAMETER);
                }

                entity.setRemark(orderStatus.getRemark());//拒绝,填入拒绝理由
                ordersService.update(entity);
                return Result.success();
            }
            else if(orderStatus.getCheckFlag()==0)//重新发起支付
            {
                entity.setRemark("");//清空拒绝
                ordersService.update(entity);
                return Result.success();
            }

            return Result.info(InfoEnum.NULL_PARAMETER);
        } else {
            return Result.info(InfoEnum.NULL_PARAMETER);
        }
    }
}