package com.njyunzhi.pet_identity.controller;

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.njyunzhi.pet_identity.common.BaseController;
import com.njyunzhi.pet_identity.common.ResponseBean;
import com.njyunzhi.pet_identity.common.StringUtils;
import com.njyunzhi.pet_identity.common.ZipUtil;
import com.njyunzhi.pet_identity.entity.TaSequence;
import com.njyunzhi.pet_identity.service.ITaSequenceService;
import com.njyunzhi.pet_identity.vo.BatchCardParams;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.lingala.zip4j.ZipFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.njyunzhi.pet_identity.service.ITaCardNoService;
import com.njyunzhi.pet_identity.entity.TaCardNo;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * <p>
    * 卡号库 前端控制器
    * </p>
 *
 * @author yansen
 * @since 2022-05-28
 */

@Api(tags = "卡号库")
@RestController
@RequestMapping("/admin")
public class TaCardNoController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(TaCardNoController.class);

    @Autowired
    public ITaCardNoService iTaCardNoService;

    @Autowired
    public ITaSequenceService iTaSequenceService;

    @Autowired
    public ZipUtil zipUtil;

    /**
     * 分页查询列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value="/cardNo",method= RequestMethod.GET)
    @ApiOperation(value="列表", notes = "列表", httpMethod = "GET", response = ResponseBean.class)
    public ResponseBean taCardNoList(@ApiParam("页码") @RequestParam(value ="pageNum",defaultValue = "1") Integer pageNum,
									 @ApiParam("单页数据量") @RequestParam(value ="pageSize",defaultValue = "10") Integer pageSize,
                                     @ApiParam("前缀") @RequestParam(value ="prefix", required = false) String prefix,
                                     @ApiParam("起始号码") @RequestParam(value ="start", required = false) Integer start,
                                     @ApiParam("终止号码") @RequestParam(value ="end", required = false) Integer end) throws Exception{

        if (StringUtils.isEmpty(prefix) && (null != start || null != end)) {
            return ResponseBean.error("卡号前缀不能为空");
        }

        IPage<TaCardNo> pg = new Page<>(pageNum, pageSize);
        QueryWrapper<TaCardNo> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge(null != start, "card_no", iTaCardNoService.getFormatNo(prefix, start));
        queryWrapper.le(null != end, "card_no", iTaCardNoService.getFormatNo(prefix, end));
        queryWrapper.orderByDesc("create_date");

        IPage<TaCardNo> result = iTaCardNoService.page(pg, queryWrapper);
        return ResponseBean.success(result);
    }


    /**
     * 分页查询列表
     * @return
     */
    @RequestMapping(value="/cardNo/export",method= RequestMethod.GET)
    @ApiOperation(value="导出", notes = "导出", httpMethod = "GET", response = ResponseBean.class)
    public ResponseBean export(@ApiParam("前缀") @RequestParam(value ="prefix") String prefix,
                               @ApiParam("起始号码") @RequestParam(value ="start", required = false) Integer start,
                               @ApiParam("终止号码") @RequestParam(value ="end", required = false) Integer end,
                               HttpServletResponse response) throws Exception{

        if (StringUtils.isEmpty(prefix)) {
            return ResponseBean.error("卡号前缀不能为空");
        }

        QueryWrapper<TaCardNo> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge(null != start, "card_no", iTaCardNoService.getFormatNo(prefix, start));
        queryWrapper.le(null != end, "card_no", iTaCardNoService.getFormatNo(prefix, end));
        queryWrapper.orderByDesc("create_date");

        List<TaCardNo> result = iTaCardNoService.list(queryWrapper);

        List<ZipUtil.RFile> files = new ArrayList<>();
        if (null != result && result.size() > 0) {
            for (TaCardNo item : result) {
                ZipUtil.RFile f = new ZipUtil.RFile();
                f.setName(item.getCardNo() + ".png");
                f.setUrl(item.getQrImage());
                files.add(f);
            }
        }

        zipUtil.flush(response, files);
        return null;
    }

    /**
     * 分页查询列表
     * @param id
     * @return
     */
    @RequestMapping(value="/cardNo/{id}",method= RequestMethod.GET)
    @ApiOperation(value="卡号详情", notes = "卡号详情", httpMethod = "GET", response = ResponseBean.class)
    public ResponseBean getDetail(@ApiParam("页码") @PathVariable String id) throws Exception{
        return ResponseBean.success(iTaCardNoService.getById(id));
    }

    /**
     * 保存对象
     * @param batchCardParams 实体对象
     * @return
     */
    @RequestMapping(value="/carNo/batch",method= RequestMethod.POST)
    @ApiOperation(value="批量生成卡号", notes = "批量生成卡号", httpMethod = "POST", response = ResponseBean.class)
    public ResponseBean taCardNoAdd(@ApiParam("保存内容") @RequestBody BatchCardParams batchCardParams) throws Exception{

        if (StringUtils.isEmpty(batchCardParams.getPrefix())) {
            return ResponseBean.error("请输入卡号前缀");
        }
        if (batchCardParams.getNum() == null || batchCardParams.getNum() < 1) {
            return ResponseBean.error("请设置生成卡号数量");
        }

        Integer maxNum = 99999;
        TaSequence taSequence = iTaSequenceService.getById("card-" + batchCardParams.getPrefix());
        if (null != taSequence && taSequence.getValue() + batchCardParams.getNum() >= maxNum) {
            return ResponseBean.error(String.format("当前前缀合法卡号剩余 %d", maxNum - taSequence.getValue()));
        }

        iTaCardNoService.createBatchCardNo(batchCardParams);

        return ResponseBean.success("ok");
    }

}
