package com.jwipc.contract.controller.pc;

import cn.hutool.core.collection.CollUtil;
import com.jwipc.contract.dto.ContractPaymentApplyDTO;
import com.jwipc.contract.dto.ContractPaymentApplySaveDTO;
import com.jwipc.contract.dto.CreateCpaDetailDto;
import com.jwipc.contract.logic.ContractPaymentApplyLogic;
import com.jwipc.contract.model.query.ContractPaymentApplyHeadQuery;
import com.jwipc.exception.DaoException;
import com.jwipc.log.annotation.AuditLogInter;
import com.jwipc.page.PageView;
import com.jwipc.security.LoginUtil;
import com.jwipc.sys.dto.RoleListDTO;
import com.jwipc.sys.logic.RoleLogic;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static com.jwipc.contract.constant.ModuleConst.MODULE_ROOT;

/**
 * <p>
 * 资产合同付款申请主表 前端控制器
 * </p>
 *
 * @author 邓京术
 * @since 2025-12-25
 */
@RestController
@RequestMapping(MODULE_ROOT + "/payment/rest")
@RequiredArgsConstructor
public class ContractPaymentApplyRestController {

    private final ContractPaymentApplyLogic contractPaymentApplyLogic;
    private final RoleLogic roleLogic;

    /**
     * 查询MRO合同申请首页列表数据
     *
     * @param query 查询条件
     * @return 结果
     */
    @AuditLogInter(value = "首页查询列表", module = "MRO合同付款申请")
    @RequestMapping("/list")
    public PageView indexPageTableData(ContractPaymentApplyHeadQuery query) {
        if (LoginUtil.isSupplier()){
            query.setSupplierCode(LoginUtil.getAccount());
        }else{
            boolean flag = true;
            List<RoleListDTO> userRoles = roleLogic.getUserRoles(LoginUtil.getUserId());
            if(CollUtil.isNotEmpty(userRoles)){
                for (RoleListDTO userRole : userRoles) {
                    if("query_all_data".equals(userRole.getRolekey())){
                        flag = false;
                    }
                }
            }
            if(flag){
                query.setUserId(LoginUtil.getUserId());
            }
        }
        return contractPaymentApplyLogic.selectDataByQuery(query);
    }

//    /**
//     * 查询对账付款申请发票数据
//     *
//     * @param query 查询条件
//     * @return 结果
//     */
//    @PostMapping("/query/cod/apply/invoice")
//    public ResponseEntity queryCodApplyInvoice(PaymentApplyItemQuery query) {
//        List<CreatePcaDetailDto> pcaDetailList = paymentCodApplyLogic.readCodPaymentInvoiceData(query);
//        return ResponseEntity.ok(pcaDetailList);
//    }

    /**
     * 查询MRO合同付款款申请数据明细
     *
     * @param id 查询条件
     * @return 结果
     */
    @PostMapping("/query/appId")
    public ResponseEntity queryCodApplyInvoiceById(Long id,Integer totalFlag,String businessType) {
        List<CreateCpaDetailDto> pcaDetailList = contractPaymentApplyLogic.queryCodApplyInvoiceById(id,totalFlag,businessType);
        return ResponseEntity.ok(pcaDetailList);
    }

    /**
     * 查询资产合同付款申请发票数据
     *
     * @param poItemNo 合同付款阶段ID
     * @return 结果
     */
    @PostMapping("/query/contractPaymentApplyed")
    public ResponseEntity queryCodApplyInvoiceByAccountStatementNo(Long poItemNo) {
        List<CreateCpaDetailDto> pcaDetailList = contractPaymentApplyLogic.queryInvoiceByContractDetailId(poItemNo);
        return ResponseEntity.ok(pcaDetailList);
    }



    /**
     * 数据保存
     * data/saveOrUpdate
     *
     * @param data 待保存的数据
     * @return 结果
     */
    @PostMapping("/data/saveOrUpdate")
    public ResponseEntity dataSave(@RequestBody ContractPaymentApplySaveDTO data) throws Exception {
        contractPaymentApplyLogic.saveOrUpdate(data);
        return ResponseEntity.ok(true);
    }

    @PostMapping("/data/saveOrUpdateCheck")
    public ResponseEntity dataSaveCheck(@RequestBody ContractPaymentApplySaveDTO data) throws Exception {
        return ResponseEntity.ok(contractPaymentApplyLogic.saveOrUpdateCheck(data));
    }

    @PostMapping("/data/importAttachement")
    public ResponseEntity importAttachement(@RequestBody List<Map<String,String>> dataList) throws Exception {
        contractPaymentApplyLogic.importAttachement(dataList);
        return ResponseEntity.ok(true);
    }

    /**
     * 删除MRO付款申请单
     *
     * @param applyIds 申请ID
     * @return 结果
     */
    @PostMapping("/data/del")
    public ResponseEntity dataDel(String applyIds) {
        contractPaymentApplyLogic.deleteCodApply(applyIds);
        return ResponseEntity.ok(true);
    }
//
//    /**
//     * 提交OA
//     * @param id 付款id
//     */
//    @PostMapping("/clear/oaNumber")
//    public ResponseEntity clearOaNumber(String ids){
//        if(StringUtils.isEmpty(ids)){
//            return ResponseEntity.ok(false);
//        }
//        paymentCodApplyLogic.clearOaNumber(ids);
//
//        return ResponseEntity.ok(true);
//    }

    /**
     * 提交共享审批
     * @param id 付款id
     */
    @PostMapping("/push/oa")
    public ResponseEntity pushOa(String ids){
        contractPaymentApplyLogic.pushOpen(ids);
        return ResponseEntity.ok(true);
    }

    /**
     * 推送影像系统
     *
     * @param pushIds 推送ID
     */
    @PostMapping("/pushImage")
    public ResponseEntity<Boolean> pushImage(String pushIds) {
        List<Long> idList = Arrays.stream(StringUtils.split(pushIds, ",")).map(Long::valueOf).toList();
        for (Long id : idList) {
            ContractPaymentApplyDTO contractPaymentApplyDTO = contractPaymentApplyLogic.getById(id);
            if (StringUtils.isNotEmpty(contractPaymentApplyDTO.getImgCode())&&StringUtils.isNotEmpty(contractPaymentApplyDTO.getPoImgCode())
                    &&contractPaymentApplyDTO.getImgTime()!=null&&contractPaymentApplyDTO.getPoImgTime()!=null
            ){
                throw new DaoException("该付款单:"+contractPaymentApplyDTO.getApApplyNo()+"已影像化，不可重复操作");
            }
        }
        contractPaymentApplyLogic.pushImage(pushIds);
        contractPaymentApplyLogic.toPoImg(pushIds);
        return ResponseEntity.ok(true);
    }

    @PostMapping("/deleteImage")
    public ResponseEntity<Boolean> deleteImage(String deleteIds) {
        List<Long> idList = Arrays.stream(StringUtils.split(deleteIds, ",")).map(Long::valueOf).toList();
        for (Long id : idList) {
            ContractPaymentApplyDTO contractPaymentApplyDTO = contractPaymentApplyLogic.getById(id);
            if (contractPaymentApplyDTO.getImgTime() == null && contractPaymentApplyDTO.getPoImgTime() == null) {
                throw new DaoException("该付款单:"+contractPaymentApplyDTO.getApApplyNo()+"未影像化，不可删除");
            }
        }
        contractPaymentApplyLogic.deleteImage(deleteIds);
        contractPaymentApplyLogic.deletePoImg(deleteIds);
        return ResponseEntity.ok(true);
    }
}
