/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the yifu4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.yifu.cloud.plus.v1.yifu.salary.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.OSSUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.MenuUtil;
import com.yifu.cloud.plus.v1.yifu.common.log.annotation.SysLog;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TSalaryStandardOriginal;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TSalaryStandardOriginalDetail;
import com.yifu.cloud.plus.v1.yifu.salary.service.TSalaryStandardOriginalDetailService;
import com.yifu.cloud.plus.v1.yifu.salary.service.TSalaryStandardOriginalService;
import com.yifu.cloud.plus.v1.yifu.salary.vo.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URL;
import java.util.List;


/**
 * 薪资原表识别导入
 *
 * @author hgw
 * @date 2024-4-2 11:03:33
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/tsalarystandardoriginal")
@Tag(name = "薪资原表识别导入")
public class TSalaryStandardOriginalController {

	private final TSalaryStandardOriginalService tSalaryStandardOriginalService;
	private final TSalaryStandardOriginalDetailService tSalaryStandardOriginalDetailService;
	private final MenuUtil menuUtil;
	private final OSSUtil ossUtil;

	/**
	 * 简单分页查询
	 *
	 * @param page                    分页对象
	 * @param tSalaryStandardOriginal 原表识别
	 * @return
	 */
	@Operation(description = "简单分页查询")
	@GetMapping("/page")
	public R<IPage<TSalaryStandardOriginal>> getTSalaryStandardOriginalPage(Page<TSalaryStandardOriginal> page, TSalaryStandardOriginal tSalaryStandardOriginal) {
		YifuUser user = SecurityUtils.getUser();
		menuUtil.setAuthSql(user, tSalaryStandardOriginal);
		return new R<>(tSalaryStandardOriginalService.getTSalaryStandardOriginalPage(page, tSalaryStandardOriginal));
	}

	/**
	 * 导入工资时的获取识别配置列表
	 */
	@Operation(description = "导入工资时的获取识别配置列表")
	@GetMapping("/getTSalaryStandardOriginalList")
	public R<List<TSalaryStandardOriginal>> getTSalaryStandardOriginalList(TSalaryStandardOriginal tSalaryStandardOriginal) {
		YifuUser user = SecurityUtils.getUser();
		menuUtil.setAuthSql(user, tSalaryStandardOriginal);
		return new R<>(tSalaryStandardOriginalService.getTSalaryStandardOriginalList(tSalaryStandardOriginal));
	}

	/**
	 * 通过id查询薪资原表识别
	 *
	 * @param id id
	 * @return R
	 */
	@Operation(summary = "通过id查询", description = "通过id查询：hasPermission('salary_tsalarystandardoriginal_get')")
	@GetMapping("/{id}")
	public R<TSalaryStandardOriginal> getById(@PathVariable("id") String id) {
		TSalaryStandardOriginal original = tSalaryStandardOriginalService.getById(id);
		if (original != null && Common.isNotNull(original.getId())) {
			if (Common.isNotNull(original.getAttaSrc())) {
				URL url = ossUtil.getObjectUrl(null, original.getAttaSrc());
				original.setAttaUrl(url.toString().replace("http", "https"));
			}
			original.setDetailList(tSalaryStandardOriginalDetailService.getTSalaryStandardOriginalDetailByOrgId(original.getId()));
		}
		return R.ok(original);
	}

	/**
	 * 修改
	 *
	 * @param tSalaryStandardOriginal
	 * @return R
	 */
	@Operation(summary = "修改薪资原表识别", description = "修改薪资原表识别：hasPermission('salary_tsalarystandardoriginal_edit')")
	@SysLog("修改薪资原表识别")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('salary_tsalarystandardoriginal_edit')")
	@Transactional
	public R<Boolean> updateById(@RequestBody TSalaryStandardOriginal tSalaryStandardOriginal) {

		if (Common.isNotNull(tSalaryStandardOriginal.getId())
				&& Common.isNotNull(tSalaryStandardOriginal.getDeptId())
				&& Common.isNotNull(tSalaryStandardOriginal.getSetName())) {
			List<TSalaryStandardOriginalDetail> detailList = tSalaryStandardOriginal.getDetailList();
			if (detailList == null || detailList.isEmpty()) {
				return R.failed("请传配置表头list");
			}
			// 判重
			TSalaryStandardOriginal isCur = new TSalaryStandardOriginal();
			isCur.setId(tSalaryStandardOriginal.getId());
			isCur.setDeptId(tSalaryStandardOriginal.getDeptId());
			isCur.setSetName(tSalaryStandardOriginal.getSetName());
			List<TSalaryStandardOriginal> curList = tSalaryStandardOriginalService.getTSalaryStandardOriginalList(isCur);
			if (curList != null && !curList.isEmpty()) {
				return R.failed("该项目下已存在此原表类型，请修改！");
			}
			// 先删除关系
			tSalaryStandardOriginalDetailService.deleteByOrgId(tSalaryStandardOriginal.getId());
			for (TSalaryStandardOriginalDetail detail : detailList) {
				detail.setOriginalId(tSalaryStandardOriginal.getId());
			}
			// 再新增权限
			tSalaryStandardOriginalDetailService.saveBatch(detailList);
			// 再保存
			tSalaryStandardOriginalService.updateById(tSalaryStandardOriginal);
			return R.ok(true);
		} else {
			return R.failed("请传参！");
		}
	}

	/**
	 * 通过id删除薪资原表识别
	 *
	 * @param id id
	 * @return R
	 */
	@Operation(summary = "通过id删除薪资原表识别", description = "通过id删除薪资原表识别：hasPermission('salary_tsalarystandardoriginal_del')")
	@SysLog("通过id删除薪资原表识别")
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('salary_tsalarystandardoriginal_del')")
	public R<String> removeById(@PathVariable String id) {
		TSalaryStandardOriginal original = tSalaryStandardOriginalService.getById(id);
		if (original != null && Common.isNotNull(original.getId())) {
			original.setDeleteFlag(CommonConstants.ONE_INT);
			tSalaryStandardOriginalService.updateById(original);
			return R.ok();
		} else {
			return R.failed("未找到");
		}
	}

	/**
	 * @param file
	 * @param tSalaryStandardOriginal
	 * @Description: 原表识别配置保存
	 * @Author: hgw
	 * @Date: 2024/4/2 18:02
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	@SysLog("原表识别配置新增")
	@Operation(description = "新增")
	@PostMapping("/doSave")
	public R<String> doSave(MultipartFile file, TSalaryStandardOriginal tSalaryStandardOriginal) throws Exception {

		if (tSalaryStandardOriginal != null && Common.isNotNull(tSalaryStandardOriginal.getDeptId())
				&& Common.isNotNull(tSalaryStandardOriginal.getSetName()) && file != null) {
			List<TSalaryStandardOriginalDetail> detailList = tSalaryStandardOriginal.getDetailList();
			if (detailList == null || detailList.isEmpty()) {
				return R.failed("请传配置表头list");
			}

			// 判重
			TSalaryStandardOriginal isCur = new TSalaryStandardOriginal();
			isCur.setDeptId(tSalaryStandardOriginal.getDeptId());
			isCur.setSetName(tSalaryStandardOriginal.getSetName());
			List<TSalaryStandardOriginal> curList = tSalaryStandardOriginalService.getTSalaryStandardOriginalList(isCur);
			if (curList != null && !curList.isEmpty()) {
				return R.failed("该项目下已存在此原表类型，请修改！");
			}

			// 上传附件
			String fileName = file.getOriginalFilename();
			//filePath不传默认存储空间的根目录
			//jpg,jpeg,png,bmp
			String key = "original/" + System.currentTimeMillis() + "_" + fileName;
			boolean flag = ossUtil.uploadFileByStream(file.getInputStream(), key, null);
			if (flag) {
				char slash = '/';
				char point = '.';
				if (fileName != null) {
					if (fileName.lastIndexOf(slash) >= 0) {
						tSalaryStandardOriginal.setAttaName(fileName.substring(fileName.lastIndexOf(slash)));
					} else {
						tSalaryStandardOriginal.setAttaName(fileName);
					}
					if (fileName.lastIndexOf(point) >= 0) {
						tSalaryStandardOriginal.setAttaType(fileName.substring(fileName.lastIndexOf(point)));
					} else {
						tSalaryStandardOriginal.setAttaType(fileName);
					}
				}
				tSalaryStandardOriginal.setAttaSize(file.getSize());
				tSalaryStandardOriginal.setAttaSrc(key);
			} else {
				return R.failed("failed:上传至存储空间失败");
			}
			tSalaryStandardOriginalService.save(tSalaryStandardOriginal);
			for (TSalaryStandardOriginalDetail detail : detailList) {
				detail.setOriginalId(tSalaryStandardOriginal.getId());
			}
			tSalaryStandardOriginalDetailService.saveBatch(detailList);
			return R.ok("保存成功！");
		} else {
			return R.failed("请传参！");
		}
	}

	/**
	 * @Description: 获取表头等信息
	 * @Author: hgw
	 * @Date: 2024-4-3 16:49:22
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	@SysLog("获取表头等信息")
	@Operation(description = "获取表头等信息")
	@PostMapping("/getExcelHeader")
	public R<ExcelSheetVo> getExcelHeader(@RequestBody MultipartFile file, @RequestParam String sheetName) {
		return tSalaryStandardOriginalService.getExcelHeader(file, sheetName);
	}

	/**
	 * @Description: 新版原表识别导入
	 * @Author: hgw
	 * @Date: 2024-4-8 18:04:56
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.String>
	 **/
	@SysLog("新版原表识别导入")
	@Operation(description = "新版原表识别导入")
	@PostMapping("/salaryUploadByOriginal")
	public R<SalaryUploadParamVo> salaryUploadByOriginal(MultipartFile file, SalaryUploadOriginalParamVo vo) {
		return tSalaryStandardOriginalService.salaryUploadByOriginal(file, vo);
	}

	/**
	 * 薪资原表配置导出 批量导出
	 * @author hgw
	 * @date 2024-5-13 17:47:07
	 **/
	//@Operation(description = "薪资原表配置导出 hasPermission('tsalaryoriginal-export')")
	@Operation(description = "薪资原表配置导出")
	@PostMapping("/exportOriginal")
	//@PreAuthorize("@pms.hasPermission('tsalaryoriginal-export')")
	public void exportOriginal(HttpServletResponse response, @RequestBody TSalaryOriginalSearchVo searchVo) {
		tSalaryStandardOriginalService.exportOriginal(response,searchVo);
	}

}
