package com.ruoyi.web.controller.back;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.RoleType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.voluntary.domain.BusiAgents;
import com.ruoyi.voluntary.service.IBusiAgentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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.enums.CardType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.voluntary.domain.BusiCards;
import com.ruoyi.voluntary.service.IBusiCardsService;

/**
 * vip卡Controller
 *
 * @author voluntary
 * @date 2022-11-20
 */
@RestController
@RequestMapping("/voluntary/busiCards")
public class BackBusiCardsController extends BaseController {
    @Autowired
    private IBusiCardsService busiCardsService;
    @Autowired
    private IBusiAgentsService agentsService;

    /**
     * 查询vip卡列表
     */
    @PreAuthorize("@ss.hasPermi('voluntary:busiCards:list')")
    @GetMapping("/list")
    public TableDataInfo list(BusiCards busiCards) {
        //代理商角色过滤agentId
        SysUser currentUser = SecurityUtils.getLoginUser().getUser();
        List<SysRole> userRoles = currentUser.getRoles();
        for (SysRole userRole : userRoles) {
            if (RoleType.isAgent(userRole.getRoleId())) {
                BusiAgents agent = agentsService.selectBusiAgentsByUserId(currentUser.getUserId());
                if(null!=agent){
                    busiCards.setAgentId(agent.getAgentId());
                }
                break;
            }
        }
        startPage();
        List<BusiCards> list = busiCardsService.selectBusiCardsList(busiCards);
        return getDataTable(list);
    }

    /**
     * 导出vip卡列表
     */
    @PreAuthorize("@ss.hasPermi('voluntary:busiCards:export')")
    @Log(title = "vip卡", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BusiCards busiCards) {
        List<BusiCards> list = busiCardsService.selectBusiCardsList(busiCards);
        ExcelUtil<BusiCards> util = new ExcelUtil<BusiCards>(BusiCards.class);
        util.exportExcel(response, list, "vip卡数据");
    }

    /**
     * 获取vip卡详细信息
     */
    @PreAuthorize("@ss.hasPermi('voluntary:busiCards:query')")
    @GetMapping(value = "/{cardId}")
    public AjaxResult getInfo(@PathVariable("cardId") Long cardId) {
        return success(busiCardsService.selectBusiCardsByCardId(cardId));
    }

    /**
     * 新增vip卡
     */
    @PreAuthorize("@ss.hasPermi('voluntary:busiCards:add')")
    @Log(title = "vip卡", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody BusiCards busiCards) {
        List<BusiCards> cards = busiCardsService.createCard(busiCards);
        if (CardType.isECard(busiCards.getType())) {
            // 创建电子卡时，需要自动分配卡：开始与结束卡号
            List<String> cardList = cards.stream().map(BusiCards::getCardNo).collect(Collectors.toList());
            String startCard = Collections.min(cardList);
            String endCard = Collections.max(cardList);
            BusiCards distributeCard = new BusiCards();
            distributeCard.setStartCard(startCard);
            distributeCard.setEndCard(endCard);
            distributeCard.setType(busiCards.getType());
            if (CardType.isECard(busiCards.getType()) || CardType.isECard(startCard) || CardType.isECard(endCard)) {
                // 默认分配给“电子卡代理商” agentCode = 83770f49fcb88c1d0538dcf689291d97
                if (StringUtils.isNull(busiCards.getAgentId())) {
                    // 电子卡代理商
                    distributeCard.setAgentId(1L);
                }
            }
            // TODO 电子卡创建时自动分配
            busiCardsService.distributionCard(distributeCard);
        }

        return AjaxResult.success();
    }

    /**
     * 修改vip卡
     */
    @PreAuthorize("@ss.hasPermi('voluntary:busiCards:edit')")
    @Log(title = "vip卡", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BusiCards busiCards) {
        return toAjax(busiCardsService.updateBusiCards(busiCards));
    }

    /**
     * 删除vip卡
     */
    @PreAuthorize("@ss.hasPermi('voluntary:busiCards:remove')")
    @Log(title = "vip卡", businessType = BusinessType.DELETE)
    @DeleteMapping("/{cardIds}")
    public AjaxResult remove(@PathVariable Long[] cardIds) {
        return toAjax(busiCardsService.deleteBusiCardsByCardIds(cardIds));
    }

    @Log(title = "批量操作", businessType = BusinessType.UPDATE)
    @PostMapping("/batch")
    public AjaxResult batch(@RequestBody String json) {
        com.alibaba.fastjson.JSONObject data = com.alibaba.fastjson.JSON.parseObject(json);
        busiCardsService.batch(data);
        return AjaxResult.success(true);
    }

    @PostMapping("/static/agent")
    @SuppressWarnings("rawtypes")
    public AjaxResult staticByAgent(@RequestBody BusiCards busiCards) {
        List<Map> data = busiCardsService.staticByAgent(busiCards);
        return AjaxResult.success(data);
    }

    @Log(title = "卡分发", businessType = BusinessType.UPDATE)
    @PostMapping("/distribution")
    public AjaxResult distributionCard(@RequestBody BusiCards busiCards) {
        return AjaxResult.success(busiCardsService.distributionCard(busiCards));
    }
}
