package com.gxwebsoft.tower.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.Company;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.tower.entity.*;
import com.gxwebsoft.tower.service.TowerContractService;
import com.gxwebsoft.tower.service.TowerIncomeService;
import com.gxwebsoft.tower.param.TowerIncomeParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 收款管理控制器
 *
 * @author 科技小王子
 * @since 2023-06-17 16:56:18
 */
@Api(tags = "收款管理管理")
@RestController
@RequestMapping("/api/tower/tower-income")
public class TowerIncomeController extends BaseController {
    @Resource
    private TowerIncomeService towerIncomeService;
    @Resource
    private TowerContractService towerContractService;

    @PreAuthorize("hasAuthority('tower:towerIncome:list')")
    @OperationLog
    @ApiOperation("分页查询收款管理")
    @GetMapping("/page")
    public ApiResult<PageResult<TowerIncome>> page(TowerIncomeParam param) {
        MPJLambdaWrapper<TowerIncome> wrapper = new MPJLambdaWrapper<>();
        wrapper.selectAll(TowerIncome.class)
                .select(TowerContract::getContactNumber)
                .select(TowerContract::getTotalInvoicingAmount)
                .select(TowerContract::getTotalIncomeAmount)
                .select(TowerProject::getProjectName)
                .selectAs(TowerCustomer::getName, TowerCustomer::getCustomerName)
                .selectAs(Company::getCompanyName, Company::getIncomeCompanyName)
                .leftJoin(TowerContract.class, TowerContract::getContractId, TowerIncome::getContractId)
                .leftJoin(TowerProject.class, TowerProject::getProjectId, TowerContract::getProjectId)
                .leftJoin(TowerCustomer.class, TowerCustomer::getCustomerId, TowerContract::getCustomerId)
                .leftJoin(Company.class, Company::getCompanyId, TowerIncome::getIncomeCompanyId);

        PageParam<TowerIncome, TowerIncomeParam> page = new PageParam<>(param);
        page.setDefaultOrder("create_time desc");
        return success(towerIncomeService.page(page, page.getWrapper()));
        // 使用关联查询
        //return success(towerIncomeService.pageRel(param));
    }

    @PreAuthorize("hasAuthority('tower:towerIncome:list')")
    @OperationLog
    @ApiOperation("查询全部收款管理")
    @GetMapping()
    public ApiResult<List<TowerIncome>> list(TowerIncomeParam param) {
        PageParam<TowerIncome, TowerIncomeParam> page = new PageParam<>(param);
        page.setDefaultOrder("create_time desc");
        return success(towerIncomeService.list(page.getOrderWrapper()));
        // 使用关联查询
        //return success(towerIncomeService.listRel(param));
    }

    @PreAuthorize("hasAuthority('tower:towerIncome:list')")
    @OperationLog
    @ApiOperation("根据id查询收款管理")
    @GetMapping("/{id}")
    public ApiResult<TowerIncome> get(@PathVariable("id") Integer id) {
        return success(towerIncomeService.getById(id));
        // 使用关联查询
        //return success(towerIncomeService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('tower:towerIncome:save')")
    @OperationLog
    @ApiOperation("添加收款管理")
    @PostMapping()
    public ApiResult<?> save(@RequestBody TowerIncome towerIncome) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
            towerIncome.setUserId(loginUser.getUserId());
        }
        if (towerIncomeService.save(towerIncome)) {
            reCalIncome(towerIncome.getContractId());
            return success(towerIncome.getIncomeId());
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('tower:towerIncome:update')")
    @OperationLog
    @ApiOperation("修改收款管理")
    @PutMapping()
    public ApiResult<?> update(@RequestBody TowerIncome towerIncome) {
        if (towerIncomeService.updateById(towerIncome)) {
            reCalIncome(towerIncome.getContractId());
            return success(towerIncome.getIncomeId());
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('tower:towerIncome:remove')")
    @OperationLog
    @ApiOperation("删除收款管理")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        int contractId = towerIncomeService.getById(id).getContractId();
        if (towerIncomeService.removeById(id)) {
            reCalIncome(contractId);
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('tower:towerIncome:save')")
    @OperationLog
    @ApiOperation("批量添加收款管理")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<TowerIncome> list) {
        if (towerIncomeService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('tower:towerIncome:update')")
    @OperationLog
    @ApiOperation("批量修改收款管理")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<TowerIncome> batchParam) {
        if (batchParam.update(towerIncomeService, "income_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('tower:towerIncome:remove')")
    @OperationLog
    @ApiOperation("批量删除收款管理")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        List<Integer> contractIdList = new ArrayList<>();
        for (int id : ids) {
            int contractId = towerIncomeService.getById(id).getContractId();
            if (!contractIdList.contains(contractId)) {
                contractIdList.add(contractId);
            }
        }
        if (towerIncomeService.removeByIds(ids)) {
            for (int contractId : contractIdList) {
                this.reCalIncome(contractId);
            }
            return success("删除成功");
        }
        return fail("删除失败");
    }

    private void reCalIncome(int contractId) {
        QueryWrapper<TowerIncome> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("contract_id", contractId)
                .select("sum(`amount`) as `total_income_amount`");
        TowerIncome towerIncomeAll = towerIncomeService.getOne(queryWrapper);

        LambdaUpdateWrapper<TowerContract> updateWrapper = new LambdaUpdateWrapper<>();
        BigDecimal totalIncomeAmount;
        if (towerIncomeAll != null) {
            totalIncomeAmount = towerIncomeAll.getTotalIncomeAmount();
        } else {
            totalIncomeAmount = BigDecimal.valueOf(0);
        }
        updateWrapper.eq(TowerContract::getContractId, contractId)
                .set(TowerContract::getTotalIncomeAmount, totalIncomeAmount);
        towerContractService.update(updateWrapper);
    }

}
