/*
 *    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.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TSettleDomainListVo;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.SecurityConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
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.config.DaprArchivesProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.HttpDaprUtil;
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.annotation.Inner;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import com.yifu.cloud.plus.v1.yifu.salary.constants.SalaryConstants;
import com.yifu.cloud.plus.v1.yifu.salary.entity.THaveSalaryNosocial;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TSalaryAccount;
import com.yifu.cloud.plus.v1.yifu.salary.entity.TSalaryAccountItem;
import com.yifu.cloud.plus.v1.yifu.salary.service.TSalaryAccountItemService;
import com.yifu.cloud.plus.v1.yifu.salary.service.TSalaryAccountService;
import com.yifu.cloud.plus.v1.yifu.salary.vo.TSalaryAccountSearchVo;
import com.yifu.cloud.plus.v1.yifu.salary.vo.TSalaryDetailVo;
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.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 工资报账主表（工资条）
 *
 * @author hgw
 * @date 2022-08-05 11:40:14
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/tsalaryaccount")
@Tag(name = "工资报账主表（工资条）管理")
public class TSalaryAccountController {

	private final TSalaryAccountService tSalaryAccountService;

	private final TSalaryAccountItemService tSalaryAccountItemService;

	private final MenuUtil menuUtil;

	private final DaprArchivesProperties daprArchivesProperties;

	/**
	 * 简单分页查询
	 *
	 * @param page           分页对象
	 * @param tSalaryAccount 工资报账主表（工资条）
	 * @return
	 */
	@Operation(description = "简单分页查询")
	@GetMapping("/page")
	public R<IPage<TSalaryAccount>> getTSalaryAccountPage(Page<TSalaryAccount> page, TSalaryAccountSearchVo tSalaryAccount) {
		tSalaryAccount.setDeleteFlag(CommonConstants.ZERO_INT);
		YifuUser user = SecurityUtils.getUser();
		menuUtil.setAuthSql(user, tSalaryAccount);
		return new R<>(tSalaryAccountService.getTSalaryAccountPage(page, tSalaryAccount));
	}

	/**
	 * 简单分页查询
	 *
	 * @param page           分页对象
	 * @param tSalaryAccount 工资报账主表（工资条）
	 * @return
	 */
	@Operation(description = "简单分页查询")
	@GetMapping("/pageOrder")
	public R<IPage<TSalaryAccount>> getTSalaryAccountPageOrder(Page<TSalaryAccount> page, TSalaryAccountSearchVo tSalaryAccount) {
		tSalaryAccount.setDeleteFlag(CommonConstants.ZERO_INT);
		YifuUser user = SecurityUtils.getUser();
		// 普通用户：
		if (user != null && Common.isNotNull(user.getId()) && CommonConstants.ONE_STRING.equals(user.getSystemFlag())) {
			String sql;
			// 获取人员项目权限
			R<TSettleDomainListVo> res = HttpDaprUtil.invokeMethodPost(daprArchivesProperties.getAppUrl()
					, daprArchivesProperties.getAppId(), "/tsettledomain/getSettleDomainIdsByUserId"
					, user.getId(), TSettleDomainListVo.class, SecurityConstants.FROM_IN);
			StringBuilder deptStr = new StringBuilder();
			if (res != null && CommonConstants.SUCCESS == res.getCode()
					&& res.getData() != null && res.getData().getDeptIds() != null
					&& !res.getData().getDeptIds().isEmpty()) {
				for (String deptId : res.getData().getDeptIds()) {
					deptStr.append(",'").append(deptId).append("'");
				}
			}
			sql = "and (1=2 or a.dept_id in ('0'#settleDomainId))";
			sql = sql.replace("#settleDomainId", deptStr.toString());
			tSalaryAccount.setAuthSql(sql);
		}
		return new R<>(tSalaryAccountService.getTSalaryAccountPage(page, tSalaryAccount));
	}

	/**
	 * 不分页查询
	 *
	 * @param tSalaryAccount 工资报账主表（工资条）
	 * @return
	 */
	@Operation(summary = "不分页查询", description = "不分页查询")
	@PostMapping("/noPage")
	//@PreAuthorize("@pms.hasPermission('salary_tsalaryaccount_get')" )
	public R<List<TSalaryAccount>> getTSalaryAccountNoPage(@RequestBody TSalaryAccountSearchVo tSalaryAccount) {
		return R.ok(tSalaryAccountService.noPageDiy(tSalaryAccount));
	}

	/**
	 * 通过id查询工资报账主表（工资条）
	 *
	 * @param id id
	 * @return R
	 */
	@Operation(summary = "通过id查询", description = "通过id查询：hasPermission('salary_tsalaryaccount_get')")
	@GetMapping("/{id}")
	public R<TSalaryAccount> getById(@PathVariable("id") String id) {
		return R.ok(tSalaryAccountService.getById(id));
	}

	/**
	 * 新增工资报账主表（工资条）
	 *
	 * @param tSalaryAccount 工资报账主表（工资条）
	 * @return R
	 */
	@Operation(summary = "新增工资报账主表（工资条）", description = "新增工资报账主表（工资条）：hasPermission('salary_tsalaryaccount_add')")
	@SysLog("新增工资报账主表（工资条）")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('salary_tsalaryaccount_add')")
	public R<Boolean> save(@RequestBody TSalaryAccount tSalaryAccount) {
		return R.ok(tSalaryAccountService.save(tSalaryAccount));
	}

	/**
	 * 修改工资报账主表（工资条）
	 *
	 * @param tSalaryAccount 工资报账主表（工资条）
	 * @return R
	 */
	@Operation(summary = "修改工资报账主表（工资条）", description = "修改工资报账主表（工资条）：hasPermission('salary_tsalaryaccount_edit')")
	@SysLog("修改工资报账主表（工资条）")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('salary_tsalaryaccount_edit')")
	public R<Boolean> updateById(@RequestBody TSalaryAccount tSalaryAccount) {
		return R.ok(tSalaryAccountService.updateById(tSalaryAccount));
	}

	/**
	 * 通过id删除工资报账主表（工资条）
	 *
	 * @param id id
	 * @return R
	 */
	@Operation(summary = "通过id删除工资报账主表（工资条）", description = "通过id删除工资报账主表（工资条）：hasPermission('salary_tsalaryaccount_del')")
	@SysLog("通过id删除工资报账主表（工资条）")
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('salary_tsalaryaccount_del')")
	public R<Boolean> removeById(@PathVariable String id) {
		return R.ok(tSalaryAccountService.removeById(id));
	}

	/**
	 * 工资报账主表（工资条） 批量导出
	 *
	 * @author hgw
	 * @date 2022-08-05 11:40:14
	 **/
	@Operation(description = "导出工资报账主表（工资条） hasPermission('salary_tsalaryaccount-export')")
	@PostMapping("/export")
	@PreAuthorize("@pms.hasPermission('salary_tsalaryaccount-export')")
	public void export(HttpServletResponse response, @RequestBody TSalaryAccountSearchVo searchVo) {
		YifuUser user = SecurityUtils.getUser();
		menuUtil.setAuthSql(user, searchVo);
		tSalaryAccountService.listExport(response, searchVo);
	}

	/**
	 * @Author fxj
	 * @Description 获取工资条
	 * @Date 14:53 2022/8/15
	 * @Param
	 * @return
	**/
	@Operation(description = "获取工资条")
	@GetMapping("/getEmpAccount")
	public R<TSalaryDetailVo> getEmpAccount(String empIdcard, String settleDepartId, String settlementMonth
			, String settleDepartNo, String settleDepartName, String empName) {
		TSalaryDetailVo salaryDetailVo = new TSalaryDetailVo();
		if (Common.isEmpty(empIdcard) && Common.isEmpty(settleDepartId) && Common.isEmpty(settlementMonth)
				&& Common.isEmpty(settleDepartNo) && Common.isEmpty(settleDepartName) && Common.isEmpty(empName)) {
			return R.failed("请输入查询条件");
		}
		if (Common.isNotNull(settlementMonth) && Common.isEmpty(empIdcard) && Common.isEmpty(settleDepartId)
				&& Common.isEmpty(settleDepartNo) && Common.isEmpty(settleDepartName) && Common.isEmpty(empName)) {
			return R.failed("结算月需配合其他查询条件一起使用，请输入其他查询条件！");
		}
		//报账表
		TSalaryAccount salaryAccount = new TSalaryAccount();
		salaryAccount.setDeleteFlag(SalaryConstants.NOT_DELETE);
		if (Common.isNotNull(empIdcard)) {
			salaryAccount.setEmpIdcard(empIdcard);
		}
		if (Common.isNotNull(settleDepartId)) {
			salaryAccount.setDeptId(settleDepartId);
		}
		if (Common.isNotNull(settlementMonth) && settlementMonth.length() == 6) {
			salaryAccount.setSettlementMonth(settlementMonth);
		}
		QueryWrapper<TSalaryAccount> queryWrapperSa = new QueryWrapper<>();
		queryWrapperSa.setEntity(salaryAccount);
		if (Common.isNotNull(empName)) {
			queryWrapperSa.eq("EMP_NAME", empName);
		}
		if (Common.isNotNull(settleDepartNo)) {
			queryWrapperSa.eq("SETTLE_DEPART_NO", settleDepartNo);
		}
		if (Common.isNotNull(settleDepartName)) {
			queryWrapperSa.like("SETTLE_DEPART_NAME", settleDepartName);
		}
		if (Common.isNotNull(settlementMonth) && settlementMonth.length() < 6) {
			queryWrapperSa.like("SETTLEMENT_MONTH", settlementMonth);
		}
		queryWrapperSa.orderByAsc("SETTLEMENT_MONTH");
		List<TSalaryAccount> salaryAccountList = tSalaryAccountService.list(queryWrapperSa);
		Map<String, String> accountTitle = new HashMap<>();
		if (salaryAccountList != null && salaryAccountList.size() > CommonConstants.ZERO_INT) {
			//报账表明细
			TSalaryAccountItem item;
			QueryWrapper<TSalaryAccountItem> queryWrapperAi;
			List<TSalaryAccountItem> itemList;
			for (TSalaryAccount a : salaryAccountList) {
				item = new TSalaryAccountItem();
				item.setSalaryAccountId(a.getId());
				queryWrapperAi = new QueryWrapper<>();
				queryWrapperAi.setEntity(item);
				itemList = tSalaryAccountItemService.list(queryWrapperAi);
				if (itemList != null && itemList.size() > CommonConstants.ZERO_INT) {
					for (TSalaryAccountItem items : itemList) {
						accountTitle.put(items.getCnName(), items.getJavaFiedName());
					}
				}
				a.setSaiList(itemList);
			}
		}
		salaryDetailVo.setSalaryAccountList(salaryAccountList);
		salaryDetailVo.setAccountTitle(accountTitle);
		return new R<>(salaryDetailVo);
	}


	/**
	 * @Author fxj
	 * @Description 获取有工资无社保数据
	 * @Date 17:20 2022/8/16
	 * @Param
	 * @return
	**/
	@Inner
	@PostMapping("/inner/getLastMonthTHaveSalaryNosocial")
	public R<List<THaveSalaryNosocial>> getLastMonthTHaveSalaryNosocial(@RequestParam(name = "month") String month){
		return new R<>(tSalaryAccountService.getLastMonthTHaveSalaryNosocial(month));
	}
}
