package com.jwipc.finance.controller.rest;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.jwipc.exception.DaoException;
import com.jwipc.finance.dto.InvoicedApplyDTO;
import com.jwipc.finance.dto.PaymentAdvanceApplyListDTO;
import com.jwipc.finance.dto.PaymentAdvanceApplySaveDto;
import com.jwipc.finance.dto.PaymentCodApplySaveDTO;
import com.jwipc.finance.entity.InvoicedApplyPa;
import com.jwipc.finance.entity.PaymentAdvanceApply;
import com.jwipc.finance.entity.PaymentAdvanceApplyDetail;
import com.jwipc.finance.logic.PaymentAdvanceApplyLogic;
import com.jwipc.finance.model.query.PaymentApplyHeadQuery;
import com.jwipc.finance.service.IInvoicedApplyPaService;
import com.jwipc.finance.service.IInvoicedApplyService;
import com.jwipc.finance.service.IPaymentAdvanceApplyService;
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.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

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

/**
 * <p>
 *预付款申请主表
 * </p>
 *
 * @author wt
 * @version 1.0
 * @since 2024/3/8
 */
@RestController
@RequestMapping(MODULE_ROOT + "/paymentAdvance/apply/rest")
@RequiredArgsConstructor
public class PaymentAdvanceApplyRestController {

    private final PaymentAdvanceApplyLogic paymentAdvanceApplyLogic;
    private final IInvoicedApplyPaService invoicedApplyPaService;
    private final IPaymentAdvanceApplyService paymentAdvanceApplyService;


    private final RoleLogic roleLogic;
    /**
     * 查询预付款申请首页列表数据
     *
     * @param query 查询条件
     * @return 结果
     */
    @AuditLogInter(value = "首页查询列表", module = "预付款申请")
    @RequestMapping("/list")
    public PageView indexPageTableData( PaymentApplyHeadQuery query) {
        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());
        }
        PageView pageView = paymentAdvanceApplyLogic.selectListByPage(query);
        return pageView;
    }

    /**
     * 数据保存
     * fin/payment/advance/apply/rest/dave/save
     *
     * @param data 待保存的数据
     * @return 结果
     */
    @PostMapping("/dave/save")
    public ResponseEntity dataSave(@RequestBody PaymentAdvanceApplySaveDto data) throws Exception {
        if (ObjectUtil.isNull(data)) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(this.returnMsg("参数异常, 请重新操作"));
        }
        paymentAdvanceApplyLogic.dataSave(data);

        return ResponseEntity.ok().build();
    }

    @PostMapping("/dave/saveCheck")
    public ResponseEntity saveCheck(@RequestBody PaymentAdvanceApplySaveDto data){
        return ResponseEntity.ok(paymentAdvanceApplyLogic.saveCheck(data));
    }

    /**
     * 删除预付款申请单
     *
     * @param applyIds 申请ID
     * @return 结果
     */
    @PostMapping("/data/del")
    public ResponseEntity dataDel(String applyIds) {
        if (StringUtils.isEmpty(applyIds)) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(this.returnMsg("参数异常, 请重新操作"));
        }

        try {
            final List<Long> applyIdList = JSONArray.parseArray(applyIds, Long.class);
            paymentAdvanceApplyLogic.delAdvanceApply(applyIdList);
        } catch (Exception e) {
            e.printStackTrace();

            String message = StringUtils.isNotEmpty(e.getMessage()) ? e.getMessage() : "系统异常: 空指针, 请联系管理";
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(this.returnMsg(message));
        }

        return ResponseEntity.ok("数据保存成功");
    }

    @PostMapping("/approval/pass")
    public ResponseEntity approvalPass(String ids) throws Exception {
        if(StringUtils.isEmpty(ids)){
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(this.returnMsg("id不能为空"));
        }
        paymentAdvanceApplyLogic.approvalPass(ids);

        return ResponseEntity.ok("ok");
    }

    /**
     * 根据采购申请明细IDS获取明细信息
     * @return 结果
     */
    @PostMapping("/find/paa/findPaaDetailByInvoiceApplyId")
    public ResponseEntity findPaaDetailByInvoiceApplyId(Long invoiceApplyId) {
        List<InvoicedApplyPa> paaDetailList = invoicedApplyPaService.list(Wrappers.lambdaQuery(InvoicedApplyPa.class).eq(InvoicedApplyPa::getInvoiceApplyId,invoiceApplyId));
        Set<String> applyNos = paaDetailList.stream().map(InvoicedApplyPa::getApplyNo).collect(Collectors.toSet());
        if(CollectionUtils.isNotEmpty(applyNos)){
            List<PaymentAdvanceApply>  apply = paymentAdvanceApplyService.list(new LambdaQueryWrapper<PaymentAdvanceApply>()
                    .in(PaymentAdvanceApply::getApApplyNo, applyNos));
            if(CollectionUtils.isNotEmpty(apply)){
                Map<String, List<PaymentAdvanceApply>> map = apply.stream().collect(Collectors.groupingBy(PaymentAdvanceApply::getApApplyNo));
                paaDetailList.stream().forEach(s ->{
                            List<PaymentAdvanceApply> invoicedApplyList= map.get(s.getApplyNo());
                            s.setPaymentStatus(invoicedApplyList.get(0).getStatus());
                        }
                );
            }
        }
        return ResponseEntity.ok(paaDetailList);
    }
    //根据采购订单号 或者 采购组或供应商编码+公司编码+币种查询预付款列表（需要是付款完成的）当数据类型是退款时，排除转单标识为X的预付款
    @PostMapping("/find/paaOrderList")
    public PageView paaOrderList(PaymentApplyHeadQuery query) {
        PageView pageView =paymentAdvanceApplyLogic.paaOrderListByPage(query);
        return pageView;
    }

    @PostMapping("/find/paaOrderFilterAmountList")
    public PageView paaOrderFilterAmountList(PaymentApplyHeadQuery query) {
        PageView pageView =paymentAdvanceApplyLogic.paaOrderFilterAmountList(query);
        return pageView;
    }



    /**
     * 提交OA
     * @param applyId 预付款id
     */
    @PostMapping("/push/oa")
    public ResponseEntity pushOa(String applyId){
//        paymentAdvanceApplyLogic.pushOa(applyId);
        paymentAdvanceApplyLogic.pushOpen(applyId);

        return ResponseEntity.ok(true);
    }

    private JSONObject returnMsg(String msg) {
        JSONObject error = new JSONObject();
        error.put("code", HttpStatus.INTERNAL_SERVER_ERROR);
        error.put("message", msg);
        return error;
    }

    /**
     * 导入
     * @param file 导入文件
     * @return
     */
    @PostMapping("import")
    public ResponseEntity<String> importData(@RequestParam(value = "file") MultipartFile file) {
        String message = paymentAdvanceApplyLogic.importData(file);
        return ResponseEntity.ok(message);
    }

    @PostMapping("/toImg")
    public ResponseEntity toImg(Long appId) {
        PaymentAdvanceApplyListDTO paymentAdvanceApplyListDTO = paymentAdvanceApplyLogic.selectById(appId);
        if (StringUtils.isNotEmpty(paymentAdvanceApplyListDTO.getImgCode())&&StringUtils.isNotEmpty(paymentAdvanceApplyListDTO.getPoImgCode())
                &&paymentAdvanceApplyListDTO.getImgTime()!=null&&paymentAdvanceApplyListDTO.getPoImgTime()!=null
        ){
            throw new DaoException("该预付款单已影像化，不可重复操作");
        }
        paymentAdvanceApplyLogic.toImg(String.valueOf(appId));
        paymentAdvanceApplyLogic.toPoImg(appId);
        return ResponseEntity.ok(true);
    }

    @PostMapping("/deleteImg")
    public ResponseEntity deleteImg(Long appId) {
        PaymentAdvanceApplyListDTO paymentAdvanceApplyListDTO = paymentAdvanceApplyLogic.selectById(appId);
        if (paymentAdvanceApplyListDTO.getImgTime()==null&&paymentAdvanceApplyListDTO.getPoImgTime()==null){
            throw new DaoException("该预付款单未影像化，不可删除");
        }
        paymentAdvanceApplyLogic.deleteImg(appId);
        paymentAdvanceApplyLogic.deletePoImg(appId);
        return ResponseEntity.ok(true);
    }

    /**
     * 发送邮件催收
     *
     * @param id id
     */
    @PostMapping("/sendEmailCollection")
    public ResponseEntity sendEmailCollection(Long id) {
        paymentAdvanceApplyLogic.sendEmailCollection(id);
        return ResponseEntity.ok(true);
    }
}
