package com.gxwebsoft.tower.controller;

import com.alipay.api.domain.Contract;
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.TowerContract;
import com.gxwebsoft.tower.entity.TowerCustomer;
import com.gxwebsoft.tower.entity.TowerProject;
import com.gxwebsoft.tower.mapper.TowerContractMapper;
import com.gxwebsoft.tower.service.TowerContractService;
import com.gxwebsoft.tower.service.TowerInvoicingService;
import com.gxwebsoft.tower.entity.TowerInvoicing;
import com.gxwebsoft.tower.param.TowerInvoicingParam;
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 com.gxwebsoft.tower.service.impl.TowerContractServiceImpl;
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.util.List;

/**
 * 开票管理控制器
 *
 * @author 科技小王子
 * @since 2023-06-17 12:47:08
 */
@Api(tags = "开票管理管理")
@RestController
@RequestMapping("/api/tower/tower-invoicing")
public class TowerInvoicingController extends BaseController {
    @Resource
    private TowerInvoicingService towerInvoicingService;
    @Resource
    private TowerContractService towerContractService;

    @PreAuthorize("hasAuthority('tower:towerInvoicing:list')")
    @OperationLog
    @ApiOperation("分页查询开票管理")
    @GetMapping("/page")
    public ApiResult<PageResult<TowerInvoicing>> page(TowerInvoicingParam param) {
        MPJLambdaWrapper<TowerInvoicing> wrapper = new MPJLambdaWrapper<>();
        wrapper.selectAll(TowerInvoicing.class)
                .select(TowerContract::getContactNumber)
                .select(TowerContract::getSignDate)
                .select(TowerContract::getTotalInvoicingAmount)
                .select(TowerProject::getProjectName)
                .selectAs(TowerCustomer::getName, TowerCustomer::getCustomerName)
                .select(Company::getCompanyName)
                .leftJoin(TowerContract.class, TowerContract::getContractId, TowerInvoicing::getContractId)
                .leftJoin(TowerProject.class, TowerProject::getProjectId, TowerContract::getProjectId)
                .leftJoin(TowerCustomer.class, TowerCustomer::getCustomerId, TowerContract::getCustomerId)
                .leftJoin(Company.class, Company::getCompanyId, TowerContract::getCompanyId);
        PageParam<TowerInvoicing, TowerInvoicingParam> page = new PageParam<>(param);
        page.setDefaultOrder("create_time desc");
        return success(towerInvoicingService.page(page, wrapper));
        // 使用关联查询
        //return success(towerInvoicingService.pageRel(param));
    }

    @PreAuthorize("hasAuthority('tower:towerInvoicing:list')")
    @OperationLog
    @ApiOperation("查询全部开票管理")
    @GetMapping()
    public ApiResult<List<TowerInvoicing>> list(TowerInvoicingParam param) {
        MPJLambdaWrapper<TowerInvoicing> wrapper = new MPJLambdaWrapper<>();
        wrapper.selectAll(TowerInvoicing.class)
                .selectAs(TowerContract::getContactNumber, TowerContract::getContractNumber)
                .select(TowerContract::getContactNumber)
                .select(TowerContract::getSignDate)
                .select(TowerContract::getTotalInvoicingAmount)
                .select(TowerProject::getProjectName)
                .selectAs(TowerCustomer::getName, TowerCustomer::getCustomerName)
                .select(Company::getCompanyName)
                .leftJoin(TowerContract.class, TowerContract::getContractId, TowerInvoicing::getContractId)
                .leftJoin(TowerProject.class, TowerProject::getProjectId, TowerContract::getProjectId)
                .leftJoin(TowerCustomer.class, TowerCustomer::getCustomerId, TowerContract::getCustomerId)
                .leftJoin(Company.class, Company::getCompanyId, TowerContract::getCompanyId);

        PageParam<TowerInvoicing, TowerInvoicingParam> page = new PageParam<>(param);
        page.setDefaultOrder("create_time desc");
        return success(towerInvoicingService.list(wrapper));
        // 使用关联查询
        //return success(towerInvoicingService.listRel(param));
    }

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

    @PreAuthorize("hasAuthority('tower:towerInvoicing:save')")
    @OperationLog
    @ApiOperation("添加开票管理")
    @PostMapping()
    public ApiResult<?> save(@RequestBody TowerInvoicing towerInvoicing) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
            towerInvoicing.setUserId(loginUser.getUserId());
        }
        if (towerInvoicingService.save(towerInvoicing)) {
            LambdaUpdateWrapper<TowerContract> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(TowerContract::getContractId, towerInvoicing.getContractId())
                    .setSql("`total_invoicing_amount` = `total_invoicing_amount` + " + towerInvoicing.getInvoicingAmount());
            towerContractService.update(null, updateWrapper);
            return success(towerInvoicing.getInvoicingId());
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('tower:towerInvoicing:update')")
    @OperationLog
    @ApiOperation("修改开票管理")
    @PutMapping()
    public ApiResult<?> update(@RequestBody TowerInvoicing towerInvoicing) {
        if (towerInvoicingService.updateById(towerInvoicing)) {
            QueryWrapper<TowerInvoicing> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("contract_id", towerInvoicing.getContractId())
                    .select("SUM(`invoicing_amount`) as `total_invoicing_amount`");
            TowerInvoicing towerInvoicingAll = towerInvoicingService.getOne(queryWrapper);

            LambdaUpdateWrapper<TowerContract> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(TowerContract::getContractId, towerInvoicing.getContractId());
            updateWrapper.set(TowerContract::getTotalInvoicingAmount, towerInvoicingAll.getTotalInvoicingAmount());
            towerContractService.update(null, updateWrapper);
            return success(towerInvoicing.getInvoicingId());
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('tower:towerInvoicing:remove')")
    @OperationLog
    @ApiOperation("删除开票管理")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (towerInvoicingService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

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

    @PreAuthorize("hasAuthority('tower:towerInvoicing:update')")
    @OperationLog
    @ApiOperation("批量修改开票管理")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<TowerInvoicing> batchParam) {
        if (batchParam.update(towerInvoicingService, "invoicing_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('tower:towerInvoicing:remove')")
    @OperationLog
    @ApiOperation("批量删除开票管理")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (towerInvoicingService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

}
