package com.ruoyi.web.controller.system;

import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.PoCollection;
import com.ruoyi.system.domain.PoTetherandcollection;
import com.ruoyi.system.domain.PoUser;
import com.ruoyi.system.domain.vo.TetherVo;
import com.ruoyi.system.service.IPoUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.repository.query.Param;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.PoTether;
import com.ruoyi.system.service.IPoTetherService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 套系Controller
 *
 * @author ruoyi
 * @date 2023-02-12
 */
@RestController
@RequestMapping("/system/tether")
public class PoTetherController extends BaseController
{
    @Autowired
    private IPoTetherService poTetherService;

    @Autowired
    private IPoUserService poUserService;

    /**
     * 标题和时间搜索消息列表
     */
    @ApiOperation("标题和时间搜索消息列表")
    @Log(title = "标题和时间搜索")
    @PreAuthorize("@ss.hasPermi('system:tether:queryTether')")
    @GetMapping("/queryTether")
    public TableDataInfo list(@RequestParam(value="tetherName",required = false)String tetherName,
                              @RequestParam(value="tetherTimeStart",required = false) Date tetherTimeStart,
                              @RequestParam(value="tetherTimeEnd",required = false) Date tetherTimeEnd)
    {
        startPage();
        List<PoTether> list= poTetherService.selectListByTitleAndTime(tetherName,tetherTimeStart,tetherTimeEnd);
        return getDataTable(list);
    }
    /**
     * 查询套系列表 数量
     */
    @PreAuthorize("@ss.hasPermi('system:tether:list')")
    @GetMapping("/list")
    @ApiOperation("查询套系列表 在售")
    public TableDataInfo Total(PoTether poTether)
    {
        startPage();
        List<PoTether> sellingList = poTetherService.selectPoTetherCollectionList(poTether);
        return getDataTable(sellingList);
    }

    /**
     * 查询套系列表 在售
     */
    @PreAuthorize("@ss.hasPermi('system:tether:sellingList')")
    @GetMapping("/sellingList")
    @ApiOperation("查询套系列表 在售")
    public TableDataInfo sellingList(PoTether poTether)
    {
        startPage();
        List<PoTether> sellingList = poTetherService.selectPoTetherSellingList(poTether);
        return getDataTable(sellingList);
    }
    /**
     * 查询套系列表 预售
     */
    @ApiOperation("查询套系列表 预售")
    @PreAuthorize("@ss.hasPermi('system:tether:advanceList')")
    @GetMapping("/advanceList")
    public TableDataInfo advanceList(PoTether poTether)
    {
        startPage();
        List<PoTether> advanceList = poTetherService.selectPoTetherAdvanceList(poTether);
        return getDataTable(advanceList);
    }
    /**
     * 查询套系列表 已过期
     */
    @ApiOperation("查询套系列表 已过期")
    @PreAuthorize("@ss.hasPermi('system:tether:selledList')")
    @GetMapping("/selledList")
    public TableDataInfo selledList(PoTether poTether)
    {
        startPage();
        List<PoTether> selledList = poTetherService.selectPoTetherSelledList(poTether);
        return getDataTable(selledList);
    }

    /**
     * 导出套系列表
     */
    @ApiOperation("导出套系列表")
    @PreAuthorize("@ss.hasPermi('system:tether:export')")
    @Log(title = "套系", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PoTether poTether)
    {
        List<PoTether> list = poTetherService.selectPoTetherList(poTether);
        ExcelUtil<PoTether> util = new ExcelUtil<PoTether>(PoTether.class);
        util.exportExcel(response, list, "套系数据");
    }


    /**
     * 藏品列表
     */
    @ApiOperation("藏品列表")
    @PreAuthorize("@ss.hasPermi('system:tether:collectionList')")
    @GetMapping("/collectionList/{tetherId}")
    public TableDataInfo collectionList( @PathVariable("tetherId") Long tetherId){

        startPage();
        List<PoTetherandcollection> collectionList = poTetherService.selectPoCollectionListById(tetherId);
        return getDataTable(collectionList);
    }

    /**
     * 新增套系
     */
    @ApiOperation("新增套系")
    @PreAuthorize("@ss.hasPermi('system:tether:add')")
    @Log(title = "套系", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody TetherVo tetherVo,
                          @RequestBody @Param("poUser") PoUser poUser,
                          @RequestBody PoTetherandcollection poTetherandcollection)
    {
        //判断当前用户是否有操作的权限
        poUserService.checkUserAllowed(poUser);

        if (UserConstants.NOT_UNIQUE.equals(poTetherService.checkPostTetherNameUnique(tetherVo))){
            return AjaxResult.error("新增失败"+tetherVo.getTetherName()+"已经存在");
        }
        if(UserConstants.NOT_UNIQUE.equals(poTetherService.checkPostTetherImageUnique(tetherVo))){
            return AjaxResult.error("新增失败"+tetherVo.getImage()+"已经存在");
        }

        tetherVo.setCreateBy(getUsername());
        tetherVo.setCreateTime(new Date());

        Date nowTime = new Date();
        nowTime = DateUtils.getNowDate();

        if (nowTime.after(tetherVo.getShowTimeEnd())){
            tetherVo.setSellStatus(2);
        }
        else if (nowTime.before(tetherVo.getShowTimeStart())){
            tetherVo.setSellStatus(1);
        }else{
            tetherVo.setSellStatus(0);
        }
        poTetherService.insertPoTetherWithCollection(tetherVo,poTetherandcollection);
        return success("新增成功");
    }

    /**
     * 通过id获取套系详细信息
     */
    @ApiOperation("通过id获取套系详细信息")
    @PreAuthorize("@ss.hasPermi('system:tether:query')")
    @GetMapping(value = "/{tetherId}")
    public AjaxResult getInfo(@PathVariable("tetherId") Long tetherId)
    {
       TetherVo byIdWithCollection = poTetherService.selectPoTetherByTetherIdWithCollection(tetherId);
       return success(byIdWithCollection);
    }

    /**
     * 修改套系
     */
    @ApiOperation("修改套系")
    @PreAuthorize("@ss.hasPermi('system:tether:edit')")
    @Log(title = "套系", businessType = BusinessType.UPDATE)
    @PutMapping("edit")
    public AjaxResult edit(@RequestBody TetherVo tetherVo,@RequestBody PoUser poUser)
    {
        //校验是否有操作的权限
        poUserService.checkUserAllowed(poUser);

        TetherVo tetherVo1 = poTetherService.selectPoTetherByTetherIdWithCollection(tetherVo.getTetherId());

        if (tetherVo1 == null){
            return error("没有对应的数据");
        }
        if (tetherVo1.getCochain() == 0){
            return error("已经上链");
        }

        if (UserConstants.NOT_UNIQUE.equals(poTetherService.checkPostTetherNameUnique(tetherVo))){
            return AjaxResult.error("修改失败"+tetherVo.getTetherName()+"已经存在");
        }
        if(UserConstants.NOT_UNIQUE.equals(poTetherService.checkPostTetherImageUnique(tetherVo))){
            return AjaxResult.error("修改失败"+tetherVo.getImage()+"已经存在");
        }

        tetherVo.setUpdateBy(getUsername());
        tetherVo.setUpdateTime(new Date());
        poTetherService.updatePoTetherWithCollection(tetherVo);
        return success("修改成功");
    }

    /**
     * 删除套系
     */
    @ApiOperation("删除套系")
    @PreAuthorize("@ss.hasPermi('system:tether:remove')")
    @Log(title = "套系", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove/{tetherIds}")
    public AjaxResult remove(@PathVariable Long[] tetherIds) throws Exception {
        if (!getUsername().equals("admin")){
            return AjaxResult.error("删除消息失败当前用户不是管理员");
        }
        poTetherService.deletePoTetherByTetherIdsWithCollection(tetherIds);
        return success("删除成功");
    }

    /**
     * 修改状态 是否上链
     */
    @ApiOperation("修改状态 是否上链")
    @PreAuthorize("@ss.hasPermi('system:tether:isCochain')")
    @PostMapping("/isCochain/{cochain}/{tetherId}")
    public AjaxResult isCochain( @PathVariable("cochain") Integer cochain , @PathVariable("tetherId") Long tetherId){

        if (!getUsername().equals("admin")){
            return AjaxResult.error("不是管理员不可以修改上下链状态");
        }

        TetherVo tetherVo = poTetherService.selectPoTetherByTetherIdWithCollection(tetherId);
        if (tetherVo.getCochain() == 0){
            return error("禁止重复上链");
        }
        return toAjax(poTetherService.updatePoTetherIsCochain(cochain,tetherId));
    }
    /**
     * 修改状态 是否上架
     */
    @ApiOperation("修改状态 是否上架")
    @PreAuthorize("@ss.hasPermi('system:tether:isGrounding')")
    @PostMapping("/isGrounding/{grounding}/{tetherId}")
    public AjaxResult isGrounding( @PathVariable("grounding") Integer grounding , @PathVariable("tetherId") Long tetherId){

        if (!getUsername().equals("admin")){
            return AjaxResult.error("不是管理员不可以修改上下架状态");
        }
        TetherVo tetherVo = poTetherService.selectPoTetherByTetherIdWithCollection(tetherId);

        if (tetherVo.getCochain() == 0 ){

            return error("此套系为上链状态禁止上架");
        }
        if (tetherVo.getGrounding() == 0){
            return error("禁止重复上架");
        }
        return toAjax(poTetherService.updatePoTetherIsGrounding(grounding,tetherId));
    }



}