package com.fs.company.controller.newAdv;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fs.common.result.Result;
import com.fs.newAdv.domain.PromotionAccount;
import com.fs.newAdv.enums.AdvertiserTypeEnum;
import com.fs.newAdv.service.IPromotionAccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;

/**
 * 推广账号管理控制器
 *
 * @author zhangqin
 * @date 2025-11-03
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/adv/promotion-account")
public class PromotionAccountController {

    @Autowired
    private IPromotionAccountService promotionAccountService;

    /**
     * 分页查询推广账号列表
     *
     * @param current 当前页
     * @param size 每页数量
     * @param accountName 账号名称（模糊查询）
     * @param advertiserId 广告商ID
     */
    @GetMapping("/page")
    public Result<IPage<PromotionAccount>> page(
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size,
            @RequestParam(required = false) String accountName,
            @RequestParam(required = false) String custom,
            @RequestParam(required = false) Long advertiserId) {

        Page<PromotionAccount> page = new Page<>(current, size);
        LambdaQueryWrapper<PromotionAccount> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(accountName), PromotionAccount::getAccountName, accountName);
        wrapper.eq(advertiserId != null, PromotionAccount::getAdvertiserId, advertiserId);
        wrapper.eq(custom != null, PromotionAccount::getCustom, custom);
        wrapper.orderByDesc(PromotionAccount::getCreateTime);
        IPage<PromotionAccount> page1 = promotionAccountService.page(page, wrapper);
        return Result.success(page1);
    }

    /**
     * 根据ID查询推广账号详情
     *
     * @param id 账号ID
     */
    @GetMapping("/{id}")
    public Result<PromotionAccount> getById(@PathVariable @NotNull(message = "账号ID不能为空") Long id) {
        PromotionAccount account = promotionAccountService.getById(id);
        return Result.success(account);
    }

    /**
     * 创建推广账号
     *
     * @param account 推广账号信息
     */
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> create(@RequestBody @Validated PromotionAccount account) {

        boolean success = promotionAccountService.save(account);
        checkAuthUrl(account);
        promotionAccountService.updateById(account);
        return success ? Result.success() : Result.error("创建失败");
    }

    private void checkAuthUrl(PromotionAccount account) {
        if (account.getApiSwitch() == 2){
            return;
        }
        if (account.getAdvertiserId().equals(AdvertiserTypeEnum.OCEANENGINE.getCode())){
            // 巨量
            account.setAuthUrl("https://open.oceanengine.com/audit/oauth.html?app_id="+account.getAppId()+"&state="+account.getId()+"&redirect_uri=https://track.mynatapp.cc/callback/oceanEngine/getAuthCode");
        }
        if (account.getAdvertiserId().equals(AdvertiserTypeEnum.BAIDU.getCode())){
            // 百度
            account.setAuthUrl(account.getAuthUrl().replaceAll("state=[^&]*", "state=" + account.getId()));
        }

    }

    /**
     * 更新推广账号
     *
     * @param id 账号ID
     * @param account 推广账号信息
     */
    @PutMapping("/{id}")
    public Result<Void> update(
            @PathVariable @NotNull(message = "账号ID不能为空") Long id,
            @RequestBody @Validated PromotionAccount account) {

        account.setId(id);
        checkAuthUrl(account);
        boolean success = promotionAccountService.updateById(account);
        return success ? Result.success() : Result.error("更新失败");
    }

    /**
     * 删除推广账号
     *
     * @param id 账号ID
     */
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable @NotNull(message = "账号ID不能为空") Long id) {
        boolean success = promotionAccountService.removeById(id);
        return success ? Result.success() : Result.error("删除失败");
    }

    /**
     * 批量删除推广账号
     *
     * @param ids 账号ID数组
     */
    @DeleteMapping("/batch")
    public Result<Void> batchDelete(@RequestBody Long[] ids) {
        boolean success = promotionAccountService.batchDelete(ids);
        return success ? Result.success() : Result.error("批量删除失败");
    }
}

