package com.gxwebsoft.tower.controller;

import com.alipay.api.domain.AlipayCommerceLogisticsWaybillIstddetailQueryModel;
import com.alipay.api.domain.Contract;
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.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.tower.entity.TowerContract;
import com.gxwebsoft.tower.entity.TowerSettle;
import com.gxwebsoft.tower.service.TowerContractService;
import com.gxwebsoft.tower.service.TowerContractSettleEquipmentService;
import com.gxwebsoft.tower.service.TowerSettleDetailService;
import com.gxwebsoft.tower.entity.TowerSettleDetail;
import com.gxwebsoft.tower.param.TowerSettleDetailParam;
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.TowerSettleService;
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.math.RoundingMode;
import java.util.List;

/**
 * 合同结算详情控制器
 *
 * @author 科技小王子
 * @since 2023-06-11 19:13:12
 */
@Api(tags = "合同结算详情管理")
@RestController
@RequestMapping("/api/tower/tower-settle-detail")
public class TowerSettleDetailController extends BaseController {
    @Resource
    private TowerSettleDetailService towerSettleDetailService;
    @Resource
    private TowerContractService towerContractService;
    @Resource
    private TowerSettleService towerSettleService;

    @PreAuthorize("hasAuthority('tower:towerSettle:list')")
    @OperationLog
    @ApiOperation("分页查询合同结算详情")
    @GetMapping("/page")
    public ApiResult<PageResult<TowerSettleDetail>> page(TowerSettleDetailParam param) {
        PageParam<TowerSettleDetail, TowerSettleDetailParam> page = new PageParam<>(param);
        page.setDefaultOrder("create_time desc");
        return success(towerSettleDetailService.page(page, page.getWrapper()));
        // 使用关联查询
        //return success(towerSettleDetailService.pageRel(param));
    }

    @PreAuthorize("hasAuthority('tower:towerSettle:list')")
    @OperationLog
    @ApiOperation("查询全部合同结算详情")
    @GetMapping()
    public ApiResult<List<TowerSettleDetail>> list(TowerSettleDetailParam param) {
        PageParam<TowerSettleDetail, TowerSettleDetailParam> page = new PageParam<>(param);
        page.setDefaultOrder("create_time desc");
        return success(towerSettleDetailService.list(page.getOrderWrapper()));
        // 使用关联查询
        //return success(towerSettleDetailService.listRel(param));
    }

    @PreAuthorize("hasAuthority('tower:towerSettle:list')")
    @OperationLog
    @ApiOperation("根据id查询合同结算详情")
    @GetMapping("/{id}")
    public ApiResult<TowerSettleDetail> get(@PathVariable("id") Integer id) {
        return success(towerSettleDetailService.getById(id));
        // 使用关联查询
        //return success(towerSettleDetailService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('tower:towerSettle:save')")
    @OperationLog
    @ApiOperation("添加合同结算详情")
    @PostMapping()
    public ApiResult<?> save(@RequestBody TowerSettleDetail towerSettleDetail) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
            towerSettleDetail.setUserId(loginUser.getUserId());
        }
        if (towerSettleDetailService.save(towerSettleDetail)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('tower:towerSettle:update')")
    @OperationLog
    @ApiOperation("修改合同结算详情")
    @PutMapping()
    public ApiResult<?> update(@RequestBody TowerSettleDetail towerSettleDetail) {
        if (towerSettleDetailService.updateById(towerSettleDetail)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('tower:towerSettle:remove')")
    @OperationLog
    @ApiOperation("删除合同结算详情")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (towerSettleDetailService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('tower:towerSettle:save')")
    @OperationLog
    @ApiOperation("批量添加合同结算详情")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<TowerSettleDetail> list) {
        Integer settleId = list.get(0).getSettleId();
        LambdaUpdateWrapper<TowerSettleDetail> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(TowerSettleDetail::getSettleId, settleId)
                .set(TowerSettleDetail::getDeleted, 1);
        towerSettleDetailService.update(lambdaUpdateWrapper);
        if (towerSettleDetailService.saveBatch(list)) {
            setSettleAmount(settleId);
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('tower:towerSettle:update')")
    @OperationLog
    @ApiOperation("批量修改合同结算详情")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<TowerSettleDetail> batchParam) {
        if (batchParam.update(towerSettleDetailService, "settle_detail_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    private void setSettleAmount(Integer settleId) {
        List<TowerSettleDetail> list = towerSettleDetailService.list(
                new LambdaQueryWrapper<TowerSettleDetail>().eq(TowerSettleDetail::getSettleId, settleId)
        );
        BigDecimal totalSettleAmount = BigDecimal.valueOf(0);
        for (TowerSettleDetail towerSettleDetail : list) {
            if (towerSettleDetail.getType().equals(0) || towerSettleDetail.getType().equals(2)) {
                BigDecimal monthAmount = towerSettleDetail.getMonthAmount().multiply(BigDecimal.valueOf(towerSettleDetail.getMonth()));
                BigDecimal dayAmount = towerSettleDetail.getDailyAmount().multiply(BigDecimal.valueOf(towerSettleDetail.getDay()));
                totalSettleAmount = totalSettleAmount.add(monthAmount).add(dayAmount).multiply(towerSettleDetail.getPayRate().divide(BigDecimal.valueOf(100), RoundingMode.FLOOR));
            } else if (towerSettleDetail.getType().equals(1) || towerSettleDetail.getType().equals(3)) {
                BigDecimal amount = towerSettleDetail.getSingleAmount().multiply(BigDecimal.valueOf(towerSettleDetail.getNum()));
                totalSettleAmount = totalSettleAmount.add(amount).divide(BigDecimal.valueOf(100), RoundingMode.FLOOR);
            } else if (towerSettleDetail.getType().equals(4)) {
                BigDecimal amount = towerSettleDetail.getSingleAmount().multiply(BigDecimal.valueOf(towerSettleDetail.getNum()));
                totalSettleAmount = totalSettleAmount.subtract(amount).divide(BigDecimal.valueOf(100), RoundingMode.FLOOR);
            }
        }
        TowerSettle towerSettle = towerSettleService.getByIdRel(list.get(0).getSettleId());
        TowerContract contract = towerContractService.getById(towerSettle.getContractId());
        contract.setTotalSettleAmount(totalSettleAmount);
        System.out.println("totalSettleAmount: " + totalSettleAmount);
        towerContractService.updateById(contract);
    }

    @PreAuthorize("hasAuthority('tower:towerSettle:remove')")
    @OperationLog
    @ApiOperation("批量删除合同结算详情")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (towerSettleDetailService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

}
