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.PrjPayplanXg;
import com.liang.service.PrjPayplanXgService;
import com.liang.service.PrjPayplannameService;
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.*;

/**
 * 付款计划(PrjPayplanXg)表控制层
 *
 */
@Controller
@RequestMapping("prjPayplanXg")
public class PrjPayplanXgController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private PrjPayplanXgService prjPayplanXgService;
    @Resource
    private PrjPayplannameService prjPayplannameService;

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

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

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

    /**
     * 页面初始化
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/list/{ht}", method = RequestMethod.POST)
    public BaseResult list(@PathVariable Integer ht) {
        List<PrjPayplanXg> list = prjPayplanXgService.getPayPlanList(ht);

        PageInfo<PrjPayplanXg> pageinfo = new PageInfo<>(list);
        //取出查询结果
        List<PrjPayplanXg> 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/addXg";
    }

    /**
     * 保存数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doAdd", method = RequestMethod.POST)
    public BaseResult doAdd(PrjPayplanXg prjPayplan,
                            @RequestParam(required = false,value = "htje")Double htje) {
        // 判断当前 合同下支付计划是否超额
        List<PrjPayplanXg> list = prjPayplanXgService.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 = prjPayplanXgService.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<PrjPayplanXg> prjPayplanList = JsonTool.parseArray(data, PrjPayplanXg.class);
        //删除之前提交但未保存的的付款计划
        Integer ht = prjPayplanList.get(0).getHt();
        prjPayplanXgService.deleteByHtId(ht);
        //再次校验付款计划总金额
        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){
                prjPayplanList.get(i).setOldid(id);
            }

        }
        BigDecimal countBD = BigDecimal.valueOf(count);
        BigDecimal htjeBD = BigDecimal.valueOf(htje);
        if (countBD.compareTo(htjeBD) == 0) {
            for (int i = 0; i < prjPayplanList.size(); i++) {
                prjPayplanList.get(i).setCjr(getSysUserId());
                prjPayplanList.get(i).setCjsj(new Date(System.currentTimeMillis()));
            }
            //保存新增的付款计划
            if (prjPayplanList.size()>0) {
                int num = prjPayplanXgService.insertBatch(prjPayplanList);
            }

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

    }


    /**
     * 编辑数据
     *
     * @return
     */
    @RequestMapping(value = "/forUpdate", method = RequestMethod.GET)
    public String forUpdate(Model model) {

        return "prjpayplan/updateXg";
    }

    /**
     * 更新数据
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doUpdate", method = RequestMethod.POST)
    public BaseResult doUpdate(PrjPayplanXg prjPayplan) {
        int num = prjPayplanXgService.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) {
        //当前项目
        PrjPayplanXg payplan = prjPayplanXgService.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());
        });

        int num = prjPayplanXgService.batchDelete(idList);
        if (num > 0) {
            return BaseResult.success("批量删除成功!");
        } else {
            return BaseResult.failure("批量删除失败!");
        }
    }
}

