package com.willalp.web.controller.canteen;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
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.DateUtils;
import com.willalp.common.utils.poi.ExcelUtil;
import com.willalp.canteen.domain.HsCanteenMenuRegister;
import com.willalp.canteen.domain.req.AddRegistersReq;
import com.willalp.canteen.service.IHsCanteenMenuRegisterService;
import com.willalp.consume.domain.ConsumeMaintain;
import com.willalp.consume.service.IConsumeMaintainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

/**
 * 菜单登记Controller
 *
 * @author songyu
 * @date 2021-11-29
 */
@RestController
@RequestMapping("/canteen/register")
public class HsCanteenMenuRegisterController extends BaseController {
    @Autowired
    private IHsCanteenMenuRegisterService hsCanteenMenuRegisterService;
    @Autowired
    private IConsumeMaintainService consumeMaintainService;

    /**
     * 查询菜单登记列表
     */
    @PreAuthorize("@ss.hasPermi('canteen:register:list')")
    @GetMapping("/list")
    public TableDataInfo list(HsCanteenMenuRegister hsCanteenMenuRegister) {
        startPage();
        List<HsCanteenMenuRegister> list = hsCanteenMenuRegisterService.selectRegisterStockList(hsCanteenMenuRegister);
        return getDataTable(list);
    }

    /**
     * 导出菜单登记列表
     */
    @PreAuthorize("@ss.hasPermi('canteen:register:export')")
    @Log(title = "菜单登记", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(HsCanteenMenuRegister hsCanteenMenuRegister) {
        List<HsCanteenMenuRegister> list = hsCanteenMenuRegisterService.selectRegisterStockList(hsCanteenMenuRegister);
        ExcelUtil<HsCanteenMenuRegister> util = new ExcelUtil<HsCanteenMenuRegister>(HsCanteenMenuRegister.class);
        return util.exportExcel(list, "菜单登记数据");
    }

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

    /**
     * 新增菜单登记
     */
    @PreAuthorize("@ss.hasPermi('canteen:register:add')")
    @Log(title = "菜单登记", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HsCanteenMenuRegister hsCanteenMenuRegister) {
        //判断菜单是否可以更改
        ConsumeMaintain con = new ConsumeMaintain();
        con.setMenuNumber(hsCanteenMenuRegister.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("菜单已使用,不允许更改");
            }
        }
        //新增逻辑
        while (true) {
            String idStr = IdWorker.getIdStr();
            HsCanteenMenuRegister byId = hsCanteenMenuRegisterService.getById(idStr);
            if (null == byId) {
                hsCanteenMenuRegister.setRegisterId(idStr);
                break;
            }
        }
        return toAjax(hsCanteenMenuRegisterService.save(hsCanteenMenuRegister));
    }

    /**
     * 修改菜单登记
     */
    @PreAuthorize("@ss.hasPermi('canteen:register:edit')")
    @Log(title = "菜单登记", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HsCanteenMenuRegister hsCanteenMenuRegister) {
        //判断菜单是否可以更改
        ConsumeMaintain con = new ConsumeMaintain();
        con.setMenuNumber(hsCanteenMenuRegister.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("菜单已使用,不允许更改");
            }
        }

        return toAjax(hsCanteenMenuRegisterService.updateById(hsCanteenMenuRegister));
    }

    /**
     * 删除菜单登记
     */
    @PreAuthorize("@ss.hasPermi('canteen:register:remove')")
    @Log(title = "菜单登记", businessType = BusinessType.DELETE)
    @DeleteMapping("/{registerIds}")
    public AjaxResult remove(@PathVariable String[] registerIds) {
        List<String> strList = Arrays.asList(registerIds);
        List<String> removeList = new ArrayList<>();
        StringBuffer msg = new StringBuffer();
        List<HsCanteenMenuRegister> registers = hsCanteenMenuRegisterService.listByIds(strList);
        registers.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.getRegisterId());
                }
            }else{
                removeList.addAll(strList);
            }
        });
        if (msg.length() == 0){
            msg.append("删除成功");
        }
        hsCanteenMenuRegisterService.removeByIds(removeList);
        return AjaxResult.success(msg);
    }

    @RequestMapping("/addRegisters")
    @ResponseBody
    public AjaxResult addRegisters(@RequestBody AddRegistersReq addRegistersReq) {
        //判断菜单是否可以更改
        ConsumeMaintain con = new ConsumeMaintain();
        con.setMenuNumber(addRegistersReq.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("菜单已使用,不允许更改");
            }
        }

        List<HsCanteenMenuRegister> hsCanteenMenuRegisters = new ArrayList<>();
        addRegistersReq.getCuisines().stream().forEach(o ->{
            HsCanteenMenuRegister register = new HsCanteenMenuRegister();
            BeanUtil.copyProperties(o,register);
            register.setMenuNumber(addRegistersReq.getMenuNumber());
//            register.setPeriodId(addRegistersReq.getPeriodId());
//            register.setPatternId(addRegistersReq.getPatternId());
//            register.setConsumerType(addRegistersReq.getConsumerType());

            register.setPrice(o.getCuisinePrice());

            while (true) {
                String idStr = IdWorker.getIdStr();
                HsCanteenMenuRegister byId = hsCanteenMenuRegisterService.getById(idStr);
                if (null == byId) {
                    register.setRegisterId(idStr);
                    break;
                }
            }

            hsCanteenMenuRegisters.add(register);
        });
        hsCanteenMenuRegisterService.saveBatch(hsCanteenMenuRegisters);
        return AjaxResult.success(success());
    }
}
