package org.eco.als.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.eco.als.domain.bo.ModelBo;
import org.eco.als.domain.vo.ModelImportVo;
import org.eco.als.domain.vo.ModelVo;
import org.eco.als.listener.ModelImportListener;
import org.eco.als.service.IModelService;
import org.eco.common.core.core.domain.CommonResult;
import org.eco.common.core.core.domain.model.LoginUser;
import org.eco.common.core.core.page.PageResult;
import org.eco.common.excel.core.ExcelResult;
import org.eco.common.excel.utils.ExcelUtil;
import org.eco.common.log.annotation.Log;
import org.eco.common.log.enums.BusinessType;
import org.eco.common.security.utils.LoginHelper;
import org.eco.common.web.annotation.RepeatSubmit;
import org.eco.common.web.core.BaseController;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 模型信息Controller
 *
 * @author wgk
 * @date 2024-07-22
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/als/model")
public class ModelController extends BaseController {
    @Resource
    private IModelService modelService;

    /**
     * 查询模型信息列表
     */
    @SaCheckPermission("als:model:list")
    @GetMapping("/list")
    public CommonResult<PageResult<ModelVo>> list(ModelBo modelBo) {
        return CommonResult.success(modelService.selectPage(modelBo));
    }

    @SaCheckPermission("als:model:import")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil.exportExcel(new ArrayList<>(), "模型信息", ModelImportVo.class, response);
    }

    /**
     * 导出
     */
    @Log(title = "模型信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ModelBo modelBo) {
        List<ModelVo> list = modelService.selectList(modelBo);
        ExcelUtil.exportExcel(list, "模型信息", ModelVo.class, response);
    }

    /**
     * 导入飞机构型列表
     */
    @Log(title = "飞机构型", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public CommonResult<Void> syncImportData(MultipartFile file, boolean updateSupport) throws Exception {
        LoginUser loginUser = LoginHelper.getLoginUser();
        ExcelResult<ModelImportVo> result = ExcelUtil.importExcel(file.getInputStream(), ModelImportVo.class, new ModelImportListener(updateSupport, loginUser));
        return CommonResult.success(result.getAnalysis().getLogInfo());
    }

    /**
     * 获取模型信息详细信息
     */
    @SaCheckPermission("als:model:query")
    @GetMapping(value = "/{id}")
    public CommonResult<ModelVo> getInfo(@PathVariable Long id) {
        return CommonResult.success(modelService.selectById(id));
    }

    /**
     * 新增模型信息
     */
    @SaCheckPermission("als:model:add")
    @Log(title = "模型信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping
    public CommonResult<Void> add(@Validated @RequestBody ModelBo modelBo) {
        if (StrUtil.containsAny(modelBo.getType(),  "6")) {
            if (StrUtil.isBlank(modelBo.getPartId())) {
                return CommonResult.fail("部件不能为空.");
            }
            ModelBo modelBo1 = new ModelBo();
            modelBo1.setPartId(modelBo.getPartId());
            modelBo1.setType(modelBo.getType());
            List<ModelVo> modelVos = modelService.selectList(modelBo1);
            if (CollUtil.isNotEmpty(modelVos)) {
                return CommonResult.fail("模型算法添加重复，请重新输入部件");
            }
        }
        boolean inserted = modelService.insert(modelBo);
        if (!inserted) {
            return CommonResult.fail("新增模型信息记录失败！");
        }
        return CommonResult.success();
    }

    /**
     * 修改模型信息
     */
    @SaCheckPermission("als:model:edit")
    @Log(title = "模型信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping
    public CommonResult<Void> edit(@Validated @RequestBody ModelBo modelBo) {
        if (StrUtil.containsAny(modelBo.getType(), "5", "6")) {
            if (StrUtil.isBlank(modelBo.getPartId())) {
                return CommonResult.fail("部件不能为空.");
            }
            ModelBo modelBo1 = new ModelBo();
            modelBo1.setPartId(modelBo.getPartId());
            modelBo1.setType(modelBo.getType());
            List<ModelVo> modelVos = modelService.selectList(modelBo1);
            if (CollUtil.isNotEmpty(modelVos)) {
                if (modelVos.stream().noneMatch(modelVo -> modelBo.getId().equals(modelVo.getId()))) {
                    return CommonResult.fail("模型算法添加重复，请重新输入部件");
                }
            }
        }
        boolean updated = modelService.update(modelBo);
        if (!updated) {
            return CommonResult.fail("修改模型信息记录失败!");
        }
        return CommonResult.success();
    }

    /**
     * 删除模型信息
     */
    @SaCheckPermission("als:model:remove")
    @Log(title = "模型信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public CommonResult<Void> remove(@PathVariable Long[] ids) {
        boolean deleted = modelService.deleteByIds(ids);
        if (!deleted) {
            return CommonResult.fail("删除模型信息记录失败!");
        }
        return CommonResult.success();
    }
}
