package io.renren.modules.business.controller;

import io.renren.common.utils.*;
import io.renren.modules.business.entity.BusinessOutlayIncomeEntity;
import io.renren.modules.business.service.BusinessAnnualService;
import io.renren.modules.business.service.BusinessOutlayIncomeService;
import io.renren.modules.business.service.BusinessOutlayService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

import static io.renren.common.utils.ShiroUtils.getUserId;


/**
 * 收支总结表
 *
 * @author jiaqiao
 * @email jiaqiao@163.com
 * @date 2022-10-13 10:00:10
 */
@RestController
@RequestMapping("business/businessoutlayincome")
public class BusinessOutlayIncomeController {
    @Autowired
    private BusinessOutlayIncomeService businessOutlayIncomeService;
    @Autowired
    private BusinessOutlayService businessOutlayService;
    @Autowired
    private BusinessAnnualService businessAnnualService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("business:businessoutlayincome:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = businessOutlayIncomeService.queryPage(params);
        return R.ok().put("page", page);
    }

    @RequestMapping("/pcListPage")
    @RequiresPermissions("business:businessoutlayincome:list")
    public R pcListPage(@RequestParam Map<String, Object> params){
        PageUtils page = businessOutlayIncomeService.pcListPage(params);
        return R.ok().put("page", page);
    }

    /**
     * 获取未删除的列表不含有翻页
     */
    @RequestMapping("/listNoPage")
    @RequiresPermissions("business:businessoutlayincome:list")
    public R listNoPage(@RequestParam Map<String, Object> params){
        List<BusinessOutlayIncomeEntity> page = businessOutlayIncomeService.listNoPage(params);
        return R.ok().put("page", page);
    }

    /**
     * 获取未删除的列表不含有翻页
     */
    @RequestMapping("/listNowTime")
    @RequiresPermissions("business:businessoutlayincome:list")
    public R listNowTime(@RequestParam Map<String, Object> params){
        List<BusinessOutlayIncomeEntity> page = businessOutlayIncomeService.listNowTime(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
        @RequiresPermissions("business:businessoutlayincome:info")
    public R info(@PathVariable("id") Integer id){
		BusinessOutlayIncomeEntity businessOutlayIncome = businessOutlayIncomeService.getById(id);

        return R.ok().put("businessOutlayIncome", businessOutlayIncome);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("business:businessoutlayincome:save")
    public R save(@RequestBody BusinessOutlayIncomeEntity businessOutlayIncome) throws ParseException {
//        BusinessOutlayIncomeEntity businessOutlayIncomeOld = null;
        if(businessOutlayIncome.getId() == null) {
            // 保存时，按填写人和日期查询是否已经填写
            Map<String, Object> param = new HashMap<>();
            param.put("outinDate", DateUtils.format(businessOutlayIncome.getOutinDate()));
            param.put("writeUserId", businessOutlayIncome.getWriteUserId());
            List l = businessOutlayIncomeService.listNoPage(param);
            if(l.size() > 0) {
                return R.error("该日期已经填写，无法再次填写！");
            }
            businessOutlayIncome.setCreateTime(new Date());
            businessOutlayIncome.setUpdateTime(new Date());
            businessOutlayIncomeService.save(businessOutlayIncome);
            //businessOutlayIncomeService.ifSave(businessOutlayIncome.getOutinDate(),businessOutlayIncome.getWriteUserId().toString(),1);
        } else {
            businessOutlayIncome.setUpdateTime(new Date());
            businessOutlayIncomeService.updateById(businessOutlayIncome);
        }
        afreshNext(businessOutlayIncome);
        return R.ok();
    }

    /***
     * 重新计算
     * 收支修改或新增时：
     * 循环修改此日之后的收支数据，知道没有下一日数据为止
     */
    private void afreshNext(BusinessOutlayIncomeEntity businessOutlayIncomeEntity){
        Map<String, Object> param = new HashMap<>();
        param.put("outinDate", businessOutlayIncomeEntity.getOutinDate());
        param.put("writeUserId", businessOutlayIncomeEntity.getWriteUserId());
        //获取下一日期收支数据
        BusinessOutlayIncomeEntity incomeEntity = businessOutlayIncomeService.getNextOutInByDate(param);
        if(incomeEntity!=null){
            Double zrye = businessOutlayIncomeEntity.getOutinTdayBalance(); //今日余额是下一日期的昨日余额
            incomeEntity.setOutinYdayBalance(zrye);
            Double jrsr = incomeEntity.getOutinTdayIncome();//今日收入
            if(jrsr == null) {
                jrsr = 0d;
            }
            param.put("userId", businessOutlayIncomeEntity.getWriteUserId());
            param.put("startTime", DateUtils.format(incomeEntity.getOutinDate()));
            param.put("endTime", DateUtils.format(incomeEntity.getOutinDate()));
            Double jrzc = businessOutlayService.getTotalByHJGId(param);
            if(jrzc == null) {
                jrzc = 0d;
            }
            incomeEntity.setOutinTdayOut(jrzc);//今日支出
            Double jrye = zrye + jrsr - jrzc;
            incomeEntity.setOutinTdayBalance(jrye);//今日余额
            incomeEntity.setUpdateTime(new Date());
            businessOutlayIncomeService.updateById(incomeEntity);
            afreshNext(incomeEntity);//递归
        }
    }

    /**
     * 获取计算的值
     */
    @RequestMapping("/getCalcVal")
    @RequiresPermissions("business:businessoutlayincome:save")
    public R getCalcVal(@RequestBody BusinessOutlayIncomeEntity businessOutlayIncome) throws ParseException {
        // 保存时，按填写人和日期查询是否已经填写
        Map<String, Object> param = new HashMap<>();
        param.put("writeUserId", businessOutlayIncome.getWriteUserId());
        if(StringUtils.isNotBlank(businessOutlayIncome.getOutinRemark())) {
            param.put("startTime", businessOutlayIncome.getOutinRemark());
        }
        // 查询昨日余额，就是总结里除去今天最大一天的今日余额
        BigDecimal zrye = businessOutlayIncomeService.getZrye(param);
        //  今日支出是明细里当天汇总过来。
        param = new HashMap<>();
        param.put("userId", businessOutlayIncome.getWriteUserId());
        String today = DateUtils.format(new Date());
        param.put("startTime", businessOutlayIncome.getOutinRemark());
        param.put("endTime", businessOutlayIncome.getOutinRemark());
        Double jrzc = businessOutlayService.getTotalByHJGId(param);
        if(jrzc == null) {
            jrzc = 0d;
        }
        Map<String, Object> result = new HashMap<>();
        result.put("zrye", zrye);
        result.put("jrzc", jrzc);

        return R.ok(result);
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("business:businessoutlayincome:update")
    public R update(@RequestBody BusinessOutlayIncomeEntity businessOutlayIncome){
        businessOutlayIncome.setUpdateTime(new Date());
		businessOutlayIncomeService.updateById(businessOutlayIncome);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("business:businessoutlayincome:delete")
    public R delete(@RequestBody Integer[] ids){
		businessOutlayIncomeService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }


    /**
     * 导出
     */
    @RequestMapping("/export")
    public void export(HttpServletResponse response, HttpServletRequest request){
        String start = request.getParameter("start");
        String end = request.getParameter("end");
        Map<String, Object> params = new HashMap<>();
        params.put("writeUserId",getUserId());
        params.put("start",start);
        params.put("end",end);
        List<BusinessOutlayIncomeEntity> list = businessOutlayIncomeService.pcListNoPage(params);
        ExcelUtil<BusinessOutlayIncomeEntity> util = new ExcelUtil<BusinessOutlayIncomeEntity>(BusinessOutlayIncomeEntity.class);
        R r = util.exportExcel(list, "收支总结");
        try {
            String filename = r.get("msg") + "";
            String filepath = FileUtils.getTempDirectoryPath() + File.separator + filename;
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, filename);
            FileUtils.writeBytes(filepath, response.getOutputStream());
            FileUtils.deleteFile(filepath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
