package com.qmth.sop.server.api;

import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.sop.business.bean.params.UserArchivesParam;
import com.qmth.sop.business.bean.query.UserArchivesQuery;
import com.qmth.sop.business.bean.result.UserArchivesResult;
import com.qmth.sop.business.bean.result.UserArchivesSubTotalResult;
import com.qmth.sop.business.entity.SysUser;
import com.qmth.sop.business.entity.TBTask;
import com.qmth.sop.business.service.SequenceService;
import com.qmth.sop.business.service.TBTaskService;
import com.qmth.sop.business.service.TBUserArchivesService;
import com.qmth.sop.business.templete.execute.AsyncUserArchivesExportService;
import com.qmth.sop.business.templete.execute.AsyncUserArchivesImportService;
import com.qmth.sop.common.annotation.OperationLog;
import com.qmth.sop.common.contant.SystemConstant;
import com.qmth.sop.common.enums.*;
import com.qmth.sop.common.util.Result;
import com.qmth.sop.common.util.ResultUtil;
import com.qmth.sop.common.util.ServletUtil;
import io.swagger.annotations.*;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 人员档案表 前端控制器
 * </p>
 *
 * @author wangliang
 * @since 2023-07-17
 */
@Api(tags = "人员档案Controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + SystemConstant.PREFIX_URL_USER_ARCHIVES)
public class TBUserArchivesController {
    @Resource
    private TBTaskService tbTaskService;

    @Resource
    private AsyncUserArchivesImportService asyncUserArchivesImportService;

    @Resource
    private AsyncUserArchivesExportService asyncUserArchivesExportService;

    @Resource
    private TBUserArchivesService tbUserArchivesService;

    @Resource
    private SequenceService sequenceService;


    @ApiOperation(value = "人员档案管理-分页查询")
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = UserArchivesResult.class)})
    public Result findUserArchivesPage(@ApiParam(value = "城市") @RequestParam(required = false) String city,
                                       @ApiParam(value = "供应商") @RequestParam(required = false) String supplierId,
                                       @ApiParam(value = "档案名称") @RequestParam(required = false) String archivesName,
                                       @ApiParam(value = "认证角色") @RequestParam(required = false) RoleTypeEnum roleType,
                                       @ApiParam(value = "认证状态") @RequestParam(required = false) Boolean authenticationStatus,
                                       @ApiParam(value = "入档时间-开始") @RequestParam(required = false) Long archivesTimeStart,
                                       @ApiParam(value = "入档时间-截止") @RequestParam(required = false) Long archivesTimeEnd,
                                       @ApiParam(value = "剩余有效天数") @RequestParam(required = false) Integer remainValidDay,
                                       @ApiParam(value = "分页页码", required = true) @RequestParam @Min(SystemConstant.PAGE_NUMBER_MIN) Integer pageNumber,
                                       @ApiParam(value = "分页数", required = true) @RequestParam @Min(SystemConstant.PAGE_SIZE_MIN) @Max(SystemConstant.PAGE_SIZE_MAX) Integer pageSize) throws Exception {

        return ResultUtil.ok(tbUserArchivesService.findUserArchivesPage(city, SystemConstant.convertIdToLong(supplierId), archivesName,
                roleType, authenticationStatus, archivesTimeStart, archivesTimeEnd, remainValidDay, pageNumber, pageSize));
    }

    @ApiOperation(value = "人员档案管理-小计")
    @RequestMapping(value = "/sub_total", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = UserArchivesSubTotalResult.class)})
    public Result findUserArchivesSubTotal(@ApiParam(value = "城市") @RequestParam(required = false) String city,
                                           @ApiParam(value = "供应商") @RequestParam(required = false) String supplierId,
                                           @ApiParam(value = "档案名称") @RequestParam(required = false) String archivesName,
                                           @ApiParam(value = "认证角色") @RequestParam(required = false) RoleTypeEnum roleType,
                                           @ApiParam(value = "认证状态") @RequestParam(required = false) Boolean authenticationStatus,
                                           @ApiParam(value = "入档时间-开始") @RequestParam(required = false) Long archivesTimeStart,
                                           @ApiParam(value = "入档时间-截止") @RequestParam(required = false) Long archivesTimeEnd,
                                           @ApiParam(value = "剩余有效天数") @RequestParam(required = false) Integer remainValidDay) {
        return ResultUtil.ok(tbUserArchivesService.findUserArchivesSubTotal(city, SystemConstant.convertIdToLong(supplierId), archivesName,
                roleType, authenticationStatus, archivesTimeStart, archivesTimeEnd, remainValidDay));
    }

    @ApiOperation(value = "人员档案管理-生成编号")
    @RequestMapping(value = "/create_code", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "查询成功", response = Result.class)})
    public Result createUserArchivesCode() throws InterruptedException {
        return ResultUtil.ok(sequenceService.createSerialNo(SequenceEnum.USER_ARCHIVES_CODE), ExceptionResultEnum.SUCCESS.getMessage());
    }

    @ApiOperation(value = "人员档案管理-编辑")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "更新成功", response = Result.class)})
    @OperationLog(logType = LogTypeEnum.EDIT)
    public Result editUserArchives(@Valid @RequestBody UserArchivesParam userArchivesParam, BindingResult bindingResult) throws InterruptedException {
        if (bindingResult.hasErrors()) {
            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        return ResultUtil.ok(tbUserArchivesService.editUserArchives(userArchivesParam, requestUser));
    }

    @ApiOperation(value = "人员档案导入")
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = Object.class)})
    @OperationLog(logType = LogTypeEnum.IMPORT)
    public Result importUserArchives(@ApiParam(value = "上传文件", required = true) @RequestParam MultipartFile file) throws Exception {
        Map<String, Object> map = tbTaskService.saveTask(file, TaskTypeEnum.USER_ARCHIVES_IMPORT);
        asyncUserArchivesImportService.importTask(map);
        TBTask tbTask = (TBTask) map.get(SystemConstant.TASK);
        return ResultUtil.ok(tbTask.getId());
    }

    @ApiOperation(value = "人员档案导出")
    @RequestMapping(value = "/export", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "返回信息", response = Object.class)})
    @OperationLog(logType = LogTypeEnum.EXPORT)
    public Result exportUserArchives(@ApiParam(value = "城市") @RequestParam(required = false) String city,
                                     @ApiParam(value = "供应商") @RequestParam(required = false) String supplierId,
                                     @ApiParam(value = "档案名") @RequestParam(required = false) String archivesName,
                                     @ApiParam(value = "角色类型") @RequestParam(required = false) RoleTypeEnum roleType,
                                     @ApiParam(value = "认证状态") @RequestParam(required = false) Boolean authenticationStatus,
                                     @ApiParam(value = "入档时间 - 起始") @RequestParam(required = false) Long archivesTimeStart,
                                     @ApiParam(value = "入档时间 - 截止") @RequestParam(required = false) Long archivesTimeEnd,
                                     @ApiParam(value = "有效期") @RequestParam(required = false) Integer remainValidDay) throws Exception {
        Map<String, Object> map = tbTaskService.saveTask(TaskTypeEnum.USER_ARCHIVES_EXPORT);
        UserArchivesQuery query = new UserArchivesQuery();
        query.setCity(city);
        query.setSupplierId(SystemConstant.convertIdToLong(supplierId));
        query.setArchivesName(archivesName);
        query.setRoleType(roleType);
        query.setAuthenticationStatus(authenticationStatus);
        query.setArchivesTimeStart(archivesTimeStart);
        query.setArchivesTimeEnd(archivesTimeEnd);
        query.setRemainValidDay(remainValidDay);
        map.put(SystemConstant.QUERY, query);
        asyncUserArchivesExportService.exportTask(map);
        TBTask tbTask = (TBTask) map.get(SystemConstant.TASK);
        return ResultUtil.ok(tbTask.getId());
    }

    @ApiOperation(value = "人员档案管理-作废")
    @RequestMapping(value = "/cancel", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "作废成功", response = Result.class)})
    @OperationLog(logType = LogTypeEnum.UPDATE)
    public Result cancelUserArchives(@ApiParam(value = "人员档案id集合", required = true) @RequestParam List<String> idList) {
        if (CollectionUtils.isNotEmpty(idList)) {
            List<Long> archivesIdList = idList.stream().map(SystemConstant::convertIdToLong).collect(Collectors.toList());
            tbUserArchivesService.cancelUserArchives(archivesIdList);
        }
        return ResultUtil.ok();
    }
}