package com.willalp.web.controller.canteen;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.willalp.common.enums.NumberRuleEnum;
import com.willalp.common.utils.DateUtils;
import com.willalp.canteen.utils.CanteenMenuUtil;
import com.willalp.consume.domain.ConsumeMaintain;
import com.willalp.consume.service.IConsumeMaintainService;
import com.willalp.number.domain.req.NumberRuleReq;
import com.willalp.number.service.IHsSysNumberRuleService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.willalp.common.annotation.Log;
import com.willalp.common.core.controller.BaseController;
import com.willalp.common.core.domain.AjaxResult;
import com.willalp.common.enums.BusinessType;
import com.willalp.canteen.domain.HsCanteenMenu;
import com.willalp.canteen.service.IHsCanteenMenuService;
import com.willalp.common.utils.poi.ExcelUtil;
import com.willalp.common.core.page.TableDataInfo;

/**
 * 菜单Controller
 *
 * @author songyu
 * @date 2021-12-02
 */
@RestController
@RequestMapping("/canteen/menu")
public class HsCanteenMenuController extends BaseController
{
    @Autowired
    private IHsCanteenMenuService hsCanteenMenuService;
    @Autowired
    private IHsSysNumberRuleService hsSysNumberRuleService;
    @Autowired
    private CanteenMenuUtil canteenMenuUtil;
    @Autowired
    private IConsumeMaintainService consumeMaintainService;

    /**
     * 查询菜单列表
     */
    @PreAuthorize("@ss.hasPermi('canteen:menu:list')")
    @GetMapping("/list")
    public TableDataInfo list(HsCanteenMenu hsCanteenMenu)
    {
        startPage();
        List<HsCanteenMenu> list = hsCanteenMenuService.selectHsCanteenMenuList(hsCanteenMenu);
        return getDataTable(list);
    }

    /**
     * 导出菜单列表
     */
    @PreAuthorize("@ss.hasPermi('canteen:menu:export')")
    @Log(title = "菜单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(HsCanteenMenu hsCanteenMenu)
    {
        List<HsCanteenMenu> list = hsCanteenMenuService.selectHsCanteenMenuList(hsCanteenMenu);
        ExcelUtil<HsCanteenMenu> util = new ExcelUtil<HsCanteenMenu>(HsCanteenMenu.class);
        return util.exportExcel(list, "菜单数据");
    }

    /**
     * 获取菜单详细信息
     */
    @PreAuthorize("@ss.hasPermi('canteen:menu:query')")
    @GetMapping(value = "/{menuId}")
    public AjaxResult getInfo(@PathVariable("menuId") String menuId)
    {
        return AjaxResult.success(hsCanteenMenuService.getById(menuId));
    }

    /**
     * 新增菜单
     */
    @PreAuthorize("@ss.hasPermi('canteen:menu:add')")
    @Log(title = "菜单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HsCanteenMenu hsCanteenMenu)
    {
        while (true) {
            String idStr = IdWorker.getIdStr();
            HsCanteenMenu byId = hsCanteenMenuService.getById(idStr);
            if (null == byId) {
                hsCanteenMenu.setMenuId(idStr);
                break;
            }
        }
        //获取编号
        hsCanteenMenu.setConsumerType(canteenMenuUtil.typeSort(hsCanteenMenu.getConsumerType()));
        NumberRuleReq numberRuleReq =new NumberRuleReq();
        numberRuleReq.setRuleId(NumberRuleEnum.MENU.getValue());
        String number = hsSysNumberRuleService.getNumber(numberRuleReq);
        hsCanteenMenu.setMenuNumber(number);
        return hsCanteenMenuService.insertHsCanteenMenu(hsCanteenMenu);
    }

    /**
     * 修改菜单
     */
    @PreAuthorize("@ss.hasPermi('canteen:menu:edit')")
    @Log(title = "菜单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HsCanteenMenu hsCanteenMenu)
    {
        //判断菜单是否可以更改
        ConsumeMaintain con = new ConsumeMaintain();
        con.setMenuNumber(hsCanteenMenu.getMenuNumber());
        List<ConsumeMaintain> cons = consumeMaintainService.selectConsumeMaintainList(con);
        if (cons.size() > 0) {
            con = cons.get(0);
            Date date =  DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", DateUtils.parseDateToStr("yyyy-MM-dd", con.getSendTime()) + " " + con.getBeginDate() + ":00");
            if (DateUtil.compare(new Date(),date) > 0){
                return AjaxResult.error("菜单已使用,不允许更改");
            }
        }
        hsCanteenMenu.setConsumerType(canteenMenuUtil.typeSort(hsCanteenMenu.getConsumerType()));
        return hsCanteenMenuService.updateHsCanteenMenu(hsCanteenMenu);
    }

    /**
     * 删除菜单
     */
    @PreAuthorize("@ss.hasPermi('canteen:menu:remove')")
    @Log(title = "菜单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{menuIds}")
    public AjaxResult remove(@PathVariable String[] menuIds)
    {
        List<String> strs = Arrays.asList(menuIds);
        List<String> removeList = new ArrayList<>();
        StringBuffer msg = new StringBuffer();
        List<HsCanteenMenu> menus = hsCanteenMenuService.listByIds(strs);
        menus.stream().forEach(o ->{
            //判断菜单是否可以更改
            ConsumeMaintain con = new ConsumeMaintain();
            con.setMenuNumber(o.getMenuNumber());
            List<ConsumeMaintain> cons = consumeMaintainService.selectConsumeMaintainList(con);
            if (cons.size() > 0) {
                con = cons.get(0);
                Date date =  DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", DateUtils.parseDateToStr("yyyy-MM-dd", con.getSendTime()) + " " + con.getBeginDate() + ":00");
                if (DateUtil.compare(new Date(),date) > 0){
                    msg.append(",").append(o.getMenuNumber()).append("编号菜单已使用");
                } else{
                    removeList.add(o.getMenuId());
                }
            }else
                removeList.addAll(strs);
        });
        if (msg.length() == 0){
            msg.append("删除成功");
        }
        hsCanteenMenuService.removeByIds(removeList);
        return AjaxResult.success(msg);
    }

    @RequestMapping("/limitMenu")
    @ResponseBody
    public AjaxResult getLimitMenu(Date date,String jgid){
        return AjaxResult.success(hsCanteenMenuService.getLimitMenu(date,jgid));
    }
}
