package com.liquidnet.client.admin.web.controller.zhengzai.adam;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.liquidnet.client.admin.common.annotation.Log;
import com.liquidnet.client.admin.common.core.controller.BaseController;
import com.liquidnet.client.admin.common.core.domain.AjaxResult;
import com.liquidnet.client.admin.common.core.page.TableDataInfo;
import com.liquidnet.client.admin.common.enums.BusinessType;
import com.liquidnet.client.admin.common.utils.poi.ExcelUtil;
import com.liquidnet.client.admin.zhengzai.adam.dto.AdamMemberCodeExcelDto;
import com.liquidnet.client.admin.zhengzai.adam.service.IAdamMemberCodeAdminService;
import com.liquidnet.client.admin.zhengzai.adam.service.IAdamMemberCodeBatchAdminService;
import com.liquidnet.client.admin.zhengzai.adam.service.IAdamMemberPriceAdminService;
import com.liquidnet.common.cache.redis.util.RedisDataSourceUtil;
import com.liquidnet.service.adam.dto.admin.AdamMemberCodeGenParam;
import com.liquidnet.service.adam.dto.admin.AdamMemberCodeListParam;
import com.liquidnet.service.adam.entity.AdamMemberCode;
import com.liquidnet.service.adam.entity.AdamMemberCodeBatch;
import com.liquidnet.service.adam.entity.AdamMemberPrice;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Api(tags = "会员码管理")
@Controller
@RequestMapping("adam/mcode")
public class AdamMemberCodeAdminController extends BaseController {
    private final String prefix = "zhengzai/adam/member/code";
    @Autowired
    IAdamMemberCodeBatchAdminService adamMemberCodeBatchAdminService;
    @Autowired
    IAdamMemberCodeAdminService adamMemberCodeAdminService;
    @Autowired
    IAdamMemberPriceAdminService adamMemberPriceAdminService;

    @GetMapping("mgt")
    public String viewCodeMgt(@RequestParam String memberId, ModelMap mmap) {
        mmap.put("memberId", memberId);
        List<AdamMemberPrice> memberPriceList = adamMemberPriceAdminService.list(Wrappers.lambdaQuery(AdamMemberPrice.class)
                .eq(AdamMemberPrice::getState, 1)
                .eq(AdamMemberPrice::getMemberId, memberId)
                .select(
                        AdamMemberPrice::getMid,
                        AdamMemberPrice::getMemberPriceId,
                        AdamMemberPrice::getName,
                        AdamMemberPrice::getPrice,
                        AdamMemberPrice::getPriceFixed,
                        AdamMemberPrice::getPriceSpecial,
                        AdamMemberPrice::getDays
                )
                .orderByAsc(AdamMemberPrice::getDays)
        );
        // 默认选中天数最长的价格包（通常为年卡），创建时可改选其它档
        AdamMemberPrice memberPrice = CollectionUtils.isEmpty(memberPriceList) ? null
                : memberPriceList.stream()
                .max(Comparator.comparing(AdamMemberPrice::getDays, Comparator.nullsFirst(Integer::compareTo)))
                .orElse(null);
        mmap.put("memberPrice", memberPrice);
        mmap.put("memberPriceList", memberPriceList);
        return prefix + "/code_mgt";
    }

    @ApiOperation(value = "会员码:上线价格包列表")
    @RequiresPermissions("adam:member:code:creation")
    @GetMapping("mgt/prices")
    @ResponseBody
    public AjaxResult listOnlinePrices(@RequestParam String memberId) {
        List<AdamMemberPrice> memberPriceList = adamMemberPriceAdminService.list(Wrappers.lambdaQuery(AdamMemberPrice.class)
                .eq(AdamMemberPrice::getState, 1)
                .eq(AdamMemberPrice::getMemberId, memberId)
                .select(
                        AdamMemberPrice::getMid,
                        AdamMemberPrice::getMemberPriceId,
                        AdamMemberPrice::getName,
                        AdamMemberPrice::getPrice,
                        AdamMemberPrice::getPriceFixed,
                        AdamMemberPrice::getPriceSpecial,
                        AdamMemberPrice::getDays
                )
                .orderByAsc(AdamMemberPrice::getDays)
        );
        return AjaxResult.success(memberPriceList);
    }

    @RequiresPermissions("adam:member:code:mgt:list")
    @Log(title = "会员管理:会员码:管理", businessType = BusinessType.LIST)
    @PostMapping("mgt/list")
    @ResponseBody
    public TableDataInfo listCodeMgt(@RequestParam String memberId) {
        LambdaQueryWrapper<AdamMemberCodeBatch> queryWrapper = Wrappers.lambdaQuery(AdamMemberCodeBatch.class);
        queryWrapper.eq(AdamMemberCodeBatch::getState, 1);
        // 本页按会员进入：只看该会员批次（member_id 精确匹配）
        if (StringUtils.isNotBlank(memberId)) {
            queryWrapper.eq(AdamMemberCodeBatch::getMemberId, memberId);
        }

        queryWrapper.select(
                AdamMemberCodeBatch::getBatchNo,
                AdamMemberCodeBatch::getMemberName,
                AdamMemberCodeBatch::getMemberCombo,
                AdamMemberCodeBatch::getMemberPriceId,
                AdamMemberCodeBatch::getGenNum,
                AdamMemberCodeBatch::getUseNum,
                AdamMemberCodeBatch::getDetail,
                AdamMemberCodeBatch::getOperator,
                AdamMemberCodeBatch::getCreatedAt
        );
        queryWrapper.orderByDesc(AdamMemberCodeBatch::getCreatedAt);

        logger.info("update member_code_batch.use_num:{}", adamMemberCodeBatchAdminService.updateBatchUseNum());

        this.startPage();
        return getDataTable(adamMemberCodeBatchAdminService.list(queryWrapper));
    }

    @ApiOperation(value = "会员码:创建")
    @RequiresPermissions("adam:member:code:creation")
    @Log(title = "会员管理:会员码:创建", businessType = BusinessType.INSERT)
    @PostMapping("mgt/creation")
    @ResponseBody
    public AjaxResult creationCodeMgt(@Validated AdamMemberCodeGenParam parameter) {
        int count = adamMemberPriceAdminService.count(
                Wrappers.lambdaQuery(AdamMemberPrice.class)
                        .eq(AdamMemberPrice::getMemberPriceId, parameter.getMemberPriceId())
                        .eq(AdamMemberPrice::getMemberId, parameter.getMemberId())
                        .eq(AdamMemberPrice::getState, 1)
        );
        if (count <= 0) {
            logger.warn("会员卡ID/价格ID无效[{}]", parameter);
            return this.error("会员卡ID/价格ID无效");
        }
        return this.toAjax(adamMemberCodeAdminService.createGiftCode(parameter));
    }

    @GetMapping("mgt/code")
    public String viewCode(@RequestParam String batchNo, ModelMap mmap) {
        mmap.put("batchNo", batchNo);
        return prefix + "/code";
    }

    @ApiOperation(value = "会员码:列表")
    @RequiresPermissions("adam:member:code:list")
    @Log(title = "会员管理:会员码:列表", businessType = BusinessType.LIST)
    @PostMapping("list")
    @ResponseBody
    public TableDataInfo listCode(AdamMemberCodeListParam parameter) {
        this.startPage();
        return getDataTable(codeListQuery(parameter));
    }

    private List<AdamMemberCode> codeListQuery(AdamMemberCodeListParam parameter) {
        LambdaQueryWrapper<AdamMemberCode> queryWrapper = Wrappers.lambdaQuery(AdamMemberCode.class).orderByDesc(AdamMemberCode::getCreatedAt);
        queryWrapper.eq(AdamMemberCode::getBatchNo, parameter.getBatchNo());
        queryWrapper.eq(AdamMemberCode::getType, 2);
        queryWrapper.ne(AdamMemberCode::getState, 2);
        if (StringUtils.isNotBlank(parameter.getCode())) {
            queryWrapper.eq(AdamMemberCode::getCode, parameter.getCode());
        }
        if (null != parameter.getState()) {
            queryWrapper.eq(AdamMemberCode::getState, parameter.getState());
        }
        queryWrapper.select(
                AdamMemberCode::getMemberNo,
                AdamMemberCode::getCode,
                AdamMemberCode::getState,
                AdamMemberCode::getUseAt
        );
        queryWrapper.orderByDesc(AdamMemberCode::getMemberNo);

        return adamMemberCodeAdminService.list(queryWrapper);
    }

    @ApiOperation(value = "会员码:导出")
    @RequiresPermissions("adam:member:code:export")
    @Log(title = "会员管理:会员码:导出", businessType = BusinessType.EXPORT)
    @PostMapping("export")
    @ResponseBody
    public AjaxResult exportCode(AdamMemberCodeListParam parameter) {
        List<AdamMemberCode> list = codeListQuery(parameter);

        ExcelUtil<AdamMemberCodeExcelDto> excelUtil = new ExcelUtil<>(AdamMemberCodeExcelDto.class);
        List<AdamMemberCodeExcelDto> excelList = new ArrayList<>();
        list.forEach(r -> {
            excelList.add(AdamMemberCodeExcelDto.getNew().copy(r));
        });
        return excelUtil.exportExcel(excelList, "会员码数据");
    }
}
