package com.artfess.cqlt.controller;


import com.alibaba.fastjson.JSON;
import com.artfess.base.annotation.ApiGroup;
import com.artfess.base.annotation.PowerLogInfo;
import com.artfess.base.constants.ApiGroupConsts;
import com.artfess.base.controller.BaseController;
import com.artfess.base.enums.DelStatusEnum;
import com.artfess.base.enums.LogType;
import com.artfess.base.enums.OperationType;
import com.artfess.base.model.CommonResult;
import com.artfess.base.valid.AddGroup;
import com.artfess.base.valid.UpdateGroup;
import com.artfess.cqlt.manager.QfSubjectInternationalInfoManager;
import com.artfess.cqlt.model.QfSubjectInternationalInfo;
import com.artfess.i18n.util.I18nUtil;
import com.artfess.poi.util.ExcelUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 国际准则科目信息 前端控制器
 *
 * @company 阿特菲斯信息技术有限公司
 * @author min.wu
 * @since 2023-02-08
 */
@Slf4j
@RestController
@Api(tags = "国际准则科目信息")
@RequestMapping("/qf/subject/international/info/")
@ApiGroup(group = {ApiGroupConsts.GROUP_BIZ})
public class QfSubjectInternationalInfoController extends BaseController<QfSubjectInternationalInfoManager, QfSubjectInternationalInfo> {

    @Override
    @PostMapping("/")
    @ApiOperation("添加实体的接口")
    public CommonResult<String> create(@ApiParam(name="model", value="实体信息") @RequestBody @Validated({AddGroup.class}) QfSubjectInternationalInfo t) {
        String id = baseService.newInsertTree(t);
        int length = t.getFullId().split("/").length - 1;
        t.setLevel(length+"");
        if(t.getSn() == null){
            t.setSn(baseService.getNextSequence(null));
        }
        baseService.updateById(t);
        if(!StringUtils.isNotBlank(id)) {
            return new CommonResult<String>(false, I18nUtil.getMessage("option.fail", LocaleContextHolder.getLocale()), null);
        }
        return new CommonResult<String>(true, I18nUtil.getMessage("option.success", LocaleContextHolder.getLocale()), null);
    }

    @Override
    @PutMapping("/")
    @ApiOperation("更新实体")
    public CommonResult<String> updateById(@ApiParam(name="model", value="实体信息") @RequestBody @Validated({UpdateGroup.class}) QfSubjectInternationalInfo t) {
        QfSubjectInternationalInfo byId = baseService.getById(t.getId());
        String id = baseService.newUpdateTree(t, byId.getName());
        int length = t.getFullId().split("/").length - 1;
        t.setLevel(length+"");
        if(t.getSn() == null){
            t.setSn(baseService.getNextSequence(null));
        }
        baseService.updateById(t);
        if(!StringUtils.isNotBlank(id)) {
            return new CommonResult<String>(false, I18nUtil.getMessage("update.fail", LocaleContextHolder.getLocale()), null);
        }
        return new CommonResult<String>(true, I18nUtil.getMessage("option.success", LocaleContextHolder.getLocale()), null);
    }

    @Override
    @DeleteMapping("/{id}")
    @ApiOperation("根据id删除")
    public CommonResult<String> deleteById(@ApiParam(name="id", value="实体id") @PathVariable String id) {
        boolean result = baseService.removeById(id);
        if(!result) {
            return new CommonResult<String>(false, I18nUtil.getMessage("delete.fail", LocaleContextHolder.getLocale()), null);
        }
        return new CommonResult<String>(true, I18nUtil.getMessage("option.success", LocaleContextHolder.getLocale()), null);
    }

    @Override
    @DeleteMapping("/")
    @ApiOperation("根据id集合批量删除")
    public CommonResult<String> deleteByIds(@ApiParam(name="ids", value="实体集合") @RequestParam String...ids) {
        boolean result = baseService.removeByIds(Arrays.asList(ids));
        if(!result) {
            return new CommonResult<String>(false, I18nUtil.getMessage("delete.fail", LocaleContextHolder.getLocale()), null);
        }
        return new CommonResult<String>(true, I18nUtil.getMessage("option.success", LocaleContextHolder.getLocale()), null);
    }

    @PostMapping("/getTree")
    @ApiOperation("获取国际准则科目信息下拉树")
    @PowerLogInfo(logType = LogType.BIZ, operaionType = OperationType.QUERY, description = "获取国际准则科目信息下拉树")
    public CommonResult<String> getTree(@ApiParam(name = "model", value = "获取资料分类下拉树") @RequestBody QfSubjectInternationalInfo entity) {
        log.info("获取国际准则科目信息下拉树请求参数:{}", JSON.toJSONString(entity));
        List<QfSubjectInternationalInfo> list = baseService.getTree(entity);
        return CommonResult.success(list, null);
    }

    @RequestMapping(value = "updateSequence", method = RequestMethod.POST, produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "批量修改排序号", notes = "批量修改排序号")
    public CommonResult<String> updateSequence(@ApiParam(name = "params", value = "排序参数：Key：ID，Value：排序号") @RequestBody HashMap<String, Integer> params) throws Exception {
        if(!params.isEmpty()){
            baseService.updateSequence(params);
        }
        return new CommonResult<String>(true, I18nUtil.getMessage("option.success", LocaleContextHolder.getLocale()), null);
    }

    @PostMapping("/move")
    @ApiOperation("移动科目的上下级")
    public CommonResult<String> move(@RequestBody QfSubjectInternationalInfo entity) {
        boolean result = baseService.move(entity);
        QueryWrapper<QfSubjectInternationalInfo> queryWrapper = new QueryWrapper<QfSubjectInternationalInfo>();
        queryWrapper.eq("parent_Id_",entity.getId());
        queryWrapper.eq("is_dele_", DelStatusEnum.N.getType());
        List<QfSubjectInternationalInfo> ts = baseService.list(queryWrapper);
        ts.forEach(qfSubjectInfo -> {
            int length = qfSubjectInfo.getFullName().split("/").length - 1;
            qfSubjectInfo.setLevel(length+"");
        });
        baseService.updateBatchById(ts);
        if(!result) {
            return new CommonResult<String>(false, I18nUtil.getMessage("delete.fail", LocaleContextHolder.getLocale()), null);
        }
        return new CommonResult<String>(true, I18nUtil.getMessage("option.success", LocaleContextHolder.getLocale()), null);
    }

    /**
     * @param file
     * @return
     */
    @ApiOperation(value = "国际科目数据导入")
    @PostMapping("/importExcel")
    public CommonResult<String> importExcel(@RequestParam("file") MultipartFile file) {
        try {
            ExcelUtils<QfSubjectInternationalInfo> excelUtil = new ExcelUtils<>(QfSubjectInternationalInfo.class);
            List<QfSubjectInternationalInfo> list = excelUtil.importExcel(null, file.getInputStream());
            boolean result = baseService.importExcel(list);
            if (!result) {
                throw new IllegalArgumentException(I18nUtil.getMessage("import.fail", LocaleContextHolder.getLocale()));
            }
            return new CommonResult<>();
        } catch (Exception e) {
            e.printStackTrace();
            throw new IllegalArgumentException(I18nUtil.getMessage("import.fail", LocaleContextHolder.getLocale()) + "," + e.getMessage());
        }
    }


    /**
     * @return
     */
    @ApiOperation(value = "批量修改科目")
    @PostMapping("/batchUpdate")
    public CommonResult<String> batchUpdate() {
        try {
            boolean result = baseService.batchUpdate();
            if (!result) {
                throw new IllegalArgumentException(I18nUtil.getMessage("import.fail", LocaleContextHolder.getLocale()));
            }
            return new CommonResult<>();
        } catch (Exception e) {
            throw new IllegalArgumentException(I18nUtil.getMessage("import.fail", LocaleContextHolder.getLocale()) + "," + e.getMessage());
        }
    }

}
