package com.ruoyi.app.mendian;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.IPosStoreService;
import com.ruoyi.system.service.IVipQuanyiService;
import com.ruoyi.system.service.IVipUserQuanyiService;
import com.ruoyi.system.service.IVipUserService;
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.stream.Collectors;

/**
 * 商家端优惠券管理Controller
 *
 * @author ruoyi
 * @date 2023-05-21
 */
@RestController
@RequestMapping("/system/shQuanyi")
public class ShQuanyiController extends BaseController {
    @Autowired
    private IVipQuanyiService vipQuanyiService;
    @Autowired
    private IVipUserService vipUserService;
    @Autowired
    private IVipUserQuanyiService vipUserQuanyiService;

    @Autowired
    private IPosStoreService storeService;

    @Anonymous
    @Auth
    @GetMapping("/getMyquanyi")
    public AjaxResult getMyquanyi(@RequestHeader String token) {
        JwtUtil jwtUtil = new JwtUtil();
        DateUtil date = new DateUtil();
        String id = jwtUtil.getusid(token);
        QueryWrapper<VipUser> Wrapper = new QueryWrapper<>();
        Wrapper.eq("user_id", id);
        Wrapper.apply("date_format (yxtim,'%Y-%m-%d') >= date_format ({0},'%Y-%m-%d')", date.GetDate());
        VipUser user = vipUserService.getOne(Wrapper);
        if (user == null) {
            return error(MessageUtils.message("no.user.not.vip"));
        } else {
            GetVipqy quany = new GetVipqy();
            List<VipQuanyi> list = quany.getvipqy(id);
            List<VipQuanyi> qulist = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                VipQuanyi vip = new VipQuanyi();
                if (list.get(i).getNum() > 0) {
                    vip.setId(list.get(i).getId());
                    vip.setName(list.get(i).getName());
                    vip.setNum(list.get(i).getNum());
                    vip.setVip(list.get(i).getVip());
                    vip.setShuoming(list.get(i).getShuoming());
                    vip.setTiaojian(list.get(i).getTiaojian());
                    vip.setYhfangs(list.get(i).getYhfangs());
                    vip.setYhnum(list.get(i).getYhnum());
                    qulist.add(vip);
                }
            }
            return success(qulist);
        }

    }

    /**
     * 查询商家优惠券列表
     */
    @Anonymous
    @Auth
    @GetMapping("/list")
    public AjaxResult list(@RequestHeader String token,
                           @RequestParam Integer page,
                           @RequestParam Integer size,
                           @RequestParam String language,
                           @RequestParam Long shId
    ) {
        JwtUtil jwtUtil = new JwtUtil();
        String id = jwtUtil.getusid(token);
        IPage<VipQuanyi> iPage = new Page<>(page, size);
        LambdaQueryWrapper<VipQuanyi> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(VipQuanyi::getShId, shId);
        queryWrapper.eq(VipQuanyi::getType,"1");
        queryWrapper.eq(VipQuanyi::getLanguage, language);
        queryWrapper.eq(VipQuanyi::getDeleted, "0");
        IPage<VipQuanyi> list = vipQuanyiService.page(iPage, queryWrapper);
        return success(list);
    }


    /**
     * 获取商家优惠券详细信息
     */
    @Anonymous
    @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);
            }
        }
        return success(result);
    }

    /**
     * 新增商家优惠券
     */
    @Anonymous
    @Auth
    @PostMapping
    public AjaxResult add(@RequestHeader String token, @RequestBody VipQuanyi vipQuanyi) {
        JwtUtil jwtUtil = new JwtUtil();
        String id = jwtUtil.getusid(token);
//        vipQuanyi.setShId(Long.valueOf(id));
        vipQuanyi.setCreateTime(new Date());
        vipQuanyi.setType("1");
        vipQuanyi.setMerchantId(Long.valueOf(id));
        return toAjax(vipQuanyiService.insertVipQuanyi(vipQuanyi));
    }

    /**
     * 修改优惠券
     */
    @Anonymous
    @Auth
    @PutMapping
    public AjaxResult edit(@RequestBody VipQuanyi vipQuanyi) {
        vipQuanyi.setUpdateTime(new Date());
        return toAjax(vipQuanyiService.updateVipQuanyi(vipQuanyi));
    }

    /**
     * 删除优惠券
     */
    @Anonymous
    @Auth
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(vipQuanyiService.deleteVipQuanyiByIds(ids));
    }

    /**
     * 补充优惠券商家id
     * @return
     */
    @Anonymous
    @GetMapping("/setMerchatId")
    public AjaxResult  setMerchatId () {
        List<VipQuanyi> list = vipQuanyiService.list(new LambdaQueryWrapper<VipQuanyi>().isNotNull(VipQuanyi::getShId).isNull(VipQuanyi::getMerchantId).eq(VipQuanyi::getType,"1"));
        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 = storeService.list(query);
            list.forEach(item->{
                stores.stream().filter(m->Long.valueOf(m.getId()).equals(item.getShId())).findFirst().ifPresent(m->item.setMerchantId(m.getUserId()));
                vipQuanyiService.updateById(item);
            });
        }
        List<VipUserQuanyi> list2 = vipUserQuanyiService.list(new LambdaQueryWrapper<VipUserQuanyi>().isNotNull(VipUserQuanyi::getShId).isNull(VipUserQuanyi::getMerchantId).eq(VipUserQuanyi::getType,"1"));
        if(!list2.isEmpty()){
            List<Long> storeIds = list2.stream().map(VipUserQuanyi::getShId).collect(Collectors.toList());
            LambdaQueryWrapper<PosStore> query= new LambdaQueryWrapper<>();
            query.in(PosStore::getId,storeIds);
            List<PosStore> stores = storeService.list(query);
            list2.forEach(item->{
                stores.stream().filter(m->Long.valueOf(m.getId()).equals(item.getShId())).findFirst().ifPresent(m->item.setMerchantId(m.getUserId()));
                vipUserQuanyiService.updateById(item);
            });
        }
        return AjaxResult.success();
    }
}


