package com.artfess.examine.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.LogType;
import com.artfess.base.enums.OperationType;
import com.artfess.base.enums.ResponseErrorEnums;
import com.artfess.base.exception.BaseException;
import com.artfess.base.exception.RequiredException;
import com.artfess.base.model.CommonResult;
import com.artfess.base.query.PageBean;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryFilter;
import com.artfess.base.valid.AddGroup;
import com.artfess.base.valid.UpdateGroup;
import com.artfess.examine.manager.ExamEquipmentSysManager;
import com.artfess.examine.model.ExamEquipmentSys;
import com.artfess.examine.model.ExamSubjectInfo;
import com.artfess.examine.model.ExamSubjectType;
import com.artfess.examine.vo.PositionVo;
import com.artfess.poi.util.ExcelUtils;
import com.artfess.poi.util.FileDownloadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * 装备系统表 前端控制器
 *
 * @company 阿特菲斯信息技术有限公司
 * @author min.wu
 * @since 2022-10-19
 */
@Slf4j
@RestController
@Api(tags = "基础数据-装备系统")
@RequestMapping("/exam/equipment/sys/")
@ApiGroup(group = {ApiGroupConsts.GROUP_BIZ})
public class ExamEquipmentSysController extends BaseController<ExamEquipmentSysManager, ExamEquipmentSys> {

    @PostMapping("/getTree")
    @ApiOperation("获取人员类别专业装备下拉树")
    @PowerLogInfo(logType = LogType.BIZ, operaionType = OperationType.QUERY, description = "获取人员类别专业装备下拉树")
    public CommonResult<String> getTree(@ApiParam(name = "model", value = "获取人员类别专业装备下拉树") @RequestBody ExamEquipmentSys entity) {
        log.info("获取装备系统下拉树请求参数:{}", JSON.toJSONString(entity));
        List<ExamSubjectType> list = baseService.getTree(entity);
        return CommonResult.success(list, null);
    }

    @Override
    @PostMapping("/")
    @ApiOperation("添加实体的接口")
    public CommonResult<String> create(@ApiParam(name="model", value="实体信息") @RequestBody @Validated({AddGroup.class}) ExamEquipmentSys t) {
        boolean result = baseService.createInfo(t);
        if(!result) {
            return new CommonResult<>(ResponseErrorEnums.FAIL_OPTION, null);
        }
        return new CommonResult<>();
    }

    @Override
    @PutMapping("/")
    @ApiOperation("更新实体")
    public CommonResult<String> updateById(@ApiParam(name="model", value="实体信息") @RequestBody @Validated({UpdateGroup.class}) ExamEquipmentSys t) {
        boolean result = baseService.updateInfo(t);
        if(!result) {
            return new CommonResult<>(ResponseErrorEnums.FAIL_OPTION, "更新实体失败");
        }
        return new CommonResult<>();
    }

    @GetMapping("/findById/{id}")
    @ApiOperation("根据id获取装备信息")
    public ExamEquipmentSys findById(@ApiParam(name="id", value="实体id") @PathVariable String id) {
        return baseService.findById(id);
    }



    @GetMapping("/findByBindPos/{ids}")
    @ApiOperation("根据专业装备id获取已绑定的组织岗位,可以是多个专业装备id")
    public List<PositionVo> findByBindPos(@ApiParam(name="ids", value="实体id") @PathVariable String ids) {
        return baseService.findByBindPos(ids);
    }

    @ApiOperation(value = "导入")
    @PostMapping("/importExcel")
    public CommonResult<String> importExcel(@RequestParam("file") MultipartFile file) {
        try {
            ExcelUtils<ExamEquipmentSys> excelUtil = new ExcelUtils<>(ExamEquipmentSys.class);
            List<ExamEquipmentSys> list = excelUtil.importExcel(null, file.getInputStream());
            boolean result = baseService.importExcel(list);
            if(!result) {
                throw new IllegalArgumentException("导入失败");
            }
            return new CommonResult<>();
        } catch (Exception e) {
            throw new IllegalArgumentException("导入失败,"+ e.getMessage());
        }
    }

    @ApiOperation(value = "导出")
    @PostMapping("/export")
    public void export(HttpServletResponse response, HttpServletRequest request, @ApiParam(name="queryFilter", value="分页查询信息") @RequestBody QueryFilter<ExamEquipmentSys> queryFilter) throws Exception {
        PageList<ExamEquipmentSys> page = baseService.query(queryFilter);
        ExcelUtils<ExamEquipmentSys> util = new ExcelUtils<ExamEquipmentSys>(ExamEquipmentSys.class);
        util.exportExcel(response, request, page.getRows(), "导出专业装备");
    }

    /**
     * 下载导入模板
     *
     * @param response
     * @return
     */
    @ApiOperation(value = "下载导入模板")
    @GetMapping("/downModel")
    public void downTemplate(HttpServletResponse response) {
        try {
            ClassPathResource classPathResource = new ClassPathResource("model/sys.xlsx");
            FileDownloadUtil.fileDownload(response, classPathResource.getInputStream(), "专业装备模板.xlsx");
        } catch (Exception e) {
            response.setCharacterEncoding("utf-8");
            throw new RequiredException("你所下载的资源不存在");
        }
    }

    @Override
    @DeleteMapping("/")
    @ApiOperation("根据id集合批量删除")
    public CommonResult<String> deleteByIds(@ApiParam(name="ids", value="实体集合") @RequestParam String...ids) {
        List<String> idList = Arrays.asList(ids);
        List<ExamSubjectInfo> list = this.baseService.getSubjectList(idList);
        if(!CollectionUtils.isEmpty(list)) {
            throw new BaseException("该装备下还有课目，请先删除课目信息");
        }

        boolean result = baseService.removeByIds(idList);
        if(!result) {
            return new CommonResult<>(ResponseErrorEnums.FAIL_OPTION, "删除实体失败");
        }
        return new CommonResult<>();
    }


    @Override
    @PostMapping(value="/query", produces={"application/json; charset=utf-8" })
    @ApiOperation("分页查询结果")
    public PageList<ExamEquipmentSys> query(@ApiParam(name="queryFilter", value="分页查询信息") @RequestBody QueryFilter<ExamEquipmentSys> queryFilter) {
        PageBean pageBean = queryFilter.getPageBean();
        if(pageBean == null){
            pageBean = new PageBean(PageBean.NO_PAGE,PageBean.WITHOUT_PAGE,true);
            queryFilter.setPageBean(pageBean);
        }
        return baseService.query(queryFilter);
    }

}
