package com.sundot.airport.web.controller.score;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sundot.airport.common.annotation.Log;
import com.sundot.airport.common.core.controller.BaseController;
import com.sundot.airport.common.core.domain.AjaxResult;
import com.sundot.airport.common.core.page.TableDataInfo;
import com.sundot.airport.common.enums.BusinessType;
import com.sundot.airport.common.utils.DateUtils;
import com.sundot.airport.common.utils.poi.ExcelUtil;
import com.sundot.airport.ledger.domain.ScoreEvent;
import com.sundot.airport.ledger.domain.ScoreIndicator;
import com.sundot.airport.ledger.mapper.ScoreIndicatorMapper;
import com.sundot.airport.ledger.service.IScoreEventService;
import com.sundot.airport.ledger.service.IScoreIndicatorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 配分事项管理（手动录入 + Excel导入）
 */
@RestController
@RequestMapping("/score/event")
public class ScoreEventController extends BaseController {

    @Autowired
    private IScoreEventService service;

    @Autowired
    private IScoreIndicatorService indicatorService;

    @PreAuthorize("@ss.hasPermi('score:event:list')")
    @GetMapping("/list")
    public TableDataInfo list(ScoreEvent query) {
        startPage();
        return getDataTable(service.selectList(query));
    }

    @PreAuthorize("@ss.hasPermi('score:event:export')")
    @Log(title = "配分事项", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ScoreEvent query) {
        List<ScoreEvent> list = service.selectList(query);
        new ExcelUtil<>(ScoreEvent.class).exportExcel(response, list, "配分事项");
    }

    @PreAuthorize("@ss.hasPermi('score:event:query')")
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return AjaxResult.success(service.getById(id));
    }

    @PreAuthorize("@ss.hasPermi('score:event:add')")
    @Log(title = "配分事项", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody ScoreEvent entity) {
        entity.setSourceType("1");
        entity.setCreateBy(getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        
        // 通过指标名称查找并设置ID
        resolveIndicatorIds(entity);
        
        // 计算 totalScore
        BigDecimal score = entity.getScoreValue() != null ? entity.getScoreValue() : BigDecimal.ZERO;
        BigDecimal cascade = entity.getCascadeScore() != null ? entity.getCascadeScore() : BigDecimal.ZERO;
        entity.setTotalScore(score.add(cascade));
        return toAjax(service.save(entity));
    }

    @PreAuthorize("@ss.hasPermi('score:event:edit')")
    @Log(title = "配分事项", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody ScoreEvent entity) {
        entity.setUpdateBy(getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        
        // 通过指标名称查找并设置ID
        resolveIndicatorIds(entity);
        
        BigDecimal score = entity.getScoreValue() != null ? entity.getScoreValue() : BigDecimal.ZERO;
        BigDecimal cascade = entity.getCascadeScore() != null ? entity.getCascadeScore() : BigDecimal.ZERO;
        entity.setTotalScore(score.add(cascade));
        return toAjax(service.updateById(entity));
    }

    @PreAuthorize("@ss.hasPermi('score:event:remove')")
    @Log(title = "配分事项", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        for (Long id : ids) service.removeById(id);
        return AjaxResult.success();
    }

    @PreAuthorize("@ss.hasPermi('score:event:import')")
    @Log(title = "配分事项导入", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult importData(@RequestParam("file") MultipartFile file) throws Exception {
        String batchNo = UUID.randomUUID().toString().replace("-", "").substring(0, 16);
        List<ScoreEvent> list = new ArrayList<>();
        EasyExcel.read(file.getInputStream(), ScoreEvent.class, new AnalysisEventListener<ScoreEvent>() {
            @Override
            public void invoke(ScoreEvent data, AnalysisContext ctx) { list.add(data); }
            @Override
            public void doAfterAllAnalysed(AnalysisContext ctx) {}
        }).sheet().doRead();
        list.forEach(item -> {
            item.setSourceType("1");
            item.setImportBatch(batchNo);
            item.setCreateBy(getUsername());
        });
        service.batchInsert(list);
        return AjaxResult.success("导入成功，共" + list.size() + "条");
    }

    /**
     * 通过指标名称查找并设置ID
     */
    private void resolveIndicatorIds(ScoreEvent entity) {
        // 通过二级指标名称查找ID
        if (entity.getLevel2Name() != null && !entity.getLevel2Name().trim().isEmpty() && entity.getLevel2Id() == null) {
            Long level2Id = findIndicatorIdByName(entity.getLevel2Name().trim());
            if (level2Id != null) {
                entity.setLevel2Id(level2Id);
            }
        }
        
        // 通过三级指标名称查找ID
        if (entity.getLevel3Name() != null && !entity.getLevel3Name().trim().isEmpty() && entity.getLevel3Id() == null) {
            Long level3Id = findIndicatorIdByName(entity.getLevel3Name().trim());
            if (level3Id != null) {
                entity.setLevel3Id(level3Id);
            }
        }
        
        // 通过四级指标名称查找ID
        if (entity.getLevel4Name() != null && !entity.getLevel4Name().trim().isEmpty() && entity.getLevel4Id() == null) {
            Long level4Id = findIndicatorIdByName(entity.getLevel4Name().trim());
            if (level4Id != null) {
                entity.setLevel4Id(level4Id);
            }
        }
    }

    /**
     * 通过名称查找指标ID
     */
    private Long findIndicatorIdByName(String name) {
        if (name == null || name.trim().isEmpty()) {
            return null;
        }
        LambdaQueryWrapper<ScoreIndicator> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ScoreIndicator::getName, name.trim());
        ScoreIndicator indicator = indicatorService.getOne(wrapper);
        return indicator != null ? indicator.getId() : null;
    }
}
