package com.centreproject.web.controller.kpi;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.centreproject.common.constant.KeyConstants;
import com.centreproject.common.core.domain.R;
import com.centreproject.system.domain.sync.kpi.DataSyncLog;
import com.centreproject.system.domain.sync.kpi.SyncRule;
import com.centreproject.system.service.sync.ISyncRuleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * This controller is used to synchronize the rules between the media and the KPI system.
 * @author zhonglei.xu
 */
@Tag(name = "sync_rule")
@RestController
@RequestMapping("/kpi/sync_rule-media")
public class SyncRuleController {

    @Autowired
    private ISyncRuleService syncRuleService;


    /**
     * 同步规则列表
     * @param syncRule 查询条件
     * @param pageNum  页码 默认1
     * @param pageSize 条数 默认10
     * @return log
     */
    @GetMapping("/page")
    @Operation(summary = "page")
    public R<Page<SyncRule>> page(@ModelAttribute SyncRule syncRule,
                                  @RequestParam(defaultValue = "1")int pageNum,
                                  @RequestParam(defaultValue = "10")int pageSize) {
        Page<SyncRule> result = syncRuleService.getPage(syncRule, pageNum, pageSize);
        return R.ok(result, KeyConstants.RULE);
    }


    /**
     * 同步规则保存
     * @param syncRule 保存
     * @return log
     */
    @PostMapping("/save")
    @Operation(summary = "save")
    public R save(@RequestBody SyncRule syncRule) {
        // 检查 module_name 和 field_name 是否为空
        if (StringUtils.isEmpty(syncRule.getModuleName()) || StringUtils.isEmpty(syncRule.getFieldName())) {
            return R.fail("module or Indicator field name can not null");
        }

        // 检查是否已存在相同 ruleType+module_name + field_name 的记录（排除自身）
        LambdaQueryWrapper<SyncRule> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SyncRule::getModuleName, syncRule.getModuleName())
                .eq(SyncRule::getFieldName, syncRule.getFieldName())
                .eq(SyncRule::getRuleType, syncRule.getRuleType());

        if (syncRule.getId() != null) {
            queryWrapper.ne(SyncRule::getId, syncRule.getId());
        }

        long count = syncRuleService.count(queryWrapper);
        if (count > 0) {
           return R.fail(String.format("Duplicate combination detected: '%s + %s'. Please use a unique combination."
                   ,syncRule.getModuleName()
                   ,syncRule.getFieldName()));
        }

        // 执行保存或更新
        if (syncRule.getId() == null) {
            syncRuleService.save(syncRule);
        } else {
            syncRuleService.updateById(syncRule);
        }
        return R.ok(syncRule, KeyConstants.RULE);
    }

    /**
     * 同步规则保存
     * @param id id
     * @return log
     */
    @GetMapping("/delete/{id}")
    @Operation(summary = "page")
    public void delete(@PathVariable("id") Long id) {
        syncRuleService.removeById(id);
    }

    /**
     * 批量保存
     * @param lists 保存
     * @return log
     */
    @PostMapping("/batch-insert")
    @Operation(summary = "batch-insert")
    public void batchInsert(@RequestBody List<SyncRule> lists) {
        syncRuleService.saveOrUpdateBatch(lists);
    }


}
