package com.ruoyi.system.controller;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.ITblContractService;
import com.sun.jna.platform.win32.Guid;
import org.apache.poi.hpsf.GUID;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.ITblContractSettlementService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;
import javax.swing.text.html.Option;

/**
 * 合同收款Controller
 * 
 * @author ruoyi
 * @date 2022-03-01
 */
@Controller
@RequestMapping("/system/settlement")
public class TblContractSettlementController extends BaseController
{
    private String prefix = "system/settlement";

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ITblContractSettlementService tblContractSettlementService;

    @Autowired
    private ITblContractService tblContractService;

    @RequiresPermissions("system:settlement:view")
    @GetMapping()
    public String settlement(ModelMap mmap) {
        mmap.put("users", userService.selectAvailableUserList(new SysUser()));
        return prefix + "/settlement";
    }

    /**
     * 查询合同收款列表
     */
    @RequiresPermissions("system:settlement:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TblContract tblContract) {
        startPage();
        List<ContractSettleIndexModel> list = tblContractService.selectTblContractSettleList(tblContract);
//        if(list.size() > 0) {
//            List<String> ids = new ArrayList<String>();
//            for (ContractSettleIndexModel c : list) {
//                ids.add(c.getId());
//            }
//            //List<CntSettleSummaryModel> sumList = tblContractSettlementService.selectContractSettleSummary(ids.toArray(new String[ids.size()]));
//            List<CntSettleSummaryModel> payedList = tblContractSettlementService.selectContractPayedSummary(ids.toArray(new String[ids.size()]));
//            List<CntSettleSummaryModel> planList =  tblContractSettlementService.selectContractPlanSettleSummary(ids.toArray(new String[ids.size()]));
//            list = list.stream().map(c->{
//                Optional<CntSettleSummaryModel> payedOpt = payedList.stream().filter(x->x.getContractId().equals(c.getId())).findFirst();
//                Optional<CntSettleSummaryModel> planOpt = planList.stream().filter(x->x.getContractId().equals(c.getId())).findFirst();
//                if(payedOpt.isPresent())
//                {
//                    CntSettleSummaryModel payed = payedOpt.get();
//                    c.setPayedAmount(payed.getPayedAmount());
//                }
//                if(planOpt.isPresent())
//                {
//                    CntSettleSummaryModel plan = planOpt.get();
//                    c.setMatureAmount(plan.getMatureAmount());
//                    c.setMatureDate(plan.getMatureDate());
//                }
//                return  c;
//            }).collect(Collectors.toList());
////            if (sumList.size() > 0)
////            {
////                list = list.stream().map( c->
////                {
////                    Optional<CntSettleSummaryModel> sumOpt =  sumList.stream().filter(x->x.getContractId().equals(c.getId())).findFirst();
////                    if(sumOpt.isPresent()) {
////                        CntSettleSummaryModel sum = sumOpt.get();
////                        c.setPayedAmount(sum.getPayedAmount());
////                        c.setMatureAmount(sum.getMatureAmount());
////                        c.setMatureDate(sum.getMatureDate());
////                    }
////                    return  c;
////                }).collect(Collectors.toList());
////            }
//        }
        return getDataTable(list);
    }

    /**
     * 导出合同收款列表
     */
    @RequiresPermissions("system:settlement:export")
    @Log(title = "合同收款", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TblContractSettlement tblContractSettlement)
    {
        List<TblContractSettlement> list = tblContractSettlementService.selectTblContractSettlementList(tblContractSettlement);
        ExcelUtil<TblContractSettlement> util = new ExcelUtil<TblContractSettlement>(TblContractSettlement.class);
        return util.exportExcel(list, "settlement");
    }

    /**
     * 新增合同收款
     */
    @GetMapping("/add/{id}")
    public String add(@PathVariable("id") String id,@RequestParam(value = "settleType",defaultValue = "0",required = false) String settleType, ModelMap mmap)
    {
        List<TblContract> contracts = tblContractService.selectTblContractList(new TblContract());
        mmap.put("contracts",contracts);
        mmap.put("contractId",id);
        mmap.put("settleType",settleType);
        return prefix + "/add";
    }

    /**
     * 新增保存合同收款
     */
    @RequiresPermissions("system:settlement:add")
    @Log(title = "合同收款", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(CntSettlementModel cntSettlementModel)
    {
        String contractId = cntSettlementModel.getContractId();

        TblContract cnt = tblContractService.selectTblContractById(contractId);
        if(cnt == null){
            return  error("合同不存在");
        }
        TblContractSettlement settlement = new TblContractSettlement();
        String settleType = cntSettlementModel.getSettleType();
        String createBy = ShiroUtils.getLoginName();
        Date createDate = new Date();
        List<TblContractSettlement> list = new ArrayList<TblContractSettlement>();
        for (int i = 0; i< cntSettlementModel.getSettleDate().length; i++)
        {
            if(cntSettlementModel.getAmount()[i].compareTo(new BigDecimal(0)) > 0){
                settlement = new TblContractSettlement();
                settlement.setContractId(contractId);
                settlement.setSettleType(settleType);
                settlement.setPayMode("0"); //尚未明确付款方式需求，默认先填0
                settlement.setSettleDate(cntSettlementModel.getSettleDate()[i]);
                settlement.setAmount(cntSettlementModel.getAmount()[i]);
                if(cntSettlementModel.getRemark().length > i) {
                    settlement.setRemark(cntSettlementModel.getRemark()[i]);
                }
                settlement.setCreateBy(createBy);
                settlement.setCreateTime(createDate);
                list.add(settlement);
            }
        }
        return toAjax(tblContractSettlementService.insertTblContractSettlementList(list));
    }

    /**
     * 修改合同收款
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id,@RequestParam(value = "settleType",defaultValue = "0",required = false) String settleType, ModelMap mmap)
    {
        TblContract contract = tblContractService.selectTblContractById(id);
        TblContractSettlement settle = new TblContractSettlement();
        settle.setContractId(id);
        settle.setSettleType(settleType);
        List<TblContractSettlement> ls = tblContractSettlementService.selectTblContractSettlementList(settle);
        mmap.put("contract",contract);
        mmap.put("settlements",ls);
        mmap.put("settleType",settleType);
        if(settleType.equals("1")){
            settle.setSettleType("0");
            mmap.put("planList",tblContractSettlementService.selectTblContractSettlementList(settle));
        }
        return prefix + "/edit";
    }

    /**
     * 修改保存合同收款
     */
    @RequiresPermissions("system:settlement:edit")
    @Log(title = "合同收款", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TblContractSettlement tblContractSettlement)
    {
        return toAjax(tblContractSettlementService.updateTblContractSettlement(tblContractSettlement));
    }

    @RequiresPermissions("system:contract:edit")
    @GetMapping("/editPayStatus/{id}")
    public  String editPayStatus(@PathVariable("id") String id,ModelMap mmap){
        TblContract tblContract = tblContractService.selectTblContractById(id);
        mmap.put("tblContract", tblContract);
        return  prefix + "/editPayStatus";
    }

    /**
     * 删除合同收款
     */
    @RequiresPermissions("system:settlement:remove")
    @Log(title = "合同收款", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(@RequestBody String ids)
    {
        return toAjax(tblContractSettlementService.deleteTblContractSettlementByIds(ids));
    }

    @RequiresPermissions("system:settlement:list")
    @PostMapping("/querysettlelist")
    @ResponseBody
    public  AjaxResult querysettlelist(@RequestBody TblContractSettlement settle){
        return AjaxResult.success(tblContractSettlementService.selectTblContractSettlementList(settle));
    }

    /**
     * 修改收款提示状态
     */
    @RequiresPermissions("system:settlement:edit")
    @Log(title = "合同收款提示状态修改", businessType = BusinessType.UPDATE)
    @PostMapping("/editWarnFlag")
    @ResponseBody
    public AjaxResult editWarnFlag(@RequestBody TblContractSettlement tblContractSettlement)
    {
        return toAjax(tblContractSettlementService.updateTblContractSettlement(tblContractSettlement));
    }
}
