package com.willalp.web.controller.canteen;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.willalp.canteen.domain.HsGiftOrder;
import com.willalp.canteen.domain.HsOrderProcess;
import com.willalp.canteen.service.IHsGiftOrderService;
import com.willalp.canteen.service.IHsOrderProcessService;
import com.willalp.common.annotation.Log;
import com.willalp.common.core.controller.BaseController;
import com.willalp.common.core.domain.AjaxResult;
import com.willalp.common.core.page.TableDataInfo;
import com.willalp.common.enums.BusinessType;
import com.willalp.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 礼品订单Controller
 *
 * @author songyu
 * @date 2021-12-03
 */
@RestController
@RequestMapping("/gift/order")
public class HsGiftOrderController extends BaseController {
    @Autowired
    private IHsGiftOrderService hsCanteenOrderService;

    @Resource
    private IHsOrderProcessService orderProcessService;

    /**
     * 查询礼品订单列表
     */
    @GetMapping("/list")
    public TableDataInfo list(HsGiftOrder hsGiftOrder) {
        startPage();
        List<HsGiftOrder> list = hsCanteenOrderService.selectHsCanteenOrderList(hsGiftOrder);
        return getDataTable(list);
    }

    /**
     * 接单
     */
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping("/takeOrder")
    public AjaxResult takeOrder(@RequestBody HsGiftOrder hsGiftOrder) {
        HsOrderProcess orderProcess = new HsOrderProcess();
        if (hsGiftOrder.getZfbz() == 1) {
            orderProcess.setOrderNo(hsGiftOrder.getOrderNumber());
            orderProcess.setProcessDate(new Date());
            orderProcess.setProcessNum(2L);
            orderProcess.setProcessDesc("接单成功，正在准备您的物品");
            orderProcess.setProcessStatus(hsGiftOrder.getStatusText());
            hsGiftOrder.setZfbz(2);
        } else if (hsGiftOrder.getZfbz() == 2) {
            return AjaxResult.error("已接单，请勿重复接单");
        }
        try {
            orderProcessService.save(orderProcess);
            hsCanteenOrderService.updateById(hsGiftOrder);
        } catch (Exception e) {
            return AjaxResult.error("接单失败！");
        }
        return AjaxResult.success();
    }

    /**
     * 导出礼品订单列表
     */
    @Log(title = "礼品订单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(HsGiftOrder hsGiftOrder) {
        List<HsGiftOrder> list = hsCanteenOrderService.exportSelectGiftOrderList(hsGiftOrder);
        ExcelUtil<HsGiftOrder> util = new ExcelUtil<HsGiftOrder>(HsGiftOrder.class);
        return util.exportExcel(list, "礼品订单数据");
    }

    /**
     * 获取礼品订单详细信息
     */
    @GetMapping(value = "/{orderId}")
    public AjaxResult getInfo(@PathVariable("orderId") String orderId) {
        return AjaxResult.success(hsCanteenOrderService.getById(orderId));
    }

    /**
     * 新增礼品订单
     */
    @Log(title = "礼品订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HsGiftOrder hsGiftOrder) {
        while (true) {
            String idStr = IdWorker.getIdStr();
            HsGiftOrder byId = hsCanteenOrderService.getById(idStr);
            if (null == byId) {
                hsGiftOrder.setOrderId(idStr);
                break;
            }
        }
        return toAjax(hsCanteenOrderService.save(hsGiftOrder));
    }

    /**
     * 修改礼品订单
     */
    @Log(title = "礼品订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HsGiftOrder hsGiftOrder) {
        HsGiftOrder byId = hsCanteenOrderService.getById(hsGiftOrder.getOrderId());
        hsGiftOrder.setStatusText(byId.getStatusText());
        return toAjax(hsCanteenOrderService.updateById(hsGiftOrder));
    }

    /**
     * 因错退还礼品订单
     */
    @Log(title = "礼品订单因错退还", businessType = BusinessType.UPDATE)
    @RequestMapping("/partback")
    @PostMapping
    public AjaxResult partback(@RequestBody HsGiftOrder hsGiftOrder) {
        while (true) {
            String idStr = IdWorker.getIdStr();
            HsGiftOrder byId = hsCanteenOrderService.getById(idStr);
            if (null == byId) {
                hsGiftOrder.setOrderId(idStr);
                break;
            }
        }
        if (hsGiftOrder.getConsumeSign() != 0) {
            return AjaxResult.error("记账订单不可退还");
        }
        hsCanteenOrderService.checkOrderTotal(hsGiftOrder);
        hsGiftOrder.setZfbz(3);
        return toAjax(hsCanteenOrderService.save(hsGiftOrder));
    }


    /**
     * 删除礼品订单
     */
    @Log(title = "礼品订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{orderIds}")
    public AjaxResult remove(@PathVariable String[] orderIds) {
        return toAjax(hsCanteenOrderService.removeByIds(Arrays.asList(orderIds)));
    }

    /**
     * 作废礼品订单
     */
    @RequestMapping("/back")
    @ResponseBody
    public AjaxResult back(@RequestBody HsGiftOrder hsGiftOrder) {
        return hsCanteenOrderService.getBack(hsGiftOrder);
    }

    /**
     * 查询每日礼品订单量
     */
    @GetMapping("/lists")
    public Map lists(HsGiftOrder hsGiftOrder) {
        startPage();
        List<HsGiftOrder> list = hsCanteenOrderService.selectHsCanteenOrderLists(hsGiftOrder);
        Map map = new HashMap();
        if (list.size() > 0) {
            List<String> date = list.stream().filter(b -> 1 == 1).map(o -> (DateUtil.date(o.getPaytime()) + "").substring(0, 10)).collect(Collectors.toList());
            List<String> paylists = list.stream().filter(b -> 1 == 1).map(o -> o.getOrderId().toString()).collect(Collectors.toList());
            map.put("date", date);
            map.put("pay", paylists);
        }
        return map;
    }

    /**
     * 首页金额总数
     *
     * @param hsGiftOrder
     * @return
     */
    @GetMapping("/sumpay")
    public String Sumpay(HsGiftOrder hsGiftOrder) {
        startPage();
        String fee = hsCanteenOrderService.getSumpay(hsGiftOrder);
        return fee;
    }

    /**
     * 首页订单总数
     *
     * @param hsGiftOrder
     * @return
     */
    @GetMapping("/sumordernum")
    public String SumOrderNum(HsGiftOrder hsGiftOrder) {
        startPage();
        String total = hsCanteenOrderService.getSumOrderNum(hsGiftOrder);
        return total;
    }


    @GetMapping("/getFinishOrder")
    public AjaxResult getFinishOrder(HsGiftOrder hsGiftOrder) {
        List<HsGiftOrder> orders = hsCanteenOrderService.selectHsCanteenOrderList(hsGiftOrder);
        orders = orders.stream().filter(o -> o.getZfbz() == 2).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(orders)) {
            return AjaxResult.error("无订单信息");
        }
        return AjaxResult.success(orders);
    }

}
