package com.casic.missiles.controller.finance;

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.BaseApprovalSubmitRequest;
import com.casic.missiles.dto.IdDTO;
import com.casic.missiles.dto.ReturnDTO;
import com.casic.missiles.dto.ReturnUtil;
import com.casic.missiles.dto.finance.AgreementApprovalListRequest;
import com.casic.missiles.dto.finance.AgreementApprovalListResponse;
import com.casic.missiles.dto.finance.AgreementInfoSaveResponse;
import com.casic.missiles.dto.finance.AgreementListRequest;
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.exception.enums.CoreExceptionEnum;
import com.casic.missiles.model.finance.FinanceAgreementInfo;
import com.casic.missiles.service.finance.IFinanceAgreementInfoService;
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 javax.validation.Valid;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 合同表 前端控制器
 * </p>
 *
 * @author wangpeng
 * @since 2023-03-31
 */
@Api(tags = "财务产值接口-合同管理")
@Slf4j
@RestController
@RequestMapping("/finance/agreement")
public class FinanceAgreementInfoController extends ExportController {
    @Autowired
    private IFinanceAgreementInfoService agreementInfoService;

    @ApiOperation("合同列表（分页）")
    @PostMapping("/listPage")
    @ResponseBody
    public ReturnDTO<PageInfoBT<FinanceAgreementInfo>> listPage(@RequestBody @Valid AgreementListRequest request, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        DictCodeUtils.validDictCode(request);
        Page<FinanceAgreementInfo> page = PageFactory.defaultPage();
        return ReturnUtil.success(super.packForBT(agreementInfoService.listPage(page, request)));
    }

    @ApiOperation("合同列表")
    @PostMapping("/list")
    @ResponseBody
    public ReturnDTO<List<FinanceAgreementInfo>> list(@RequestBody @Valid AgreementListRequest request, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        DictCodeUtils.validDictCode(request);
        return ReturnUtil.success(agreementInfoService.list(request));
    }

    @ApiOperation("合同列表导出")
    @PostMapping("/listExport")
    @ResponseBody
    public void export(@RequestBody @Valid AgreementListRequest request, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        DictCodeUtils.validDictCode(request);
        List<FinanceAgreementInfo> list;
        if (!CollectionUtils.isEmpty(request.getIds())) {
            list = agreementInfoService.listByIds(request.getIds());
            for (FinanceAgreementInfo record : list) {
                DictCodeUtils.convertDictCodeToName(record);
            }
        } else {
            list = agreementInfoService.list(request);
        }
        super.exportExcel(FinanceAgreementInfo.class, list, ExportEnum.AGREEMENT_INFO_EXPORT.getSheetName());
    }

    @ApiOperation("合同审批列表（分页）")
    @PostMapping("/approval/listPage")
    public ReturnDTO<PageInfoBT<AgreementApprovalListResponse>> approvalListPage(@RequestBody @Valid AgreementApprovalListRequest request, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        DictCodeUtils.validDictCode(request);
        Page<AgreementApprovalListResponse> page = PageFactory.defaultPage();
        List<AgreementApprovalListResponse> responseList = agreementInfoService.agreementApprovalListPage(request, page);
        page.setRecords(responseList);
        return ReturnUtil.success(super.packForBT(page));
    }

    @ApiOperation("合同审批保存（保存至草稿箱）")
    @PostMapping("/save")
    @ResponseBody
    public ReturnDTO<AgreementInfoSaveResponse> save(@RequestBody @Valid FinanceAgreementInfo agreementInfo, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        DictCodeUtils.validDictCode(agreementInfo);
        return agreementInfoService.saveAgreementInfo(agreementInfo);
    }

    @ApiOperation("草稿箱合同编辑")
    @PostMapping("/draftUpdate")
    @ResponseBody
    public ReturnDTO draftUpdate(@RequestBody @Valid FinanceAgreementInfo agreementInfo, BindingResult bindingResult) throws Exception {
        Assert.isFalse(Objects.isNull(agreementInfo.getId()), () -> {
            throw new BusinessException(BusinessExceptionEnum.ID_NULL);
        });
        if (bindingResult.hasErrors()) {
            throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        DictCodeUtils.validDictCode(agreementInfo);
        return agreementInfoService.agreementDraftUpdate(agreementInfo);
    }

    @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 agreementInfoService.submitAgreement(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 agreementInfoService.agreementDelete(idDTO.getId());
    }

    @ApiOperation("合同详情")
    @PostMapping("/detail")
    @ResponseBody
    public ReturnDTO<FinanceAgreementInfo> supplierDetail(@RequestBody @Valid IdDTO idDTO) throws Exception {
        Assert.isFalse(Objects.isNull(idDTO.getId()), () -> {
            throw new BusinessException(BusinessExceptionEnum.ID_NULL);
        });
        return agreementInfoService.agreementDetail(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 agreementInfoService.agreementApprovalDelete(request);
    }

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