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.exception.RequiredException;
import com.artfess.base.model.CommonResult;
import com.artfess.base.valid.AddGroup;
import com.artfess.base.valid.UpdateGroup;
import com.artfess.cqlt.manager.QfSubjectInfoManager;
import com.artfess.cqlt.model.QfSubjectInfo;
import com.artfess.i18n.util.I18nUtil;
import com.artfess.poi.util.ExcelUtils;
import com.artfess.poi.util.FileDownloadUtil;
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.core.io.ClassPathResource;
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.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/info/")
@ApiGroup(group = {ApiGroupConsts.GROUP_BIZ})
public class QfSubjectInfoController extends BaseController<QfSubjectInfoManager, QfSubjectInfo> {

    @Override
    @PostMapping("/")
    @ApiOperation("添加实体的接口")
    public CommonResult<String> create(@ApiParam(name="model", value="实体信息") @RequestBody @Validated({AddGroup.class}) QfSubjectInfo t) {
        String id = baseService.newInsertTree(t);
        int length = t.getFullId().split("/").length;
        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})  QfSubjectInfo t) {
        QfSubjectInfo byId = baseService.getById(t.getId());
        String id = baseService.newUpdateTree(t, byId.getName());
        int length = t.getFullId().split("/").length;
        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);
    }

    @PostMapping("/getTree")
    @ApiOperation("获取国内准则科目信息下拉树")
    @PowerLogInfo(logType = LogType.BIZ, operaionType = OperationType.QUERY, description = "获取国内准则科目信息下拉树")
    public CommonResult<String> getTree(@ApiParam(name = "model", value = "获取国内准则科目信息下拉树") @RequestBody QfSubjectInfo entity) {
        log.info("获取国内准则科目信息下拉树请求参数:{}", JSON.toJSONString(entity));
        List<QfSubjectInfo> list = baseService.getTree(entity);
        return CommonResult.success(list, 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);
    }

    @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("/associatedSubject")
    @ApiOperation("关联国际准则科目")
    public CommonResult<String> associatedSubject(@ApiParam(name="model", value="实体信息") @RequestBody QfSubjectInfo t) {
        baseService.associatedSubject(t);
        return new CommonResult<String>(true, I18nUtil.getMessage("option.success", LocaleContextHolder.getLocale()), null);
    }

    @Override
    @GetMapping("/{id}")
    @ApiOperation("根据id查询实体")
    public QfSubjectInfo getById(@ApiParam(name="id", value="实体id") @PathVariable String id) {
        return baseService.findById(id);
    }

    @PostMapping("/move")
    @ApiOperation("移动科目的上下级")
    public CommonResult<String> move(@RequestBody QfSubjectInfo entity) {
        boolean result = baseService.move(entity);
        QueryWrapper<QfSubjectInfo> queryWrapper = new QueryWrapper<QfSubjectInfo>();
        queryWrapper.eq("parent_Id_",entity.getId());
        queryWrapper.eq("is_dele_", DelStatusEnum.N.getType());
        List<QfSubjectInfo> ts = baseService.list(queryWrapper);
        ts.forEach(qfSubjectInfo -> {
            int length = qfSubjectInfo.getFullName().split("/").length;
            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) throws Exception {
        try {
            ExcelUtils<QfSubjectInfo> excelUtil = new ExcelUtils<>(QfSubjectInfo.class);
            List<QfSubjectInfo> 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) {
            throw new IllegalArgumentException(I18nUtil.getMessage("import.fail", LocaleContextHolder.getLocale()) + "," + e.getMessage());
        }
    }

    /**
     * 下载导入模板
     *
     * @param response
     * @return
     */
    @ApiOperation(value = "下载导入模板", notes = "其中层级，使用Excel")
    @GetMapping("/downModel")
    public void downTemplate(HttpServletResponse response) {
        try {
            ClassPathResource classPathResource = new ClassPathResource("model/inlandSubjectInfo.xlsx");
            FileDownloadUtil.fileDownload(response, classPathResource.getInputStream(), "国内科目准则数据导入模板·含数据.xlsx");
        } catch (Exception e) {
            response.setCharacterEncoding("utf-8");
            throw new RequiredException(I18nUtil.getMessage("resources.noexist", LocaleContextHolder.getLocale()));
        }
    }

    /**
     * 下载导入模板
     *
     * @param response
     * @return
     */
    @ApiOperation(value = "下载SQL备份")
    @GetMapping("/downSQL")
    public void downSQL(HttpServletResponse response) {
        try {
            ClassPathResource classPathResource = new ClassPathResource("sql/subjectInfoAndRelate.sql");
            FileDownloadUtil.fileDownload(response, classPathResource.getInputStream(), "国内外科目数据及关联数据备份【2023.03.08】.sql");
        } catch (Exception e) {
            response.setCharacterEncoding("utf-8");
            throw new RequiredException(I18nUtil.getMessage("resources.noexist", LocaleContextHolder.getLocale()));
        }
    }

}
