/**
 * Copyright (c) 2018-2099, Chill Zhuang 庄骞 (bladejava@qq.com).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.xiaoniu.subsystem.business.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.xiaoniu.common.core.result.R;
import com.xiaoniu.common.core.utils.BeanUtil;
import com.xiaoniu.common.core.utils.poi.ExcelUtil;
import com.xiaoniu.common.log.annotation.Log;
import com.xiaoniu.common.log.enums.BusinessType;
import com.xiaoniu.subsystem.business.domain.AgreementContract;
import com.xiaoniu.subsystem.business.domain.dto.AgreementContractPageDTO;
import com.xiaoniu.subsystem.business.domain.dto.AgreementContractSaveDTO;
import com.xiaoniu.subsystem.business.domain.dto.AgreementContractUpdateDTO;
import com.xiaoniu.subsystem.business.domain.vo.AgreementContractVO;
import com.xiaoniu.subsystem.business.service.IAgreementContractService;
import com.xiaoniu.subsystem.system.domain.SysUser;
import com.xiaoniu.subsystem.system.service.ISysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

import static com.xiaoniu.common.security.utils.SecurityUtils.getUnitId;
import static com.xiaoniu.common.security.utils.SecurityUtils.getUserId;

/**
 * 协议/合同管理表 控制器
 *
 * @author sst
 * @since 2024-11-26
 */
@RestController
@AllArgsConstructor
@RequestMapping("/agreementcontract")
@Tag(name = "协议-合同管理表", description = "协议-合同管理表接口")
public class AgreementContractController {

    private IAgreementContractService agreementContractService;
    private ISysUserService userService;


    /**
     * 详情
     */
    @GetMapping("/detail")
    @ApiOperationSupport(order = 1)
    @Log(title = "协议-合同详情", businessType = BusinessType.OTHER)
    @Operation(summary = "详情", description = "传入agreementContract")
    public R<AgreementContractVO> detail(@Parameter(description = "主键", required = true) @RequestParam Long agreementContractId) {
        AgreementContract detail = agreementContractService.getById(agreementContractId);
        return R.data(BeanUtil.copy(detail, AgreementContractVO.class));
    }

    /**
     * 分页 协议/合同管理表
     */
    @GetMapping("/page")
    @ApiOperationSupport(order = 2)
    @Operation(summary = "分页", description = "传入agreementContract")
    public R<IPage<AgreementContractVO>> page(@Validated AgreementContractPageDTO dto) {
        IPage<AgreementContract> pages = agreementContractService.page(new Page<>(dto.getPageNum(), dto.getPageSize()),
                new LambdaQueryWrapper<AgreementContract>()
                        .orderByDesc(AgreementContract::getCreateTime)
                        .eq(dto.getFlightId() != null,AgreementContract::getFlightId,dto.getFlightId())
                        .eq(dto.getStatus() != null,AgreementContract::getStatus,dto.getStatus())
                        .eq(dto.getType() != null,AgreementContract::getType, dto.getType())
                        .eq(StringUtils.isNotBlank(dto.getYear()), AgreementContract::getYear, dto.getYear())
                        .like(StringUtils.isNotBlank(dto.getAgreementContractCode()),
                                AgreementContract::getAgreementContractCode, dto.getAgreementContractCode())
                        .like(StringUtils.isNotBlank(dto.getAgreementContractName()),
                                AgreementContract::getAgreementContractName, dto.getAgreementContractName()));
        IPage<AgreementContractVO> copy = BeanUtil.copy(pages, AgreementContractVO.class);
        if (CollectionUtils.isNotEmpty(pages.getRecords())) {
            List<SysUser> users = userService.listByIds(
                    pages.getRecords().stream().map(AgreementContract::getCreateUser).toList());
            Map<Long, String> map = users.stream()
                    .collect(Collectors.toMap(SysUser::getUserId, SysUser::getRealName));
            copy.setRecords(copy.getRecords().stream().peek(l ->
                    l.setCreateUserName(map.get(l.getCreateUser()))).toList());
        }
        return R.data(copy);
    }

    /**
     * 导出
     */
    @GetMapping("/export")
    @ApiOperationSupport(order = 3)
    @Log(title = "协议/合同导出", businessType = BusinessType.EXPORT)
    @Operation(summary = "导出", description = "传入ids")
    public void export(HttpServletResponse response, @Validated AgreementContractPageDTO dto) {
        List<AgreementContract> list = new ArrayList<>();
        if (StringUtils.isNotBlank(dto.getIds())) {
            list.addAll(agreementContractService.list(new LambdaQueryWrapper<AgreementContract>()
                    .orderByDesc(AgreementContract::getCreateTime)
                    .in(StringUtils.isNotBlank(dto.getIds()), AgreementContract::getAgreementContractId,
                            Arrays.stream(dto.getIds().split(",")).toList())));
        } else {
            list.addAll(agreementContractService.list(new LambdaQueryWrapper<AgreementContract>()
                    .orderByDesc(AgreementContract::getCreateTime)
                    .eq(dto.getFlightId() != null,AgreementContract::getFlightId,dto.getFlightId())
                    .eq(AgreementContract::getType, dto.getType())
                    .eq(StringUtils.isNotBlank(dto.getYear()), AgreementContract::getYear, dto.getYear())
                    .like(StringUtils.isNotBlank(dto.getAgreementContractCode()),
                            AgreementContract::getAgreementContractCode, dto.getAgreementContractCode())
                    .like(StringUtils.isNotBlank(dto.getAgreementContractName()),
                            AgreementContract::getAgreementContractName, dto.getAgreementContractName())));
        }
        ExcelUtil<AgreementContract> excelUtil = new ExcelUtil<>(AgreementContract.class);
        excelUtil.exportExcel(response, list, (0 == dto.getType() ? "协议数据" : "合同数据"));
    }

    /**
     * 新增 协议/合同管理表
     */
    @PostMapping("/save")
    @ApiOperationSupport(order = 4)
    @Operation(summary = "新增", description = "传入agreementContract")
    public R save(@Valid @RequestBody AgreementContractSaveDTO dto) {
        return R.status(agreementContractService.save(Objects.requireNonNull(BeanUtil.copy(dto, AgreementContract.class))
                .setYear(String.valueOf(LocalDate.now().getYear()))
                .setCreateDept(getUnitId()).setCreateUser(getUserId()).setCreateTime(new Date())));
    }

    /**
     * 修改 协议/合同管理表
     */
    @PostMapping("/update")
    @ApiOperationSupport(order = 5)
    @Operation(summary = "修改", description = "传入agreementContract")
    public R update(@Valid @RequestBody AgreementContractUpdateDTO dto) {
        return R.status(agreementContractService.updateById(Objects.requireNonNull(BeanUtil.copy(dto, AgreementContract.class))
                .setUpdateUser(getUserId()).setUpdateTime(new Date())));
    }

    // /**
    //  * 新增或修改 协议/合同管理表
    //  */
    // @PostMapping("/submit")
    // @ApiOperationSupport(order = 6)
    // @Operation(summary = "新增或修改", description = "传入agreementContract")
    // public R submit(@Valid @RequestBody AgreementContractDTO agreementContract) {
    //     return R.status(agreementContractService.saveOrUpdate(agreementContract));
    // }


    /**
     * 删除 协议/合同管理表
     */
    @PostMapping("/remove")
    @ApiOperationSupport(order = 7)
    @Operation(summary = "删除", description = "传入ids")
    public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String agreementContractIds) {
        return R.status(agreementContractService.removeByIds(Arrays.stream(agreementContractIds.split(",")).toList()));
    }


}
