package com.ruoyi.app.vip;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.app.utils.DateUtil;
import com.ruoyi.app.utils.GetVipqy;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.system.utils.Auth;
import com.ruoyi.system.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * quanyiController
 *
 * @author ruoyi
 * @date 2023-06-06
 */
@RestController
@RequestMapping("/system/sjquanyi")
public class VipSjQuanyiController extends BaseController {
    @Autowired
    private IVipQuanyiService vipQuanyiService;
    @Autowired
    private IVipUserQuanyiService vipUserQuanyiService;
    @Autowired
    private IPosStoreService posStoreService;
    @Autowired
    private IInfoUserService infoUserService;


    /**
     * 查询quanyi列表
     */
    @PreAuthorize("@ss.hasPermi('system:sjquanyi:list')")
    @GetMapping("/list")
    public TableDataInfo list(VipQuanyi vipQuanyi) {
        startPage();
        List<VipQuanyi> list = vipQuanyiService.selectVipQuanyiList(vipQuanyi);
        if (!list.isEmpty()) {
            List<Long> storeIds = list.stream().map(VipQuanyi::getShId).collect(Collectors.toList());
            LambdaQueryWrapper<PosStore> query = new LambdaQueryWrapper<>();
            query.in(PosStore::getId, storeIds);
            List<PosStore> stores = posStoreService.list(query);
            List<Long> merchantIds = list.stream().map(VipQuanyi::getMerchantId).collect(Collectors.toList());
            LambdaQueryWrapper<InfoUser> mquery = new LambdaQueryWrapper<>();
            query.in(PosStore::getId, merchantIds);
            List<InfoUser> merchants = infoUserService.list(mquery);
            list.forEach(item -> {
                merchants.stream().filter(m -> m.getUserId().equals(item.getMerchantId())).findFirst().ifPresent(m -> item.setMerchantName(m.getNickName()));
                stores.stream().filter(m -> Long.valueOf(m.getId()).equals(item.getShId())).findFirst().ifPresent(m -> item.setStoreName(m.getPosName()));
            });
        }
        return getDataTable(list);
    }

    /**
     * 导出quanyi列表
     */
    @PreAuthorize("@ss.hasPermi('system:sjquanyi:export')")
    @Log(title = "quanyi", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, VipQuanyi vipQuanyi) {
        List<VipQuanyi> list = vipQuanyiService.selectVipQuanyiList(vipQuanyi);
        ExcelUtil<VipQuanyi> util = new ExcelUtil<VipQuanyi>(VipQuanyi.class);
        util.exportExcel(response, list, MessageUtils.message("no.export.excel.rights"));
    }

    /**
     * 获取quanyi详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:sjquanyi:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        VipQuanyi result = vipQuanyiService.selectVipQuanyiById(id);
        if (result != null) {
            LambdaQueryWrapper<VipUserQuanyi> query = new LambdaQueryWrapper<>();
            query.eq(VipUserQuanyi::getQuanyiId, id);
            boolean exist = vipUserQuanyiService.count(query) > 0;
            if (exist) {
                result.setEdit(!exist);
            } else {
                result.setEdit(true);
            }
            LambdaQueryWrapper<InfoUser> userQuery = new LambdaQueryWrapper<>();
            userQuery.eq(InfoUser::getUserId, result.getMerchantId());
            InfoUser infoUser = infoUserService.getOne(userQuery);
            if (infoUser != null) {
                result.setMerchantName(infoUser.getNickName());
            }
        }
        return success(result);
    }

    /**
     * 新增quanyi
     */
    @PreAuthorize("@ss.hasPermi('system:sjquanyi:add')")
    @Log(title = "quanyi", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody VipQuanyi vipQuanyi) {
        vipQuanyi.setCreateTime(new Date());
        return toAjax(vipQuanyiService.insertVipQuanyi(vipQuanyi));
    }

    /**
     * 修改quanyi
     */
    @PreAuthorize("@ss.hasPermi('system:sjquanyi:edit')")
    @Log(title = "quanyi", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody VipQuanyi vipQuanyi) {
        vipQuanyi.setUpdateTime(new Date());
        return toAjax(vipQuanyiService.updateVipQuanyi(vipQuanyi));
    }

    /**
     * 删除quanyi
     */
    @PreAuthorize("@ss.hasPermi('system:sjquanyi:remove')")
    @Log(title = "quanyi", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(vipQuanyiService.deleteVipQuanyiByIds(ids));
    }

    @Anonymous
    @GetMapping("/getStoreList")
    public AjaxResult getStoreList(@RequestParam Long sjId) {
        LambdaQueryWrapper<PosStore> query = new LambdaQueryWrapper<>();
        query.eq(PosStore::getUserId, sjId);
        query.eq(PosStore::getOffShelf, '0'); //0 上架的
        List<PosStore> list = posStoreService.list(query);
        return success(list);
    }
}
