package cn.ezhizao.project.business.deposit.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.ezhizao.common.utils.SecurityUtils;
import cn.ezhizao.project.business.entrustOrder.domain.BizEntrustOrder;
import cn.ezhizao.project.business.entrustOrder.service.IBizEntrustOrderService;
import cn.ezhizao.project.system.domain.SysFileStorage;
import cn.ezhizao.project.system.service.ISysFileStorageService;
import cn.hutool.core.date.DateTime;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.project.business.deposit.domain.BizDeposit;
import cn.ezhizao.project.business.deposit.service.IBizDepositService;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.common.utils.poi.ExcelUtil;
import cn.ezhizao.framework.web.page.TableDataInfo;

/**
 * 存款Controller
 *
 * @author ruoyi
 * @date 2023-11-13
 */
@RestController
@RequestMapping("/business/deposit")
public class BizDepositController extends BaseController
{
    @Resource
    private IBizDepositService bizDepositService;

    @Resource
    private  ISysFileStorageService fileStorageService;

    @Resource
    private IBizEntrustOrderService bizEntrustOrderService;

    /**
     * 查询存款列表
     */
    @PreAuthorize("@ss.hasPermi('business:deposit:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizDeposit bizDeposit) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizDeposit);
        startPage();
        List<BizDeposit> list = bizDepositService.getList(bizDeposit);
        return getDataTable(list);
    }

    /**
     * 查询存款列表
     */
    @PreAuthorize("@ss.hasAnyPermi('business:deposit:edit,business:deposit:add')")
    @GetMapping("/listEntrustOrder")
    public TableDataInfo listEntrustOrder(BizEntrustOrder order) throws NoSuchFieldException, IllegalAccessException
    {
//        setTenantId(order);
        order.setFromTenantId(getTenantId());
        startPage();
        startOrderBy();
        List<BizEntrustOrder> list = bizEntrustOrderService.getList(order);
        return getDataTable(list);
    }

    /**
     * 导出存款列表
     */
    @PreAuthorize("@ss.hasPermi('business:deposit:export')")
    @Log(title = "存款", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizDeposit bizDeposit) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizDeposit);
        List<BizDeposit> list = bizDepositService.getList(bizDeposit);
        list.forEach(l -> {
            switch (l.getStatus()) {
                case 0:
                    l.setStatusTyp("未审核");
                    break;
                case 1:
                    l.setStatusTyp("已审核");
                    break;
                case 2:
                    l.setStatusTyp("不通过");
                    break;
            }
        });
        ExcelUtil<BizDeposit> util = new ExcelUtil<BizDeposit>(BizDeposit.class);
        util.exportExcel(response, list, "存款数据");
    }

    /**
     * 获取存款详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:deposit:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        BizDeposit bizDeposit = new BizDeposit();
        bizDeposit.setId(id);
        bizDeposit = bizDepositService.getList(bizDeposit).stream().findFirst().orElse(null);
        return success(bizDeposit);
    }

    /**
     * 新增存款
     */
    @PreAuthorize("@ss.hasPermi('business:deposit:add')")
    @Log(title = "存款", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizDeposit bizDeposit) throws NoSuchFieldException, IllegalAccessException
    {
        bizDeposit.setRemainAmount(bizDeposit.getAmount());
//        setTenantId(bizDeposit);
        return toAjax(bizDepositService.save(bizDeposit));
    }

    /**
     * 审核存款
     */
    @PreAuthorize("@ss.hasPermi('business:deposit:verify')")
    @Log(title = "存款", businessType = BusinessType.UPDATE)
    @PostMapping("/verify")
    public AjaxResult verify(@RequestBody BizDeposit bizDeposit) {
        if (bizDeposit.getStatus().equals(1) && bizDeposit.getFreeAmount() != null && bizDeposit.getFreeAmount().compareTo(BigDecimal.ZERO) > 0) {
            BizDeposit freeDeposit = new BizDeposit();
            freeDeposit.setDepositDate(DateTime.now().toTimestamp());
            freeDeposit.setVerifierId(SecurityUtils.getUserId());
            freeDeposit.setAmount(bizDeposit.getFreeAmount());
            freeDeposit.setEntrustOrderId(bizDeposit.getEntrustOrderId());
            freeDeposit.setRemainAmount(freeDeposit.getAmount());
            freeDeposit.setVerifyDate(DateTime.now().toTimestamp());
            freeDeposit.setType(2);
            freeDeposit.setStatus(1);
            freeDeposit.setFromTenantId(bizDeposit.getFromTenantId());
            freeDeposit.setTenantId(bizDeposit.getTenantId());
            bizDepositService.save(freeDeposit);
        }
        return toAjax(bizDepositService.updateById(bizDeposit));
    }

    /**
     * 修改存款
     */
    @PreAuthorize("@ss.hasPermi('business:deposit:edit')")
    @Log(title = "存款", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizDeposit bizDeposit) throws NoSuchFieldException, IllegalAccessException
    {
        bizDeposit.setRemainAmount(bizDeposit.getAmount());
//        setTenantId(bizDeposit);

        List<SysFileStorage> fileStorages = bizDeposit.getFiles();
        fileStorages.forEach(l -> {
            l.setMasterId(bizDeposit.getId());
            l.setMasterTableName("biz_deposit");
        });

        SysFileStorage delConditions = new SysFileStorage();
        delConditions.setMasterId(bizDeposit.getId());
        delConditions.setMasterTableName("biz_deposit");
        fileStorageService.physicalDelete(delConditions);

        return toAjax(bizDepositService.updateById(bizDeposit)&&(fileStorages.isEmpty() || fileStorageService.saveOrUpdateBatch(fileStorages)));
    }

    /**
     * 删除存款
     */
    @PreAuthorize("@ss.hasPermi('business:deposit:remove')")
    @Log(title = "存款", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids)
    {
        // 判断删除的存是否已审核
        if(bizDepositService.query().in("id", ids).ne("status", 0).count() > 0) {
            return error("不能删除已审核存款。");
        }
        return toAjax(bizDepositService.removeBatchByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('business:deposit:list')")
    @GetMapping("/getRemain")
    public AjaxResult getRemain()  throws NoSuchFieldException, IllegalAccessException{
        BizDeposit bizDeposit = new BizDeposit();
        setTenantId(bizDeposit);
        // 获取存款余额
        BigDecimal totalRemain = bizDepositService.getTotalRemain(bizDeposit);
        BigDecimal donateRemain = bizDepositService.getDonateRemain(bizDeposit);
        Map<String, Object> map = new HashMap<>();
        map.put("totalRemain", totalRemain);
        map.put("donateRemain", donateRemain);
        return success(map);
    }

}
