package com.bs.cw.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.bs.tm.domain.TmOrder;
import com.bs.tm.domain.TmOrderTransCargo;
import com.bs.tm.service.ITmOrderService;
import com.bs.tm.service.ITmOrderTransCargoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
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 com.bs.common.annotation.Log;
import com.bs.common.core.controller.BaseController;
import com.bs.common.core.domain.AjaxResult;
import com.bs.common.core.page.TableDataInfo;
import com.bs.common.enums.BusinessType;
import com.bs.common.utils.poi.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.hutool.core.lang.Validator;
import com.bs.cw.domain.CwAmortizeCost;
import com.bs.cw.service.ICwAmortizeCostService;
import javax.annotation.Resource;

/**
 * 费用Controller
 *
 * @author bs
 * @date 2024-02-07
 */
@Api(tags = "费用")
@RestController
@RequestMapping("/amortize/cost")
public class CwAmortizeCostController extends BaseController {
    @Resource
    private ICwAmortizeCostService cwAmortizeCostService;
    @Resource
    private ITmOrderTransCargoService tmOrderTransCargoService;
    @Resource
    private ITmOrderService tmOrderService;

    /**
     * 分页查询费用列表
     */
    @ApiOperation("分页查询费用列表")
    @GetMapping("/pageList")
    public TableDataInfo pageList(CwAmortizeCost cwAmortizeCost) {
        startPage();
        LambdaQueryWrapper<CwAmortizeCost> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,cwAmortizeCost);
        List<CwAmortizeCost> list = cwAmortizeCostService.list(queryWrapper);
        return getDataTable(list);
    }

    /**
     * 查询费用列表
     */
    @ApiOperation("查询费用列表")
    @GetMapping("/list")
    public AjaxResult list(CwAmortizeCost cwAmortizeCost) {
        LambdaQueryWrapper<CwAmortizeCost> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,cwAmortizeCost);
        List<CwAmortizeCost> list = cwAmortizeCostService.list(queryWrapper);
        return success(list);
    }

    /**
     * 导出费用列表
     */
    @ApiOperation("导出费用列表")
    @Log(title = "费用导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CwAmortizeCost cwAmortizeCost) {
        LambdaQueryWrapper<CwAmortizeCost> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,cwAmortizeCost);
        List<CwAmortizeCost> list = cwAmortizeCostService.list(queryWrapper);
        ExcelUtil<CwAmortizeCost> util = new ExcelUtil<CwAmortizeCost>(CwAmortizeCost. class);
        util.exportExcel(response, list, "费用数据");
    }

    /**
     * 获取费用详细信息
     */
    @ApiOperation("获取费用详细信息")
    @GetMapping(value = "/{ID}")
    public AjaxResult getInfo(@PathVariable("ID") Long ID) {
        return success(cwAmortizeCostService.getById(ID));
    }

    /**
     * 新增费用
     */
    @ApiOperation("新增费用")
    @Log(title = "费用新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CwAmortizeCost cwAmortizeCost) {
        return toAjax(cwAmortizeCostService.save(cwAmortizeCost));
    }

    /**
     * 修改费用
     */
    @ApiOperation("修改费用")
    @Log(title = "费用修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CwAmortizeCost cwAmortizeCost) {
        return toAjax(cwAmortizeCostService.updateById(cwAmortizeCost));
    }

    @ApiOperation("自动计算费用")
    @Log(title = "自动计算费用", businessType = BusinessType.INSERT)
    @PostMapping("/autoCalc")
    public AjaxResult autoCalc(@RequestBody TmOrder tmOrder) {
        if (null != tmOrder && Validator.isNotEmpty(tmOrder.getOrderType())) {
            CwAmortizeCost cwAmortizeCost = new CwAmortizeCost();
            cwAmortizeCost.setOrderType(tmOrder.getOrderType());
            cwAmortizeCost.setOrderId(tmOrder.getId());
            cwAmortizeCost.setOrderNo(tmOrder.getOrderNo());
            if (null == tmOrder.getFreightRates()) {
                cwAmortizeCost.setItemRate(BigDecimal.ZERO);
            } else {
                cwAmortizeCost.setItemRate(tmOrder.getFreightRates());
            }
            cwAmortizeCost.setCurrency(tmOrder.getCurrency());
            cwAmortizeCost.setStatus("0");
            cwAmortizeCost.setWriteoffCost(new BigDecimal(0));
            cwAmortizeCost.setInvoiceCost(new BigDecimal(0));
            cwAmortizeCost.setWriteoffStatus("0");
            cwAmortizeCost.setCustId(tmOrder.getCustId());
            cwAmortizeCost.setCustName(tmOrder.getCustName());
            cwAmortizeCost.setItemCode("ysfy");
            cwAmortizeCost.setItemName("运输费用");
            cwAmortizeCost.setInputDate(new Date());
            BigDecimal cargoWtTotal = new BigDecimal(0);
            List<TmOrderTransCargo> lsCargos = new ArrayList<>();
            if ("0".equals(tmOrder.getOrderType())) {
                //cwAmortizeCost.setItemNum();
                //cwAmortizeCost.setItemCost();
                cwAmortizeCost.setRpFlag("0");
                List<TmOrder> lsOrder = tmOrderService.list(new LambdaQueryWrapper<TmOrder>().eq(TmOrder::getSourceNo, tmOrder.getOrderNo()));
                if (null != lsOrder && lsOrder.size() > 0) {
                    List<Long> ids = new ArrayList<>();
                    for (TmOrder order : lsOrder) {
                        ids.add(order.getId());
                    }
                    lsCargos = tmOrderTransCargoService.list(new LambdaQueryWrapper<TmOrderTransCargo>().in(TmOrderTransCargo::getOrderId, ids));
                }
            } else if ("1".equals(tmOrder.getOrderType())) {
                cwAmortizeCost.setRpFlag("1");
                lsCargos = tmOrderTransCargoService.list(new LambdaQueryWrapper<TmOrderTransCargo>().eq(TmOrderTransCargo::getOrderId, tmOrder.getId()));
            }
            if (null != lsCargos && lsCargos.size() > 0) {
                for (TmOrderTransCargo cargo : lsCargos) {
                    if (null != cargo.getRealTransWt() && cargo.getRealTransWt().compareTo(BigDecimal.ZERO) > 0) {
                        cargoWtTotal = cargoWtTotal.add(cargo.getRealTransWt());
                    } else if (null != cargo.getRealLoadWt() && cargo.getRealLoadWt().compareTo(BigDecimal.ZERO) > 0) {
                        cargoWtTotal = cargoWtTotal.add(cargo.getRealTransWt());
                    }
                }
            }
            cwAmortizeCost.setItemNum(cargoWtTotal);
            cwAmortizeCost.setItemCost(cargoWtTotal.multiply(cwAmortizeCost.getItemRate()));
            cwAmortizeCost.setItemType("1");
            return toAjax(cwAmortizeCostService.save(cwAmortizeCost));
        } else {
            return warn("请选择订单进行计算");
        }
    }

    /**
     * 删除费用
     */
    @ApiOperation("删除费用")
    @Log(title = "费用删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{IDs}")
    public AjaxResult remove(@PathVariable List<Long> IDs) {
        return toAjax(cwAmortizeCostService.removeBatchByIds(IDs));
    }

    /**
      * 条件设置
      */
    private void condition (LambdaQueryWrapper<CwAmortizeCost> queryWrapper,CwAmortizeCost cwAmortizeCost){


        //id
        if(Validator.isNotEmpty(cwAmortizeCost.getId())){
            queryWrapper.eq(CwAmortizeCost::getId,cwAmortizeCost.getId());
        }

        //订单ID
        if(Validator.isNotEmpty(cwAmortizeCost.getOrderId())){
            queryWrapper.eq(CwAmortizeCost::getOrderId,cwAmortizeCost.getOrderId());
        }

        //提单号
        if(Validator.isNotEmpty(cwAmortizeCost.getOrderNo())){
            queryWrapper.like(CwAmortizeCost::getOrderNo,cwAmortizeCost.getOrderNo());
        }

        //应收应付0-应收1-应付
        if(Validator.isNotEmpty(cwAmortizeCost.getRpFlag())){
            queryWrapper.eq(CwAmortizeCost::getRpFlag,cwAmortizeCost.getRpFlag());
        }

        //业务类型
        if(Validator.isNotEmpty(cwAmortizeCost.getBizCode())){
            queryWrapper.eq(CwAmortizeCost::getBizCode,cwAmortizeCost.getBizCode());
        }

        //费目代码
        if(Validator.isNotEmpty(cwAmortizeCost.getItemCode())){
            queryWrapper.eq(CwAmortizeCost::getItemCode,cwAmortizeCost.getItemCode());
        }

        //费目名称
        if(Validator.isNotEmpty(cwAmortizeCost.getItemName())){
            queryWrapper.eq(CwAmortizeCost::getItemName,cwAmortizeCost.getItemName());
        }

        //费率
        if(Validator.isNotEmpty(cwAmortizeCost.getItemRate())){
            queryWrapper.eq(CwAmortizeCost::getItemRate,cwAmortizeCost.getItemRate());
        }

        //数量
        if(Validator.isNotEmpty(cwAmortizeCost.getItemNum())){
            queryWrapper.eq(CwAmortizeCost::getItemNum,cwAmortizeCost.getItemNum());
        }

        //费用
        if(Validator.isNotEmpty(cwAmortizeCost.getItemCost())){
            queryWrapper.eq(CwAmortizeCost::getItemCost,cwAmortizeCost.getItemCost());
        }

        //币种
        if(Validator.isNotEmpty(cwAmortizeCost.getCurrency())){
            queryWrapper.eq(CwAmortizeCost::getCurrency,cwAmortizeCost.getCurrency());
        }

        //开始日期
        if(Validator.isNotEmpty(cwAmortizeCost.getBeginDate())){
            queryWrapper.ge(CwAmortizeCost::getInputDate,cwAmortizeCost.getBeginDate());
        }

        //结束日期
        if(Validator.isNotEmpty(cwAmortizeCost.getEndDate())){
            queryWrapper.le(CwAmortizeCost::getInputDate,cwAmortizeCost.getEndDate());
        }

        //录入日期
        if(Validator.isNotEmpty(cwAmortizeCost.getInputDate())){
            queryWrapper.eq(CwAmortizeCost::getInputDate,cwAmortizeCost.getInputDate());
        }

        //摘要
        if(Validator.isNotEmpty(cwAmortizeCost.getSummary())){
            queryWrapper.eq(CwAmortizeCost::getSummary,cwAmortizeCost.getSummary());
        }

        //凭证号
        if(Validator.isNotEmpty(cwAmortizeCost.getVoucherNo())){
            queryWrapper.eq(CwAmortizeCost::getVoucherNo,cwAmortizeCost.getVoucherNo());
        }

        //税率
        if(Validator.isNotEmpty(cwAmortizeCost.getTaxRate())){
            queryWrapper.eq(CwAmortizeCost::getTaxRate,cwAmortizeCost.getTaxRate());
        }

        //不含税价
        if(Validator.isNotEmpty(cwAmortizeCost.getTaxFreePrice())){
            queryWrapper.eq(CwAmortizeCost::getTaxFreePrice,cwAmortizeCost.getTaxFreePrice());
        }

        //税金
        if(Validator.isNotEmpty(cwAmortizeCost.getTaxAmount())){
            queryWrapper.eq(CwAmortizeCost::getTaxAmount,cwAmortizeCost.getTaxAmount());
        }

        //报销单号
        if(Validator.isNotEmpty(cwAmortizeCost.getExpenseNo())){
            queryWrapper.eq(CwAmortizeCost::getExpenseNo,cwAmortizeCost.getExpenseNo());
        }

        //状态
        if(Validator.isNotEmpty(cwAmortizeCost.getStatus())){
            queryWrapper.eq(CwAmortizeCost::getStatus,cwAmortizeCost.getStatus());
        }

        //是否公共成本
        if(Validator.isNotEmpty(cwAmortizeCost.getIsPublic())){
            queryWrapper.eq(CwAmortizeCost::getIsPublic,cwAmortizeCost.getIsPublic());
        }

        //相关方
        if(Validator.isNotEmpty(cwAmortizeCost.getCustId())){
            queryWrapper.eq(CwAmortizeCost::getCustId,cwAmortizeCost.getCustId());
        }

        //相关方名称
        if(Validator.isNotEmpty(cwAmortizeCost.getCustName())){
            queryWrapper.eq(CwAmortizeCost::getCustName,cwAmortizeCost.getCustName());
        }

        //${column.columnComment}
        if(Validator.isNotEmpty(cwAmortizeCost.getRelId())){
            queryWrapper.eq(CwAmortizeCost::getRelId,cwAmortizeCost.getRelId());
        }

        //备注
        if(Validator.isNotEmpty(cwAmortizeCost.getRemark())){
            queryWrapper.eq(CwAmortizeCost::getRemark,cwAmortizeCost.getRemark());
        }

        //租户id
        if(Validator.isNotEmpty(cwAmortizeCost.getTenantId())){
            queryWrapper.eq(CwAmortizeCost::getTenantId,cwAmortizeCost.getTenantId());
        }

        //已核销金额
        if(Validator.isNotEmpty(cwAmortizeCost.getWriteoffCost())){
            queryWrapper.eq(CwAmortizeCost::getWriteoffCost,cwAmortizeCost.getWriteoffCost());
        }

        //开票金额
        if(Validator.isNotEmpty(cwAmortizeCost.getInvoiceCost())){
            queryWrapper.eq(CwAmortizeCost::getInvoiceCost,cwAmortizeCost.getInvoiceCost());
        }

        //锁定状态
        if(Validator.isNotEmpty(cwAmortizeCost.getLockStatus())){
            queryWrapper.eq(CwAmortizeCost::getLockStatus,cwAmortizeCost.getLockStatus());
        }

        //借贷方,0-借方,1-贷方
        if(Validator.isNotEmpty(cwAmortizeCost.getDrOrCr())){
            queryWrapper.eq(CwAmortizeCost::getDrOrCr,cwAmortizeCost.getDrOrCr());
        }

        //科目ID
        if(Validator.isNotEmpty(cwAmortizeCost.getSubjectId())){
            queryWrapper.eq(CwAmortizeCost::getSubjectId,cwAmortizeCost.getSubjectId());
        }

        //是否为预收付款,null/0-不是,1-预收款,2-预付款
        if(Validator.isNotEmpty(cwAmortizeCost.getAdvanceMoney())){
            queryWrapper.eq(CwAmortizeCost::getAdvanceMoney,cwAmortizeCost.getAdvanceMoney());
        }

        //价格类型
        if(Validator.isNotEmpty(cwAmortizeCost.getPriceType())){
            queryWrapper.eq(CwAmortizeCost::getPriceType,cwAmortizeCost.getPriceType());
        }

        //核销状态
        if(Validator.isNotEmpty(cwAmortizeCost.getWriteoffStatus())){
            queryWrapper.eq(CwAmortizeCost::getWriteoffStatus,cwAmortizeCost.getWriteoffStatus());
        }

        //原票原转凭证号
        if(Validator.isNotEmpty(cwAmortizeCost.getInvcTurnNo())){
            queryWrapper.eq(CwAmortizeCost::getInvcTurnNo,cwAmortizeCost.getInvcTurnNo());
        }

        //成本结转凭证号
        if(Validator.isNotEmpty(cwAmortizeCost.getCostSettleNo())){
            queryWrapper.eq(CwAmortizeCost::getCostSettleNo,cwAmortizeCost.getCostSettleNo());
        }

        //费用类型
        if(Validator.isNotEmpty(cwAmortizeCost.getItemType())){
            queryWrapper.eq(CwAmortizeCost::getItemType,cwAmortizeCost.getItemType());
        }

        //剩余量
        if(Validator.isNotEmpty(cwAmortizeCost.getRemainNum())){
            queryWrapper.eq(CwAmortizeCost::getRemainNum,cwAmortizeCost.getRemainNum());
        }

        //销售价格
        if(Validator.isNotEmpty(cwAmortizeCost.getSalePrice())){
            queryWrapper.eq(CwAmortizeCost::getSalePrice,cwAmortizeCost.getSalePrice());
        }

        //成本单价
        if(Validator.isNotEmpty(cwAmortizeCost.getCostPrice())){
            queryWrapper.eq(CwAmortizeCost::getCostPrice,cwAmortizeCost.getCostPrice());
        }

        //总成本
        if(Validator.isNotEmpty(cwAmortizeCost.getTotalCostPrice())){
            queryWrapper.eq(CwAmortizeCost::getTotalCostPrice,cwAmortizeCost.getTotalCostPrice());
        }

        //是否已收发票
        if(Validator.isNotEmpty(cwAmortizeCost.getReceiveInvoice())){
            queryWrapper.eq(CwAmortizeCost::getReceiveInvoice,cwAmortizeCost.getReceiveInvoice());
        }

        //创建人
        if(Validator.isNotEmpty(cwAmortizeCost.getCreateBy())){
            queryWrapper.eq(CwAmortizeCost::getCreateBy,cwAmortizeCost.getCreateBy());
        }

        //创建时间
        if(Validator.isNotEmpty(cwAmortizeCost.getCreateTime())){
            queryWrapper.eq(CwAmortizeCost::getCreateTime,cwAmortizeCost.getCreateTime());
        }

        //修改人
        if(Validator.isNotEmpty(cwAmortizeCost.getUpdateBy())){
            queryWrapper.eq(CwAmortizeCost::getUpdateBy,cwAmortizeCost.getUpdateBy());
        }

        //修改时间
        if(Validator.isNotEmpty(cwAmortizeCost.getUpdateTime())){
            queryWrapper.eq(CwAmortizeCost::getUpdateTime,cwAmortizeCost.getUpdateTime());
        }

        //删除标志（0代表存在 2代表删除）
        if(Validator.isNotEmpty(cwAmortizeCost.getDelFlag())){
            queryWrapper.eq(CwAmortizeCost::getDelFlag,cwAmortizeCost.getDelFlag());
        }

        }

}
