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

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.zhengzai.adam.service.IAdamCaomeiBadgeAdminService;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.adam.dto.param.AdamCaomeiBadgeParam;
import com.liquidnet.service.adam.dto.param.AdamCaomeiBadgeClaimUserSearchParam;
import com.liquidnet.service.adam.dto.param.AdamCaomeiBadgeSearchParam;
import com.github.pagehelper.PageInfo;
import com.liquidnet.service.adam.entity.AdamCaomeiBadge;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Objects;
@Api(tags = "草莓护照-徽章管理")
@Controller
@RequestMapping("adam/caomei/badge")
public class AdamCaomeiBadgeController extends BaseController {

    private final String prefix = "zhengzai/adam/caomei/badge";

    private static final int BADGE_NAME_MAX_CHARS = 50;
    private static final int BADGE_SUBTITLE_MAX_CHARS = 20;

    @Autowired
    private IAdamCaomeiBadgeAdminService adamCaomeiBadgeAdminService;

    @Value("${liquidnet.client.admin.platformUrl}")
    private String platformUrl;

    @RequiresPermissions("adam:caomei:badge:list")
    @GetMapping()
    public String view() {
        return prefix + "/badge_list";
    }

    @RequiresPermissions("adam:caomei:badge:list")
    @PostMapping("list")
    @ResponseBody
    public TableDataInfo list(AdamCaomeiBadgeSearchParam param) {
        startPage();
        PageInfo<?> pageInfo = adamCaomeiBadgeAdminService.listWithClaimedCount(param);
        return getDataTable(pageInfo);
    }

    @RequiresPermissions("adam:caomei:badge:add")
    @GetMapping("add")
    public String add(ModelMap mmap) {
        mmap.put("platformUrl", platformUrl);
        return prefix + "/badge_add";
    }

    @RequiresPermissions("adam:caomei:badge:add")
    @Log(title = "草莓护照-徽章管理:新增", businessType = BusinessType.INSERT)
    @PostMapping("add")
    @ResponseBody
    public AjaxResult addSave(AdamCaomeiBadgeParam param) {
        if (param == null) {
            return error("参数错误");
        }
        AjaxResult nameCheck = validateBadgeName(param.getName());
        if (nameCheck != null) {
            return nameCheck;
        }
        AjaxResult subTitleCheck = validateBadgeSubTitle(param.getSubTitle());
        if (subTitleCheck != null) {
            return subTitleCheck;
        }
        String trimmedName = StringUtils.trimToEmpty(param.getName());

        AdamCaomeiBadge badge = new AdamCaomeiBadge();
        BeanUtils.copyProperties(param, badge);
        badge.setName(trimmedName);
        badge.setSubTitle(StringUtils.trimToEmpty(param.getSubTitle()));
        badge.setShareText(StringUtils.defaultString(badge.getShareText()));
        badge.setBadgeId(IDGenerator.nextSnowId());
        badge.setDisplayStatus(0); // 默认下架
        if (badge.getSort() == null) {
            badge.setSort(0);
        }
        badge.setCreatedAt(new Date());
        badge.setUpdatedAt(new Date());

        // 演出纪念徽章、签证页须关联音乐节
        if (badgeRequiresPerformance(badge.getType())) {
            String pid = StringUtils.trimToEmpty(badge.getPerformanceId());
            if (StringUtils.isBlank(pid)) {
                return error(badgePerformanceRequiredMessage(badge.getType()));
            }
            badge.setPerformanceId(pid);
            if (!adamCaomeiBadgeAdminService.kylinPerformanceExists(pid)) {
                return error("无相关演出");
            }
        } else {
            badge.setPerformanceId("");
        }

        return toAjax(adamCaomeiBadgeAdminService.save(badge));
    }

    @RequiresPermissions("adam:caomei:badge:list")
    @GetMapping("detail/{badgeId}")
    public String detail(@PathVariable("badgeId") String badgeId, ModelMap mmap) {
        AdamCaomeiBadge badge = adamCaomeiBadgeAdminService.getOne(
                Wrappers.lambdaQuery(AdamCaomeiBadge.class).eq(AdamCaomeiBadge::getBadgeId, badgeId), false
        );
        mmap.put("badge", badge);
        return prefix + "/badge_detail";
    }

    @RequiresPermissions("adam:caomei:badge:list")
    @GetMapping("claimUsers/{badgeId}")
    public String claimUsers(@PathVariable("badgeId") String badgeId, ModelMap mmap) {
        mmap.put("badgeId", badgeId);
        return prefix + "/badge_claim_users";
    }

    @RequiresPermissions("adam:caomei:badge:list")
    @PostMapping("claimUsers/list")
    @ResponseBody
    public TableDataInfo claimUsersList(AdamCaomeiBadgeClaimUserSearchParam param) {
        startPage();
        PageInfo<?> pageInfo = adamCaomeiBadgeAdminService.listClaimUsers(param);
        return getDataTable(pageInfo);
    }

    @RequiresPermissions("adam:caomei:badge:edit")
    @GetMapping("edit/{badgeId}")
    public String edit(@PathVariable("badgeId") String badgeId, ModelMap mmap) {
        AdamCaomeiBadge badge = adamCaomeiBadgeAdminService.getOne(
                Wrappers.lambdaQuery(AdamCaomeiBadge.class).eq(AdamCaomeiBadge::getBadgeId, badgeId), false
        );
        mmap.put("badge", badge);
        mmap.put("platformUrl", platformUrl);
        return prefix + "/badge_edit";
    }

    @RequiresPermissions("adam:caomei:badge:edit")
    @Log(title = "草莓护照-徽章管理:修改", businessType = BusinessType.UPDATE)
    @PostMapping("edit")
    @ResponseBody
    public AjaxResult editSave(AdamCaomeiBadgeParam param) {
        if (param == null || StringUtils.isBlank(param.getBadgeId())) {
            return error("参数错误");
        }
        AdamCaomeiBadge oldBadge = adamCaomeiBadgeAdminService.getOne(
                Wrappers.lambdaQuery(AdamCaomeiBadge.class).eq(AdamCaomeiBadge::getBadgeId, param.getBadgeId()), false
        );
        if (oldBadge == null || oldBadge.getDisplayStatus() == 1) {
            return error("已发布的徽章不允许修改");
        }
        AjaxResult nameCheck = validateBadgeName(param.getName());
        if (nameCheck != null) {
            return nameCheck;
        }
        AjaxResult subTitleCheck = validateBadgeSubTitle(param.getSubTitle());
        if (subTitleCheck != null) {
            return subTitleCheck;
        }
        String trimmedName = StringUtils.trimToEmpty(param.getName());
        if (!Objects.equals(param.getType(), oldBadge.getType())) {
            return error("徽章类型不允许修改");
        }

        AdamCaomeiBadge badge = new AdamCaomeiBadge();
        BeanUtils.copyProperties(param, badge);
        badge.setName(trimmedName);
        badge.setSubTitle(StringUtils.trimToEmpty(param.getSubTitle()));
        badge.setShareText(StringUtils.defaultString(badge.getShareText()));
        badge.setMid(oldBadge.getMid());
        badge.setUpdatedAt(new java.util.Date());
        // 徽章类型与「已发布不可改」一致：编辑时不允许变更类型
        badge.setType(oldBadge.getType());
        if (badgeRequiresPerformance(badge.getType())) {
            String pid = StringUtils.trimToEmpty(badge.getPerformanceId());
            if (StringUtils.isBlank(pid)) {
                return error(badgePerformanceRequiredMessage(badge.getType()));
            }
            badge.setPerformanceId(pid);
            if (!adamCaomeiBadgeAdminService.kylinPerformanceExists(pid)) {
                return error("无相关演出");
            }
        } else {
            badge.setPerformanceId("");
        }
        return toAjax(adamCaomeiBadgeAdminService.updateById(badge));
    }

    @RequiresPermissions("adam:caomei:badge:edit")
    @Log(title = "草莓护照-徽章管理:状态修改", businessType = BusinessType.UPDATE)
    @PostMapping("changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(AdamCaomeiBadgeParam param) {
        AdamCaomeiBadge oldBadge = adamCaomeiBadgeAdminService.getOne(
                Wrappers.lambdaQuery(AdamCaomeiBadge.class).eq(AdamCaomeiBadge::getBadgeId, param.getBadgeId()), false
        );
        if (oldBadge == null) {
            return error("操作失败：未找到徽章");
        }
        AdamCaomeiBadge updateBadge = new AdamCaomeiBadge();
        updateBadge.setMid(oldBadge.getMid());
        updateBadge.setDisplayStatus(param.getDisplayStatus());
        updateBadge.setUpdatedAt(new java.util.Date());
        return toAjax(adamCaomeiBadgeAdminService.updateById(updateBadge));
    }

    private static boolean badgeRequiresPerformance(Integer type) {
        return type != null && (type == 2 || type == 4);
    }

    private static String badgePerformanceRequiredMessage(Integer type) {
        if (type != null && type == 4) {
            return "签证页必须关联音乐节";
        }
        return "演出纪念徽章必须关联演出";
    }

    /**
     * @return 校验通过返回 null，否则返回错误 AjaxResult
     */
    private AjaxResult validateBadgeName(String name) {
        String n = StringUtils.trimToEmpty(name);
        if (StringUtils.isBlank(n)) {
            return error("徽章名称不能为空");
        }
        int len = n.codePointCount(0, n.length());
        if (len > BADGE_NAME_MAX_CHARS) {
            return error("徽章名称不能超过" + BADGE_NAME_MAX_CHARS + "个字");
        }
        return null;
    }

    private AjaxResult validateBadgeSubTitle(String subTitle) {
        String s = StringUtils.trimToEmpty(subTitle);
        if (StringUtils.isBlank(s)) {
            return null;
        }
        int len = s.codePointCount(0, s.length());
        if (len > BADGE_SUBTITLE_MAX_CHARS) {
            return error("徽章副标题不能超过" + BADGE_SUBTITLE_MAX_CHARS + "个字");
        }
        return null;
    }
}
