package cn.ezhizao.project.business.controller;

import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.ezhizao.common.utils.poi.ExcelUtil;
import cn.ezhizao.framework.aspectj.lang.annotation.Log;
import cn.ezhizao.framework.aspectj.lang.enums.BusinessType;
import cn.ezhizao.framework.web.controller.BaseController;
import cn.ezhizao.framework.web.domain.AjaxResult;
import cn.ezhizao.framework.web.page.TableDataInfo;
import cn.ezhizao.project.business.domain.BizOutsourceBalanceMonth;
import cn.ezhizao.project.business.service.IBizOutsourceBalanceMonthService;
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.project.business.domain.BizOutsourceBalanceAccount;
import cn.ezhizao.project.business.service.IBizOutsourceBalanceAccountService;

/**
 * 外协结算Controller
 *
 * @author ezhizao
 * @date 2024-08-12
 */
@RestController
@RequestMapping("/business/balanceAccount")
public class BizOutsourceBalanceAccountController extends BaseController
{
    @Resource
    private IBizOutsourceBalanceAccountService bizOutsourceBalanceAccountService;
    @Resource
    private IBizOutsourceBalanceMonthService bizOutsourceBalanceMonthService;

    /**
     * 查询外协结算列表
     */
    @PreAuthorize("@ss.hasPermi('business:balanceAccount:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizOutsourceBalanceAccount bizOutsourceBalanceAccount) throws NoSuchFieldException, IllegalAccessException
    {
        startPage();
        setTenantId(bizOutsourceBalanceAccount);
        List<BizOutsourceBalanceAccount> list = bizOutsourceBalanceAccountService.getList(bizOutsourceBalanceAccount);
        return getDataTable(list);
    }

    /**
     * 导出外协结算列表
     */
    @PreAuthorize("@ss.hasPermi('business:balanceAccount:export')")
    @Log(title = "外协结算", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizOutsourceBalanceAccount bizOutsourceBalanceAccount) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizOutsourceBalanceAccount);
        List<BizOutsourceBalanceAccount> list = bizOutsourceBalanceAccountService.getList(bizOutsourceBalanceAccount);
        ExcelUtil<BizOutsourceBalanceAccount> util = new ExcelUtil<BizOutsourceBalanceAccount>(BizOutsourceBalanceAccount.class);
        util.exportExcel(response, list, "外协结算数据");
    }

    /**
     * 获取外协结算详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:balanceAccount:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(bizOutsourceBalanceAccountService.getById(id));
    }

    /**
     * 新增外协结算
     */
    @PreAuthorize("@ss.hasPermi('business:balanceAccount:save')")
    @Log(title = "外协结算", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizOutsourceBalanceAccount bizOutsourceBalanceAccount) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizOutsourceBalanceAccount);
        return toAjax(bizOutsourceBalanceAccountService.save(bizOutsourceBalanceAccount));
    }

    /**
     * 修改外协结算
     */
    @PreAuthorize("@ss.hasPermi('business:balanceAccount:save')")
    @Log(title = "外协结算", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizOutsourceBalanceAccount bizOutsourceBalanceAccount) throws NoSuchFieldException, IllegalAccessException
    {
        setTenantId(bizOutsourceBalanceAccount);
        boolean result = bizOutsourceBalanceAccountService.updateById(bizOutsourceBalanceAccount);
        return result ? success(bizOutsourceBalanceAccount) : error();
    }

    /**
     * 删除外协结算
     */
    @PreAuthorize("@ss.hasPermi('business:balanceAccount:remove')")
    @Log(title = "外协结算", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids)
    {
        return toAjax(bizOutsourceBalanceAccountService.removeBatchByIds(ids));
    }

    /**
     * 结算
     */
    @PreAuthorize("@ss.hasPermi('business:balanceAccount:confirm')")
    @Log(title = "外协结算", businessType = BusinessType.UPDATE)
    @PostMapping("/confirm")
    public AjaxResult confirm(@RequestBody List<BizOutsourceBalanceAccount> bizOutsourceBalanceAccounts)
    {
        bizOutsourceBalanceAccounts.forEach(l ->{
            l.setStatus(1);
//            l.setCheckoutDate(new Date());
        });
        bizOutsourceBalanceAccountService.updateBatchById(bizOutsourceBalanceAccounts);
        return success();
    }
    /**
     * 取消结算
     */
    @PreAuthorize("@ss.hasPermi('business:balanceAccount:cancel')")
    @Log(title = "外协结算", businessType = BusinessType.UPDATE)
    @PostMapping("/cancel")
    public AjaxResult cancel(@RequestBody List<BizOutsourceBalanceAccount> bizOutsourceBalanceAccounts)
    {
        // 判断是否在外协结算期间内结算的
        // 获取当前结算期
        BizOutsourceBalanceMonth bizOutsourceBalanceMonth = bizOutsourceBalanceMonthService.query().isNull("stop_date").one();
        if (bizOutsourceBalanceAccounts.stream().anyMatch(v -> v.getCheckoutDate() == null)) {
            return error("请选择已结算外协，取消结算");
        }
        if (bizOutsourceBalanceAccounts.stream().anyMatch(v -> v.getCheckoutDate().before(bizOutsourceBalanceMonth.getStartDate()))) {
            return error("结算日期小于" + new DateTime(bizOutsourceBalanceMonth.getStartDate()).toString("yyyy-MM-dd") + "，不允许取消结算");
        }
        bizOutsourceBalanceAccounts.forEach(l ->{
            l.setStatus(0);
            l.setCheckoutDate(null);
        });
        bizOutsourceBalanceAccountService.updateBatchById(bizOutsourceBalanceAccounts);
        return success();
    }

    @PreAuthorize("@ss.hasPermi('business:balanceAccount:save')")
    @Log(title = "外协结算保存", businessType = BusinessType.UPDATE)
    @PostMapping("/saveBatch")
    public AjaxResult saveBatch(@RequestBody List<BizOutsourceBalanceAccount> bizOutsourceBalanceAccounts) {
        return toAjax(bizOutsourceBalanceAccountService.saveOrUpdateBatch(bizOutsourceBalanceAccounts));
    }
}
