package com.zehong.web.controller.transaction;

import com.zehong.common.annotation.Log;
import com.zehong.common.core.controller.BaseController;
import com.zehong.common.core.domain.AjaxResult;
import com.zehong.common.core.domain.entity.SysUser;
import com.zehong.common.core.exception.BusinessException;
import com.zehong.common.core.page.TableDataInfo;
import com.zehong.common.enums.BusinessType;
import com.zehong.common.utils.SecurityUtils;
import com.zehong.common.utils.ServletUtils;
import com.zehong.common.utils.StringUtils;
import com.zehong.common.utils.poi.ExcelUtil;
import com.zehong.framework.web.service.TokenService;
import com.zehong.system.domain.TAccount;
import com.zehong.system.domain.TPurchase;
import com.zehong.system.service.ITAccountService;
import com.zehong.system.service.ITPurchaseService;
import com.zehong.system.service.impl.purchase.PurchaseOperateStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 外部采购（报销）申请Controller
 * 
 * @author zehong
 * @date 2023-06-16
 */
@RestController
@RequestMapping("/system/purchase")
public class TPurchaseController extends BaseController
{
    @Autowired
    private ITPurchaseService tPurchaseService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ITAccountService itAccountService;
    /**
     * 查询外部采购（报销）申请列表
     */
    @PreAuthorize("@ss.hasPermi('system:purchase:list')")
    @GetMapping("/list")
    public TableDataInfo list(TPurchase tPurchase)
    {
        // 获取当前用户
        SysUser user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        if (StringUtils.isNotNull(user) && !user.isAdmin()) {
            tPurchase.setPurchaseDeptId(user.getDeptId());
        }
        startPage();
        List<TPurchase> list = tPurchaseService.selectTPurchaseList(tPurchase);
        setOperate(list);
        return getDataTable(list);
    }

    /**
     * 设置查询权限
     * @param purchaseList 采购列表
     */
    private void setOperate (List<TPurchase> purchaseList){
        purchaseList.stream().forEach(purchase ->{
            new PurchaseOperateStrategy().purchaseOperateStrategy(purchase);
        });
    }

    /**
     * 导出外部采购（报销）申请列表
     */
    @PreAuthorize("@ss.hasPermi('system:purchase:export')")
    @Log(title = "外部采购（报销）申请", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TPurchase tPurchase)
    {
        List<TPurchase> list = tPurchaseService.selectTPurchaseList(tPurchase);
        ExcelUtil<TPurchase> util = new ExcelUtil<TPurchase>(TPurchase.class);
        return util.exportExcel(list, "外部采购（报销）申请数据");
    }

    /**
     * 获取外部采购（报销）申请详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:purchase:query')")
    @GetMapping(value = "/{purchaseId}")
    public AjaxResult getInfo(@PathVariable("purchaseId") Long purchaseId)
    {
        return AjaxResult.success(tPurchaseService.selectTPurchaseById(purchaseId));
    }

    /**
     * 新增外部采购（报销）申请
     */
    @PreAuthorize("@ss.hasPermi('system:purchase:add')")
    @Log(title = "外部采购（报销）申请", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TPurchase tPurchase)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();

        if(!itAccountService.checkAccountCanTrade(user.getDeptId(),tPurchase.getTotal())){
            return AjaxResult.error("账户可用金额不足！");
        }
        return toAjax(tPurchaseService.insertTPurchase(tPurchase));
    }

    /**
     * 修改外部采购（报销）申请
     */
    @PreAuthorize("@ss.hasPermi('system:purchase:edit')")
    @Log(title = "外部采购（报销）申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TPurchase tPurchase)
    {
        return toAjax(tPurchaseService.updateTPurchase(tPurchase));
    }

    /**
     * 删除外部采购（报销）申请
     */
    @PreAuthorize("@ss.hasPermi('system:purchase:remove')")
    @Log(title = "外部采购（报销）申请", businessType = BusinessType.DELETE)
	@DeleteMapping("/{purchaseIds}")
    public AjaxResult remove(@PathVariable Long[] purchaseIds)
    {
        return toAjax(tPurchaseService.deleteTPurchaseByIds(purchaseIds));
    }

    /**
     * 核算部审批
     * @param tPurchase
     * @return
     */
    @PostMapping("/approvalPurchase")
    public AjaxResult approvalPurchase(@RequestBody TPurchase tPurchase){
        try{
            return toAjax(tPurchaseService.approvalPurchase(tPurchase));
        }catch (BusinessException e){
            return AjaxResult.error(e.getMessage());
        }
    }
}
