/*
 *    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.LocalDateTimeUtils;
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.insurances.vo.EkpSocialViewVo;
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.util.SalaryCommonUtil;
import com.yifu.cloud.plus.v1.yifu.salary.vo.TSalaryAccountSearchVo;
import com.yifu.cloud.plus.v1.yifu.salary.vo.TSalaryAccountSumVo;
import com.yifu.cloud.plus.v1.yifu.salary.vo.TSalaryDetailVo;
import com.yifu.cloud.plus.v1.yifu.salary.vo.WageProofDto;
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.math.BigDecimal;
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")
	@SysLog("员工报账查询-批量导出")
	@PreAuthorize("@pms.hasPermission('salary_tsalaryaccount-export')")
	public void export(HttpServletResponse response, @RequestBody TSalaryAccountSearchVo searchVo) {
		YifuUser user = SecurityUtils.getUser();
		if (Common.isEmpty(user)){
			tSalaryAccountService.exportError(response, CommonConstants.USER_FAIL);
		}
		menuUtil.setAuthSql(user, searchVo);
		tSalaryAccountService.exportAsso(response, searchVo,CommonConstants.ZERO_INT);
	}

	/**
	 * 审核人导出
	 * @author hgw
	 * @date  2023-2-17 11:17:48
	 **/
	@Operation(description = "审核人导出 hasPermission('account_audit_export')")
	@PostMapping("/auditExport")
	@SysLog("员工报账查询-审核人导出")
	@PreAuthorize("@pms.hasPermission('account_audit_export')")
	public void auditExport(HttpServletResponse response, @RequestBody TSalaryAccountSearchVo searchVo) {
		tSalaryAccountService.exportAsso(response, searchVo,CommonConstants.ONE_INT);
	}

	/**
	 * @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 deptNo, String deptName, String empName) {
		TSalaryDetailVo salaryDetailVo = new TSalaryDetailVo();
		if (Common.isEmpty(empIdcard) && Common.isEmpty(settleDepartId) && Common.isEmpty(settlementMonth)
				&& Common.isEmpty(deptNo) && Common.isEmpty(deptName) && Common.isEmpty(empName)) {
			return R.failed("请输入查询条件");
		}
		if (Common.isNotNull(settlementMonth) && Common.isEmpty(empIdcard) && Common.isEmpty(settleDepartId)
				&& Common.isEmpty(deptNo) && Common.isEmpty(deptName) && 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(deptNo)) {
			queryWrapperSa.eq("DEPT_NO", deptNo);
		}
		if (Common.isNotNull(settleDepartId)) {
			queryWrapperSa.eq("DEPT_ID", settleDepartId);
		}
		if (Common.isNotNull(settlementMonth) && settlementMonth.length() < 6) {
			queryWrapperSa.eq("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));
	}

	/**
	 * @param viewVo
	 * @Description: 更新结算信息
	 * @Author: huyc
	 * @Date: 2022/8/25
	 * @return:
	 **/
	@Inner
	@PostMapping("/inner/updateSalarySettleStatus")
	public Boolean updateSalarySettleStatus(@RequestBody List<EkpSocialViewVo> viewVo) {
		return tSalaryAccountService.updateSalarySettleStatus(viewVo);
	}

	/**
	 * 服务间调用
	 * @Author pwang
	 * @Date 2019-11-06 17:14
	 * @return
	 **/
	@Inner
	@PostMapping("/inner/findAverageSalaryForProve")
	public WageProofDto findAverageSalaryForProve(@RequestBody WageProofDto pd) {
		return getWageProofDtoR(pd.getStartMouth(), pd.getEndMouth(), pd.getEmIdCard(), pd.getSumType(), null);
	}

	/**
	 * 获取证明工资数据接口
	 * @Author pwang
	 * @Date 2019-11-06 17:14
	 * @param startMouth 开始月
	 * @param endMouth 结束月
	 * @param emIdCard 员工身份证
	 * @param settleDepartId 结算主体id
	 * @param sumType 0实发平均 1应发平均
	 * @return
	 **/
	@Operation(summary = "获取证明工资数据", description = "获取证明工资数据")
	@GetMapping("/getAverageSalaryForProve")
	public R<WageProofDto> getAverageSalaryForProve(String startMouth, String endMouth, String emIdCard,String sumType, String settleDepartId) {
		if( Common.isEmpty(startMouth) || Common.isEmpty(endMouth) || Common.isEmpty(emIdCard) || Common.isEmpty(sumType) ){
			return R.failed("参数不完整");
		}
		WageProofDto wp = getWageProofDtoR(startMouth, endMouth, emIdCard, sumType, settleDepartId);
		if (Common.isEmpty(wp.getErrorInfo())) {
			return R.failed(wp.getErrorInfo());
		} else {
			return R.ok(wp);
		}
	}

	private WageProofDto getWageProofDtoR(String startMouth, String endMouth, String emIdCard, String sumType, String settleDepartId) {
		WageProofDto wp = new WageProofDto();
		List<String> accountIdForProve = tSalaryAccountService.getAccountIdForProve(startMouth, endMouth, emIdCard, settleDepartId);
		String accIdStr;
		int realMonthCount = 0;
		BigDecimal salary = null;
		List<String> accountMonthForProve = null;

		if (Common.isNotNull(accountIdForProve)) {
			accountMonthForProve = tSalaryAccountService.getAccountMonthForProve(startMouth, endMouth, emIdCard, settleDepartId);
			if (Common.isNotNull(accountMonthForProve)) {
				realMonthCount = accountMonthForProve.size();
				int count = LocalDateTimeUtils.getBeginOfMonth(endMouth.concat("01"), startMouth.concat("01"), "yyyyMMdd") + 1;
				if (count != realMonthCount) {
					wp.setErrorInfo("信息不一致，实际发工资月份为：" + SalaryCommonUtil.listToStrEasy(accountMonthForProve));
					return wp;
				}
			} else {
				wp.setErrorInfo("实发工资月份有误！");
				return wp;
			}
			//普通工资信息
			accIdStr = SalaryCommonUtil.listForSqlIn(accountIdForProve);
			if ("0".equals(sumType)) {
				salary = tSalaryAccountItemService.getAllMoneyByAccountIdAndFiedName(accIdStr, SalaryConstants.ACTUAL_SALARY_SUM_JAVA);//实发合计

			} else {
				salary = tSalaryAccountItemService.getAllMoneyByAccountIdAndFiedName(accIdStr, SalaryConstants.RELAY_SALARY_JAVA);//应发合计
			}
		}
		if (null == salary) {
			wp.setErrorInfo("无工资信息！");
			return wp;
		}
		wp.setRealMonthCount(realMonthCount);
		wp.setSalary(salary.divide(new BigDecimal(realMonthCount), SalaryConstants.PLACES, BigDecimal.ROUND_HALF_UP));
		return wp;
	}

	/**
	 * 报账跨年查询导出
	 * @author hgw
	 * @date  2023-3-30 15:36:00
	 **/
	@Operation(description = "报账跨年查询导出 hasPermission('account_all_year_export')")
	@PostMapping("/allYearExport")
	@PreAuthorize("@pms.hasPermission('account_all_year_export')")
	public R<List<TSalaryAccount>> allYearExport(@RequestBody TSalaryAccountSearchVo tSalaryAccount) {
		if (Common.isEmpty(tSalaryAccount.getEmpIdcard())) {
			return R.failed("身份证不可为空！");
		}
		return R.ok(tSalaryAccountService.allYearExport(tSalaryAccount));
	}

	/**
	 * @param salaryId
	 * @Description: 提交时获取应发实发
	 * @Author: hgw
	 * @Date: 2023/4/18 16:30
	 **/
	@Operation(description = "提交时获取应发实发")
	@GetMapping("/getAccountSumBySalaryId")
	public R<TSalaryAccountSumVo> getAccountSumBySalaryId(@RequestParam String salaryId) {
		// 劳务费，应发取值为导表的金额，不是加了税的应发。2023-4-23 11:21:10 产品倩倩与客服沟通的结果
		return R.ok(tSalaryAccountService.getAccountSumBySalaryId(salaryId));
	}
	
}
