package com.casic.missiles.controller.business;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.casic.missiles.core.base.controller.ExportController;
import com.casic.missiles.core.page.PageFactory;
import com.casic.missiles.core.page.PageInfoBT;
import com.casic.missiles.dto.*;
import com.casic.missiles.dto.business.outsource.OutsourcerApprovalListRequest;
import com.casic.missiles.dto.business.outsource.OutsourcerApprovalListResponse;
import com.casic.missiles.dto.business.outsource.OutsourcerListRequest;
import com.casic.missiles.dto.business.outsource.OutsourcerSaveResponse;
import com.casic.missiles.dto.flowable.ApprovalDeleteRequest;
import com.casic.missiles.enums.BusinessExceptionEnum;
import com.casic.missiles.enums.ExportEnum;
import com.casic.missiles.exception.BusinessException;
import com.casic.missiles.model.business.BusinessOutsourcerInfo;
import com.casic.missiles.model.business.BusinessOutsourcerInfoImport;
import com.casic.missiles.model.equipment.EquipmentFixedAssets;
import com.casic.missiles.model.equipment.EquipmentFixedAssetsImport;
import com.casic.missiles.model.exception.enums.CoreExceptionEnum;
import com.casic.missiles.service.business.IBusinessOutsourcerInfoService;
import com.casic.missiles.utils.ConvertUtils;
import com.casic.missiles.utils.DictCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 分包方 前端控制器
 * </p>
 *
 * @author wangpeng
 * @since 2023-03-25
 */
@Api(tags = "分包管理接口-分包方档案&分包方资格审批")
@Slf4j
@RestController
@RequestMapping("/business/outsourcer")
public class BusinessOutsourcerController extends ExportController {
    @Autowired
    private IBusinessOutsourcerInfoService outsourcerInfoService;

    @ApiOperation("分包方档案列表&详情（分页）")
    @PostMapping("/listPage")
    @ResponseBody
    public ReturnDTO<PageInfoBT<BusinessOutsourcerInfo>> outsourcerListPage(@RequestBody @Valid OutsourcerListRequest request, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        Page<BusinessOutsourcerInfo> page = PageFactory.defaultPage();
        return ReturnUtil.success(super.packForBT(outsourcerInfoService.listPage(page, request)));
    }

    @ApiOperation("分包方档案列表&详情")
    @PostMapping("/list")
    @ResponseBody
    public ReturnDTO<List<BusinessOutsourcerInfo>> outsourcerList(@RequestBody @Valid OutsourcerListRequest request, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        return ReturnUtil.success(outsourcerInfoService.list(request));
    }

    @ApiOperation("分包方档案导出")
    @PostMapping("/listExport")
    @ResponseBody
    public void export(@RequestBody @Valid OutsourcerListRequest request, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        List<BusinessOutsourcerInfo> list;
        if (!CollectionUtils.isEmpty(request.getIds())) {
            list = outsourcerInfoService.listByIds(request.getIds());
        } else {
            list = outsourcerInfoService.list(request);
        }
        for (BusinessOutsourcerInfo record : list) {
            DictCodeUtils.convertDictCodeToName(record);
        }
        super.exportExcel(BusinessOutsourcerInfo.class, list, ExportEnum.OUTSOURCER_EXPORT.getSheetName());
    }

    @ApiOperation("分包方资格审批列表（分页）")
    @PostMapping("/approval/listPage")
    public ReturnDTO<PageInfoBT<OutsourcerApprovalListResponse>> outsourcerApprovalListPage(@RequestBody @Valid OutsourcerApprovalListRequest request, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        DictCodeUtils.validDictCode(request);
        Page<OutsourcerApprovalListResponse> page = PageFactory.defaultPage();
        List<OutsourcerApprovalListResponse> responseList = outsourcerInfoService.outsourcerApprovalListPage(request, page);
        page.setRecords(responseList);
        return ReturnUtil.success(super.packForBT(page));
    }

    /**
     * 批量导入分包方档案
     */
    @ApiOperation("批量导入分包方档案")
    @PostMapping(value = "/import", headers = "content-type=multipart/form-data")
    @ResponseBody
    public ReturnDTO importBatch(@RequestParam MultipartFile[] multipartFile) throws Exception {
        List<BusinessOutsourcerInfoImport> sourceList = new ArrayList();
        for (MultipartFile file : multipartFile) {
            List<BusinessOutsourcerInfoImport> list =  super.importExcel(BusinessOutsourcerInfoImport.class, file, null, null);
            sourceList.addAll(list);
        }
        List<BusinessOutsourcerInfo> targetList = ConvertUtils.sourceToTarget(sourceList, BusinessOutsourcerInfo.class);
        return outsourcerInfoService.addBusinessOutsourcerList(targetList);
    }

    @ApiOperation("分包方资格审批保存（保存至草稿箱）")
    @PostMapping("/save")
    @ResponseBody
    public ReturnDTO<OutsourcerSaveResponse> save(@RequestBody @Valid BusinessOutsourcerInfo outsourcerInfo, BindingResult bindingResult) throws Exception {
        if(bindingResult.hasErrors()){
            throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        DictCodeUtils.validDictCode(outsourcerInfo);
        return outsourcerInfoService.saveOutsourcer(outsourcerInfo);
    }

    @ApiOperation("草稿箱分包方资格编辑")
    @PostMapping("/draftUpdate")
    @ResponseBody
    public ReturnDTO draftUpdate(@RequestBody @Valid BusinessOutsourcerInfo outsourcerInfo, BindingResult bindingResult) throws Exception {
        Assert.isFalse(Objects.isNull(outsourcerInfo.getId()), () -> {
            throw new BusinessException(BusinessExceptionEnum.ID_NULL);
        });
        if(bindingResult.hasErrors()){
            throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        DictCodeUtils.validDictCode(outsourcerInfo);
        return outsourcerInfoService.draftUpdate(outsourcerInfo);
    }

    @ApiOperation("分包方资格提交（未调用过保存接口保存至草稿箱需先调用保存接口，再调用该接口）")
    @PostMapping("/submit")
    @ResponseBody
    public ReturnDTO submit(@RequestBody @Valid BaseApprovalSubmitRequest request, BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
            throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        return outsourcerInfoService.submitOutsourcer(request);
    }

    @ApiOperation("分包方档案删除（草稿删除也调用该接口）")
    @PostMapping("/delete")
    @ResponseBody
    public ReturnDTO delete(@RequestBody @Valid IdDTO idDTO) {
        Assert.isFalse(Objects.isNull(idDTO.getId()), () -> {
            throw new BusinessException(BusinessExceptionEnum.ID_NULL);
        });
        return outsourcerInfoService.deleteOutsourcer(idDTO.getId());
    }

    @ApiOperation("分包方档案批量删除")
    @PostMapping("/batchDelete")
    @ResponseBody
    public ReturnDTO batchDelete(@RequestBody @Valid IdsDTO idsDTO) {
        Assert.isFalse(CollectionUtils.isEmpty(idsDTO.getIds()), () -> {
            throw new BusinessException(BusinessExceptionEnum.ID_NULL);
        });
        return outsourcerInfoService.deleteBatchOutsourcer(idsDTO.getIds());
    }

    @ApiOperation("分包方档案详情")
    @PostMapping("/detail")
    @ResponseBody
    public ReturnDTO<BusinessOutsourcerInfo> supplierDetail(@RequestBody @Valid IdDTO idDTO) throws Exception {
        Assert.isFalse(Objects.isNull(idDTO.getId()), () -> {
            throw new BusinessException(BusinessExceptionEnum.ID_NULL);
        });
        return outsourcerInfoService.outsourcerDetail(idDTO.getId());
    }

    @ApiOperation("分包方资格审批操作-删除")
    @PostMapping("/approval/operate/delete")
    @ResponseBody
    public ReturnDTO delete(@RequestBody @Valid ApprovalDeleteRequest request, BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
            throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        return outsourcerInfoService.approvalDelete(request);
    }

    @ApiOperation("未通过分包方资格编辑（驳回后的分包方重新编辑，仅未通过列表中的编辑按钮可调用）")
    @PostMapping("/failUpdate")
    @ResponseBody
    public ReturnDTO failUpdate(@RequestBody @Valid BusinessOutsourcerInfo outsourcerInfo, BindingResult bindingResult) {
        Assert.isFalse(Objects.isNull(outsourcerInfo.getId()), () -> {
            throw new BusinessException(BusinessExceptionEnum.ID_NULL);
        });
        if (bindingResult.hasErrors()) {
            throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        return outsourcerInfoService.failUpdate(outsourcerInfo);
    }
}
