package com.liang.controller;

import com.github.pagehelper.PageInfo;
import com.liang.common.JsonTool;
import com.liang.common.base.BaseController;
import com.liang.common.base.BaseResult;
import com.liang.entity.PrjPayplan;
import com.liang.entity.PrjProject;
import com.liang.entity.StaExpertFee;
import com.liang.entity.StaPayapproval;
import com.liang.service.PrjPayplanService;
import com.liang.service.PrjPayplannameService;
import com.liang.service.StaPayapprovalService;
import io.swagger.models.auth.In;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Date;
import java.util.*;

/**
 * 付款计划(PrjPayplan)表控制层
 *
 * @author makejava
 * @since 2023-06-30 13:07:21
 */
@Controller
@RequestMapping("prjPayplan")
public class PrjPayplanController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private PrjPayplanService prjPayplanService;
    @Resource
    private PrjPayplannameService prjPayplannameService;

    @Resource
    private StaPayapprovalService staPayapprovalService;
    /**
     * 分页查询
     *
     * @param prjPayplan  筛选条件
     * @param pageRequest 分页对象
     * @return 查询结果
     */
    @GetMapping
    public ResponseEntity<Page<PrjPayplan>> queryByPage(PrjPayplan prjPayplan, PageRequest pageRequest) {
        return ResponseEntity.ok(this.prjPayplanService.queryByPage(prjPayplan, pageRequest));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<PrjPayplan> queryById(@PathVariable("id") Integer id) {
        return ResponseEntity.ok(this.prjPayplanService.queryById(id));
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(Integer id) {
        return ResponseEntity.ok(this.prjPayplanService.deleteById(id));
    }

    /**
     * 页面初始化
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list/{ht}", method = RequestMethod.POST)
    public BaseResult list(@PathVariable Integer ht) {
        List<PrjPayplan> list = prjPayplanService.getPayPlanList(ht);
        //添加判断 此付款计划是否已经被使用
        for (int i = 0; i < list.size(); i++) {
            Double a = staPayapprovalService.selectPayByFkjh(list.get(i).getId());
            list.get(i).setYfkje(a);
        }
        PageInfo<PrjPayplan> pageinfo = new PageInfo<>(list);
        //取出查询结果
        List<PrjPayplan> rows = pageinfo.getList();
        int total = (int) pageinfo.getTotal();
        Map<String, Object> result = new HashMap<>();
        result.put(RESULT_ROWS, rows);
        result.put(RESULT_TOTAL, total);

        return BaseResult.success(result);
    }

    /**
     * 新建数据
     *
     * @return
     */
    @RequestMapping(value = "/forAdd", method = RequestMethod.GET)
    public String forAdd(Model model) {
        //付款计划名称
        List<Map<String, String>> jhmcList = prjPayplannameService.getPlanName();
        model.addAttribute("jhmcList", jhmcList);

        return "prjpayplan/add";
    }

    /**
     * 保存数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doAdd", method = RequestMethod.POST)
    public BaseResult doAdd(PrjPayplan prjPayplan,
                            @RequestParam(required = false,value = "htje")Double htje) {
        // 判断当前 合同下支付计划是否超额
        List<PrjPayplan> list = prjPayplanService.getPayPlanList(prjPayplan.getHt());
        // 使用 Stream 计算总和
        Double je = 0.00 + prjPayplan.getZfje();
        for (int i = 0; i<list.size();i++){
            je = je + list.get(i).getZfje();
        }
        BigDecimal jes = BigDecimal.valueOf(je);
        jes = jes.setScale(3, BigDecimal.ROUND_HALF_UP);
        BigDecimal htjes = BigDecimal.valueOf(htje);
        if (jes.compareTo(htjes) <= 0){
            prjPayplan.setCjr(getSysUserId());
            int num = prjPayplanService.insert(prjPayplan);
            if (num > 0)
                return BaseResult.success("保存成功!", prjPayplan);
            else
                return BaseResult.failure("保存失败!");
        }else {
            return BaseResult.failure("保存失败，计划金额超出合同总金额!");
        }

    }

    @ResponseBody
    @RequestMapping(value = "/doAdd1", method = RequestMethod.POST)
    @Transactional
        public BaseResult doAdd( @RequestBody String data,
                            @RequestParam(required = false,value = "htje")Double htje) {
        List<PrjPayplan> prjPayplanList = JsonTool.parseArray(data, PrjPayplan.class);
        List<PrjPayplan> prjPayplanUpdateList = new ArrayList<>();//存放已存在的数据
        List<PrjPayplan> prjPayplanAddList = new ArrayList<>();//存放新创建的数据
        Integer ht = prjPayplanList.get(0).getHt();

        //再次校验付款计划总金额
        Double count = 0.0;
        for (int i = 0; i <prjPayplanList.size(); i++) {
            count +=prjPayplanList.get(i).getZfje();
            Integer id = prjPayplanList.get(i).getId();
            if (id!=null){
            prjPayplanUpdateList.add(prjPayplanList.get(i));
            }else {
            prjPayplanAddList.add(prjPayplanList.get(i));
            }

        }
        BigDecimal countBD = BigDecimal.valueOf(count);
        BigDecimal htjeBD = BigDecimal.valueOf(htje);
        if (countBD.compareTo(htjeBD) == 0) {
            for (int i = 0; i < prjPayplanAddList.size(); i++) {
                prjPayplanAddList.get(i).setCjr(getSysUserId());
                prjPayplanAddList.get(i).setCjsj(new Date(System.currentTimeMillis()));
            }
            //清理已删除的数据
            List<PrjPayplan> oldpayPlanList = prjPayplanService.getPayPlanList(ht);//获取就的付款计划数据
            Iterator<PrjPayplan> iterator = oldpayPlanList.iterator();
            while (iterator.hasNext()) {
                PrjPayplan oldItem = iterator.next();
                boolean found = false;
                for (PrjPayplan newItem : prjPayplanUpdateList) {
                    if (oldItem.getId().equals(newItem.getId())) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    prjPayplanService.deleteById(oldItem.getId());
                }
            }
            //保存新增的付款计划
            if (prjPayplanAddList.size()>0) {
                int num = prjPayplanService.insertBatch(prjPayplanAddList);
            }
            //修改已存在的付款计划
            for (int i = 0; i < prjPayplanUpdateList.size(); i++) {
             prjPayplanService.update(prjPayplanUpdateList.get(i));
            }


            return BaseResult.success("保存成功!", prjPayplanList);
        }else {
            return BaseResult.failure(-1,"保存失败，付款计划总金额不等于合同金额!");
        }

    }

    /**
     * 编辑数据
     *
     * @return
     */
    @RequestMapping(value = "/forUpdate", method = RequestMethod.GET)
    public String forUpdate() {
//        //当前项目
//        PrjPayplan payplan = prjPayplanService.queryById(id);
//        model.addAttribute("payplan", payplan);

        return "prjpayplan/update";
    }
    /**
     * 更新数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdate", method = RequestMethod.POST)
    public BaseResult doUpdate(PrjPayplan prjPayplan) {
        int num = prjPayplanService.update(prjPayplan);
        if (num > 0)
            return BaseResult.success("保存成功!", prjPayplan);
        else
            return BaseResult.failure("保存失败!");
    }

    /**
     * 浏览数据
     *
     * @return
     */
    @RequestMapping(value = "/forView/{id}", method = RequestMethod.GET)
    public String forView(Model model, @PathVariable Integer id) {
        //当前项目
        PrjPayplan payplan = prjPayplanService.queryById(id);
        model.addAttribute("payplan", payplan);

        return "prjpayplan/view";
    }
    @RequestMapping(value = "/forView1", method = RequestMethod.GET)
    public String forView1(Model model) {
        //当前项目
        return "prjpayplan/view1";
    }

    /**
     * 批量删除
     *
     * @param data
     * @return
     */
    @RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult batchDelete(@RequestBody String data) {
        List<PrjPayplan> contractList = JsonTool.parseArray(data, PrjPayplan.class);
        List<Integer> idList = new ArrayList<>();
        contractList.forEach(item -> {
            idList.add(item.getId());
        });
        List<PrjPayplan> ero = new ArrayList<>();
        if (idList.size() > 1) {
            for (int i = 0; i < idList.size(); i++) {
                List<StaPayapproval> list = staPayapprovalService.getFkjh(idList.get(i));
                if (list.size() == 0) {
                    continue;
                } else {
                    // 查询出当前付款计划详细信息
                    PrjPayplan prjPayplan = prjPayplanService.queryById(idList.get(i));
                    ero.add(prjPayplan);
                    idList.remove(idList.get(i));
                }
            }
            int num = prjPayplanService.batchDelete(idList);
            if (num > 0) {
                if (ero.size() == 0) {
                    return BaseResult.success("批量删除成功!");
                } else {
                    return BaseResult.success("批量部分删除成功！");
                }
            } else {
                return BaseResult.failure("批量删除失败!");
            }
        }else {
            List<StaPayapproval> list = staPayapprovalService.getFkjh(idList.get(0));
            if (list.size() == 0){
                int num = prjPayplanService.batchDelete(idList);
                if (num > 0) {
                    return BaseResult.success("删除成功！");
                }else {
                    return BaseResult.failure(1,"删除失败！");
                }
            }else {
                return BaseResult.failure(1,"删除失败，该比付款计划已绑定付款申请，不能删除！");
            }

        }
    }
}

