package cn.iocoder.yudao.module.system.controller.admin.hr;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.infra.api.file.FileApi;
import cn.iocoder.yudao.module.system.controller.admin.hr.vo.payslip.*;
import cn.iocoder.yudao.module.system.service.hr.payslip.PayslipService;
import com.alibaba.excel.EasyExcel;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Tag(name = "管理后台 - 工资条")
@RestController
@RequestMapping("/system/hr/payslip")
public class PayslipController {

    @Resource
    private PayslipService payslipService;

    @Resource
    private FileApi fileApi;

    @PostMapping("/create")
    @Operation(summary = "创建工资条")
    @PreAuthorize("@ss.hasPermission('system:hr:payslip:create')")
    public CommonResult<Boolean> createPayslip(@Valid List<PayslipCreateReqVO> createReqVO) {
        payslipService.createPayslip(createReqVO);
        return success(true);
    }

    @PutMapping("/issued")
    @Operation(summary = "下发工资条")
    @PreAuthorize("@ss.hasPermission('system:hr:payslip:update')")
    public CommonResult<Boolean> updatePayslip(@RequestBody PayslipPageReqVO updateReqVO) {
        payslipService.issuedPayslip(updateReqVO);
        return success(true);
    }

    @PutMapping("/update")
    @Operation(summary = "更新工资条")
    @PreAuthorize("@ss.hasPermission('system:hr:payslip:update')")
    public CommonResult<Boolean> updatePayslip(@RequestBody PayslipCreateReqVO updateReqVO) {
        payslipService.updatePayslip(updateReqVO);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得工资条")
    @Parameter(name = "id", description = "编号", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('system:hr:payslip:query')")
    public CommonResult<PayslipRespVO> getPayslip(@RequestParam("id") Long id) {

        PayslipRespVO data = BeanUtils.toBean(payslipService.getPayslip(id), PayslipRespVO.class);
        List<PayslipDetail> details = data.getDetails();
        // 设置实发工资
        details.add(new PayslipDetail()
                .setCode("salary")
                .setName("实发工资")
                .setValue(data.getSalary()));

        // 设置开户行
        details.add(new PayslipDetail()
                .setCode("bankName")
                .setName("开户行")
                .setValue(data.getBankName()));

        // 设置银行卡号
        details.add(new PayslipDetail()
                .setCode("bankNo")
                .setName("卡号")
                .setValue(data.getBankNo()));

        // 设置备注
        details.add(new PayslipDetail()
                .setCode("remark")
                .setName("备注")
                .setValue(data.getRemark()));

        if (data.getIsConfirm() != null && data.getIsConfirm() == 1) {
            data.setSignURL(fileApi.getUserSignImgPath(data.getUserId()).getData());
        }

        // 设置签名
        details.add(new PayslipDetail()
                .setCode("signURL")
                .setName("签名")
                .setValue(data.getSignURL()));
        data.setDetails(details);

        return success(data);
    }

    @PostMapping("/Page")
    @Operation(summary = "获得工资条分页")
    @Parameter(name = "id", description = "编号", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('system:hr:payslip:query')")
    public CommonResult<PageResult<PayslipRespVO>> getPage(@RequestBody PayslipPageReqVO pageReqVO) {

        PageResult<PayslipRespVO> pageResult = BeanUtils.toBean(payslipService.getPage(pageReqVO), PayslipRespVO.class);
        pageResult.getList().forEach(data -> {
            List<PayslipDetail> details = data.getDetails();
            // 设置实发工资
            details.add(new PayslipDetail()
                    .setCode("salary")
                    .setName("实发工资")
                    .setValue(data.getSalary()));

            // 设置开户行
            details.add(new PayslipDetail()
                    .setCode("bankName")
                    .setName("开户行")
                    .setValue(data.getBankName()));

            // 设置银行卡号
            details.add(new PayslipDetail()
                    .setCode("bankNo")
                    .setName("卡号")
                    .setValue(data.getBankNo()));

            // 设置备注
            details.add(new PayslipDetail()
                    .setCode("remark")
                    .setName("备注")
                    .setValue(data.getRemark()));

            if (data.getIsConfirm() != null && data.getIsConfirm() == 1) {
                data.setSignURL(fileApi.getUserSignImgPath(data.getUserId()).getData());
            }

            // 设置签名
            details.add(new PayslipDetail()
                    .setCode("signURL")
                    .setName("签名")
                    .setValue(data.getSignURL()));
            data.setDetails(details);
        });
        return success(pageResult);
    }

    @PostMapping("/myPage")
    @Operation(summary = "获得当前登录用户的工资条分页")
    @Parameter(name = "id", description = "编号", required = true, example = "1")
    @PreAuthorize("@ss.hasPermission('system:hr:payslip:query')")
    public CommonResult<PageResult<PayslipRespVO>> getMyPage(@RequestBody PayslipPageReqVO pageReqVO) {

        PageResult<PayslipRespVO> pageResult = BeanUtils.toBean(payslipService.getMyPage(pageReqVO), PayslipRespVO.class);

        // 获取电子签名Map
        Map<Long, String> signImgPathMap = fileApi.getUserSignImgPathMap(convertList(pageResult.getList(), PayslipRespVO::getUserId)).getCheckedData();

        pageResult.getList().forEach(data -> {
            List<PayslipDetail> details = data.getDetails();
            // 设置实发工资
            details.add(new PayslipDetail()
                    .setCode("salary")
                    .setName("实发工资")
                    .setValue(data.getSalary()));

            // 设置开户行
            details.add(new PayslipDetail()
                    .setCode("bankName")
                    .setName("开户行")
                    .setValue(data.getBankName()));

            // 设置银行卡号
            details.add(new PayslipDetail()
                    .setCode("bankNo")
                    .setName("卡号")
                    .setValue(data.getBankNo()));

            // 设置备注
            details.add(new PayslipDetail()
                    .setCode("remark")
                    .setName("备注")
                    .setValue(data.getRemark()));

            if (data.getIsConfirm() == 1) {
                data.setSignURL(signImgPathMap.get(data.getUserId()));
            }

            // 设置签名
            details.add(new PayslipDetail()
                    .setCode("signURL")
                    .setName("签名")
                    .setValue(data.getSignURL()));
            data.setDetails(details);
        });
        return success(pageResult);
    }

    @PostMapping("/import")
    @Operation(summary = "导入工资条")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true),
            @Parameter(name = "date", description = "日期", required = true),
            @Parameter(name = "deptId", description = "公司编号", required = true),
            @Parameter(name = "companyName", description = "公司名称", required = true),
            @Parameter(name = "isUpdate", description = "是否允许覆盖", required = true)
    })
    @PreAuthorize("@ss.hasPermission('system:hr:payslip:import')")
    public CommonResult<Boolean> importExcel(@RequestParam("file") MultipartFile file,
                                             @RequestParam("date") String date,
                                             @RequestParam("deptId") Long deptId,
                                             @RequestParam("companyName") String companyName,
                                             @RequestParam("isUpdate") Boolean isUpdate) throws Exception {

        List<PayslipImportExcelVO> list = EasyExcel.read(file.getInputStream(), PayslipImportExcelVO.class, null)
                .headRowNumber(3)
                .autoCloseStream(false)  // 不要自动关闭，交给 Servlet 自己处理
                .doReadAllSync();
        // 导入数据
        payslipService.importPayslip(list, date, deptId, companyName, isUpdate);
        return success(true);
    }

    @GetMapping("/export")
    @Operation(summary = "导出工资条")
    @PreAuthorize("@ss.hasPermission('system:user:export')")
    @OperateLog(type = EXPORT)
    public void exportList(@Validated PayslipPageReqVO exportReqVO,
                               HttpServletResponse response) throws IOException {
        exportReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);

        payslipService.exportList(response, exportReqVO);
    }
}
