package com.xiaoniu.subsystem.business.controller;

import com.alibaba.nacos.common.utils.CollectionUtils;
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.PersonnelConfirm;
import com.xiaoniu.subsystem.business.domain.Sign;
import com.xiaoniu.subsystem.business.domain.dto.SignDTO;
import com.xiaoniu.subsystem.business.domain.dto.SignPageDTO;
import com.xiaoniu.subsystem.business.domain.vo.SignPageVO;
import com.xiaoniu.subsystem.business.service.ISignService;
import com.xiaoniu.subsystem.system.domain.Unit;
import com.xiaoniu.subsystem.system.service.IUnitService;
import io.jsonwebtoken.lang.Collections;
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 lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

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

/**
 * <p>
 * 签到表 前端控制器
 * </p>
 *
 * @author haoxuyang
 * @since 2024-12-23 05:36:11
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/Sign")
@Tag(name = "签到表", description = "签到")
public class SignController {
    private final IUnitService unitService;
    private final ISignService signService;


    /**
     * 分页
     */
    @GetMapping("/page")
    @ApiOperationSupport(order = 2)
    @Operation(summary = "分页", description = "传入SignPageDTO")
    public R<IPage<SignPageVO>> page(@Validated SignPageDTO dto) {
      IPage<Sign> pages = signService.page(new Page<>(dto.getPageNum(),dto.getPageSize()),
              new LambdaQueryWrapper<Sign>()
                      .orderByDesc(Sign::getCreateTime)
                      .eq(null != dto.getFlightId(),Sign::getFlightId,dto.getFlightId())
                      .eq(null != dto.getUserId(),Sign::getUserId,dto.getUserId())
                      .eq(null != dto.getUserId(),Sign::getUserId,dto.getUserId())
                      .eq(null != dto.getUserName(),Sign::getUserName,dto.getUserName())
                      .ge(null != dto.getSignDate1(),Sign::getSignDate,dto.getSignDate1())
                      .le(null != dto.getSignDate2(),Sign::getSignDate,dto.getSignDate2())
                      .eq(StringUtils.isNotBlank(dto.getYear()),Sign::getYear,dto.getYear())
                      .and(StringUtils.isNotBlank(dto.getStatus()),
                              qw -> qw.eq(Sign::getMorningStatus,dto.getStatus())
                                      .or()
                                      .eq(Sign::getAfternoonStatus,dto.getStatus())
                      )
      );
        IPage<SignPageVO> copy = BeanUtil.copy(pages, SignPageVO.class);
        return R.data(copy);
    }

    /*
    * 新增
    * */
    @PostMapping("/save")
    @ApiOperationSupport(order=4)
    @Operation(summary = "新增",description="传入SingDTO")
    public R save(@Validated @RequestBody SignDTO dto){
        Unit unit = unitService.getById(getUnitId());
        Sign copy = BeanUtil.copy(dto, Sign.class)
                .setCreateDept(unit.getCreateDept())
                .setCreateUser(getUserId())
                .setCreateTime(new Date());
        List<Sign> one = signService.list(new LambdaQueryWrapper<Sign>()
                .eq(Sign::getFlightId,dto.getFlightId())
                .eq(Sign::getUserId, dto.getUserId())
                .eq(Sign::getSignDate, dto.getSignDate())
        );
        if (CollectionUtils.isNotEmpty(one)){
            return R.fail("签到数据已存在");
        }
        return R.data(signService.save(copy));
    }

    /*
    * 修改
    * */
    @PostMapping("/update")
    @ApiOperationSupport(order = 5)
    @Operation(summary = "修改",description="传入SignDTO")
    public R update(@Validated @RequestBody SignDTO dto){
        Sign copy = BeanUtil.copy(dto, Sign.class)
                .setUpdateUser(getUserId())
                .setUpdateTime(new Date());
        return R.data(signService.updateById(copy));
    }

    /*
    * 删除
    * */
    @PostMapping("/remove")
    @ApiOperationSupport(order=7)
    @Operation(summary = "删除",description = "传入ids")
    public R remove(@Parameter(description = "主键集合",required = true) @RequestParam String ids){

        return R.data(signService.removeByIds(Arrays.stream(ids.split(",")).toList()));

    }


    /*
    * 导出
    * */
    @GetMapping("/export")
    @ApiOperationSupport(order = 3)
    @Log(title = "导出", businessType = BusinessType.EXPORT)
    @Operation(summary = "导出", description = "传入SignPageDTO")
    public void export(HttpServletResponse response,@Validated SignPageDTO dto){
        List<Sign> list = new ArrayList<>();
        if (StringUtils.isNotBlank(dto.getIds())){
            list.addAll(signService.list(new LambdaQueryWrapper<Sign>()
                    .orderByDesc(Sign::getCreateTime)
                    .in(StringUtils.isNotBlank(dto.getIds()),Sign::getSignId,dto.getIds())));
        }else{
            list.addAll(signService.list(new LambdaQueryWrapper<Sign>()
                    .eq(null != dto.getFlightId(),Sign::getFlightId,dto.getFlightId())
                    .eq(null != dto.getUserId(),Sign::getUserId,dto.getUserId())
                    .eq(null != dto.getUserName(),Sign::getUserName,dto.getUserName())
                    .ge(null != dto.getSignDate1(),Sign::getSignDate,dto.getSignDate1())
                    .le(null != dto.getSignDate2(),Sign::getSignDate,dto.getSignDate2())
                    .eq(StringUtils.isNotBlank(dto.getYear()),Sign::getYear,dto.getYear())
                    .and(StringUtils.isNotBlank(dto.getStatus()),
                            qw -> qw.eq(Sign::getMorningStatus,dto.getStatus())
                                    .or()
                                    .eq(Sign::getAfternoonStatus,dto.getStatus())
                    )
            ));
        }
        ExcelUtil<Sign> excelUtil = new ExcelUtil<>(Sign.class);
        excelUtil.exportExcel(response,list,"签到数据");
    }

    /*
    * 导入
    * */
    @PostMapping("/import")
    @Log(title = "考勤信息统计导入", businessType = BusinessType.IMPORT)
    @ApiOperationSupport(order = 9)
    public R importData(MultipartFile file,
                        @Parameter(description = "是否支持更新",required = true)
                        @RequestParam boolean updateSupport) throws Exception {
        ExcelUtil<Sign> excelUtil = new ExcelUtil<>(Sign.class);
        List<Sign> list = excelUtil.importExcel(file.getInputStream());
        return R.success(signService.importData(list,updateSupport));
    }

    /**
     * 模版导入
     */
    @GetMapping("/importTemplate")
    @ApiOperationSupport(order = 10)
    @Operation(summary = "导入模版下载")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<Sign> util = new ExcelUtil<>(Sign.class);
        util.importTemplateExcel(response, "签到导入模版");
    }



}
