/*
 *    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.social.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yifu.cloud.plus.v1.yifu.archives.vo.SocialAndFundReduceVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TSettleDomainListVo;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CacheConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.ResultConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.SecurityConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.redis.RedisDistributedLock;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.ErrorMessage;
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.social.entity.TDispatchInfo;
import com.yifu.cloud.plus.v1.yifu.social.service.TDispatchInfoService;
import com.yifu.cloud.plus.v1.yifu.social.vo.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 派单信息记录表
 *
 * @author fxj
 * @date 2022-07-15 11:38:05
 */
@Log4j2
@RestController
@RequiredArgsConstructor
@RequestMapping("/tdispatchinfo" )
@Tag(name = "派单信息记录表管理")
public class TDispatchInfoController {

    private final TDispatchInfoService tDispatchInfoService;

	private final MenuUtil menuUtil;

	private final DaprArchivesProperties daprArchivesProperties;

    /**
     * 简单分页查询
     * @param page 分页对象
     * @param tDispatchInfo 派单信息记录表
     * @return
     */
    @Operation(description = "简单分页查询")
    @GetMapping("/page")
    public R<IPage<TDispatchInfoPageVo>> getTDispatchInfoPage(Page<TDispatchInfo> page, TDispatchInfoSearchVo tDispatchInfo) {
		tDispatchInfo.setDeleteFlag(CommonConstants.ZERO_STRING);
		YifuUser user = SecurityUtils.getUser();
		menuUtil.setAuthSql(user, tDispatchInfo);
		if (Common.isNotNull(tDispatchInfo.getAuthSql())) {
			if (tDispatchInfo.getAuthSql().contains(CommonConstants.A_DEPT_ID)) {
				tDispatchInfo.setAuthSql(tDispatchInfo.getAuthSql().replace(CommonConstants.A_DEPT_ID, "a.SETTLE_DOMAIN"));
			}
			if (tDispatchInfo.getAuthSql().contains("1=2 EXISTS")) {
				tDispatchInfo.setAuthSql(tDispatchInfo.getAuthSql().replace("1=2 EXISTS", "EXISTS"));
			}
		}
		tDispatchInfo.setCreateBy(user.getId());
        return  new R<>(tDispatchInfoService.getTDispatchInfoPageAudit(page,tDispatchInfo));
    }

    /**
     * 不分页查询
     * @param tDispatchInfo 派单信息记录表
     * @return
     */
    @Operation(summary = "不分页查询", description = "不分页查询")
    @PostMapping("/noPage" )
    //@PreAuthorize("@pms.hasPermission('demo_tdispatchinfo_get')" )
    public R<List<TDispatchInfo>> getTDispatchInfoNoPage(@RequestBody TDispatchInfoSearchVo tDispatchInfo) {
		tDispatchInfo.setDeleteFlag(CommonConstants.ZERO_STRING);
        return R.ok(tDispatchInfoService.noPageDiy(tDispatchInfo));
    }
	/**
	 * 简单分页查询--申请
	 * @param page 分页对象
	 * @param tDispatchInfo 派单信息记录表--申请
	 * @return
	 */
	@Operation(description = "简单分页查询--申请")
	@GetMapping("/pageApply")
	public R<IPage<TDispatchInfoPageVo>> getTDispatchApplyPage(Page<TDispatchInfo> page, TDispatchInfoSearchVo tDispatchInfo) {
		YifuUser user = SecurityUtils.getUser();
		if (Common.isEmpty(user)){
			return  R.failed(CommonConstants.USER_FAIL);
		}
		tDispatchInfo.setCreateBy(user.getId());
		tDispatchInfo.setDeleteFlag(CommonConstants.ZERO_STRING);

		menuUtil.setAuthSql(user, tDispatchInfo);
		if (Common.isNotNull(tDispatchInfo.getAuthSql())) {
			if(tDispatchInfo.getAuthSql().contains(CommonConstants.A_DEPT_ID)) {
				tDispatchInfo.setAuthSql(tDispatchInfo.getAuthSql().replace(CommonConstants.A_DEPT_ID, "a.SETTLE_DOMAIN"));
			}
			if (tDispatchInfo.getAuthSql().contains("s.") || tDispatchInfo.getAuthSql().contains("f.")){
				tDispatchInfo.setAuthSql(tDispatchInfo.getAuthSql().replace("s.", "a."));
				tDispatchInfo.setAuthSql(tDispatchInfo.getAuthSql().replace("f.", "a."));
			}
		}
		return new R<>(tDispatchInfoService.getTDispatchInfoPage(page,tDispatchInfo));
	}

	/**
	 * 简单分页查询--申请
	 * @param page 分页对象
	 * @param tDispatchInfo 派单信息记录表--申请
	 * @return
	 */
	@Operation(description = "简单分页查询--申请")
	@GetMapping("/pageApplyOrder")
	public R<IPage<TDispatchInfoPageVo>> getTDispatchApplyPageOrder(Page<TDispatchInfo> page, TDispatchInfoSearchVo tDispatchInfo) {
		YifuUser user = SecurityUtils.getUser();
		if (Common.isEmpty(user)) {
			return R.failed(CommonConstants.USER_FAIL);
		}
		tDispatchInfo.setCreateBy(user.getId());
		tDispatchInfo.setDeleteFlag(CommonConstants.ZERO_STRING);

		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());
			tDispatchInfo.setAuthSql(sql);
			if (Common.isNotNull(tDispatchInfo.getAuthSql()) && tDispatchInfo.getAuthSql().contains(CommonConstants.A_DEPT_ID)) {
				tDispatchInfo.setAuthSql(tDispatchInfo.getAuthSql().replace(CommonConstants.A_DEPT_ID, "a.SETTLE_DOMAIN"));
			}
		}
		return new R<>(tDispatchInfoService.getTDispatchInfoPage(page, tDispatchInfo));
	}

	/**
	 * 简单分页查询--审核
	 * @param page 分页对象
	 * @param tDispatchInfo 派单信息记录表--审核
	 * @return
	 */
	@Operation(description = "简单分页查询--审核")
	@GetMapping("/pageAudit")
	public R<IPage<TDispatchInfoPageVo>> getTDispatchAuditPage(Page<TDispatchInfo> page, TDispatchInfoSearchVo tDispatchInfo) {
		tDispatchInfo.setDeleteFlag(CommonConstants.ZERO_STRING);
		tDispatchInfo.setStatus(CommonConstants.ONE_STRING);
		YifuUser user = SecurityUtils.getUser();
		// SSC派单组-1659015946137583618L  SSC审核组-1659016108176130049L
		long roleId = 1659016108176130049L;
		boolean isSsc =	tDispatchInfoService.haveRole(user, roleId);
		if (isSsc) {
			tDispatchInfo.setStatus(CommonConstants.FIVE_STRING);
			tDispatchInfo.setNoCreateUser(user.getId());
		}
		menuUtil.setAuthSql(user, tDispatchInfo);
		if (Common.isNotNull(tDispatchInfo.getAuthSql())) {
			if (tDispatchInfo.getAuthSql().contains(CommonConstants.A_DEPT_ID)) {
				tDispatchInfo.setAuthSql(tDispatchInfo.getAuthSql().replace(CommonConstants.A_DEPT_ID, "a.SETTLE_DOMAIN"));
			}
			if (tDispatchInfo.getAuthSql().contains("1=2 EXISTS")) {
				tDispatchInfo.setAuthSql(tDispatchInfo.getAuthSql().replace("1=2 EXISTS", "EXISTS"));
			}
		}
		tDispatchInfo.setCreateBy(user.getId());
		return new R<>(tDispatchInfoService.getTDispatchInfoPageAudit(page,tDispatchInfo));
	}

	/**
	 * 简单分页查询--社保办理列表
	 * @param page 分页对象
	 * @param tDispatchInfo 派单信息记录表--社保办理列表
	 * @return
	 */
	@Operation(description = "简单分页查询--社保办理列表")
	@GetMapping("/pageSocialHandle")
	public R<IPage<TDispatchInfo>> getTDispatchSocialHandlePage(Page<TDispatchInfo> page, SocialHandleSearchVo tDispatchInfo) {
		tDispatchInfo.setDeleteFlag(CommonConstants.ZERO_STRING);
		YifuUser user = SecurityUtils.getUser();
		menuUtil.setAuthSql(user, tDispatchInfo);
		if (Common.isNotNull(tDispatchInfo.getAuthSql()) && tDispatchInfo.getAuthSql().contains(CommonConstants.A_DEPT_ID)) {
			tDispatchInfo.setAuthSql(tDispatchInfo.getAuthSql().replace(CommonConstants.A_DEPT_ID, "a.SETTLE_DOMAIN"));
		}
		tDispatchInfo.setCreateBy(user.getId());
		return new R<>(tDispatchInfoService.getTDispatchSocialHandlePage(page,tDispatchInfo));
	}

	/**
	 * 简单分页查询--公积金办理列表
	 * @param page 分页对象
	 * @param tDispatchInfo 派单信息记录表--公积金办理列表
	 * @return
	 */
	@Operation(description = "简单分页查询--公积金办理列表")
	@GetMapping("/pageFundHandle")
	public R<IPage<TDispatchInfo>> getTDispatchFundHandlePage(Page<TDispatchInfo> page, SocialHandleSearchVo tDispatchInfo) {
		tDispatchInfo.setDeleteFlag(CommonConstants.ZERO_STRING);
		YifuUser user = SecurityUtils.getUser();
		menuUtil.setAuthSql(user, tDispatchInfo);
		if (Common.isNotNull(tDispatchInfo.getAuthSql()) && tDispatchInfo.getAuthSql().contains(CommonConstants.A_DEPT_ID)) {
			tDispatchInfo.setAuthSql(tDispatchInfo.getAuthSql().replace(CommonConstants.A_DEPT_ID, "a.SETTLE_DOMAIN"));
		}
		tDispatchInfo.setCreateBy(user.getId());
		return  new R<>(tDispatchInfoService.getTDispatchFundHandlePage(page,tDispatchInfo));
	}
    /**
     * 通过id查询派单信息记录表
     * @param id
     * @return R
     */
    @Operation(summary = "通过id查询", description = "通过id查询：hasPermission('demo_tdispatchinfo_get')")
    @GetMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('demo_tdispatchinfo_get')" )
    public R<TDispatchInfo> getById(@PathVariable("id" ) String id) {
        return R.ok(tDispatchInfoService.getById(id));
    }

	/**
	 * 通过id查询派单相关系信息
	 * @author fxj
	 * @param id id
	 * @return R
	 * @date 2022-07-25 10:19
	 */
	@Operation(summary = "通过id查询派单相关系信息", description = "通过id查询派单相关系信息")
	@GetMapping("/getSocialAndFundInfoById" )
	public R<DispatchDetailVo> getSocialAndFundInfoById(@RequestParam(value = "id") String id) {
		return R.ok(tDispatchInfoService.getSocialAndFundInfoById(id));
	}

	/**
     * 新增派单信息记录表
     * @param tDispatchInfo 派单信息记录表
     * @return R
     */
    @Operation(summary = "新增派单信息记录表", description = "新增派单信息记录表：hasPermission('demo_tdispatchinfo_add')")
    @SysLog("新增派单信息记录表" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('demo_tdispatchinfo_add')" )
    public R<Boolean> save(@RequestBody TDispatchInfo tDispatchInfo) {
        return R.ok(tDispatchInfoService.save(tDispatchInfo));
    }

    /**
     * 修改派单信息记录表
     * @param tDispatchInfo 派单信息记录表
     * @return R
     */
    @Operation(summary = "修改派单信息记录表", description = "修改派单信息记录表：hasPermission('demo_tdispatchinfo_edit')")
    @SysLog("修改派单信息记录表" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('demo_tdispatchinfo_edit')" )
    public R<Boolean> updateById(@RequestBody TDispatchInfo tDispatchInfo) {
        return R.ok(tDispatchInfoService.updateById(tDispatchInfo));
    }

    /**
     * 通过id删除派单信息记录表
     * @param id id
     * @return R
     */
    @Operation(summary = "通过id删除派单信息记录表", description = "通过id删除派单信息记录表：hasPermission('demo_tdispatchinfo_del')")
    @SysLog("通过id删除派单信息记录表" )
    @DeleteMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('demo_tdispatchinfo_del')" )
    public R<Boolean> removeById(@PathVariable String id) {
        return tDispatchInfoService.removeByIdDiy(id);
    }

    /**
	 * 派单信息记录表 批量导入
	 *
     * @author fxj
     * @date 2022-07-15 11:38:05
	 **/
    @SneakyThrows
    @Operation(description = "批量新增派单信息记录表 hasPermission('demo_tdispatchinfo-batch-import')")
    @SysLog("批量新增派单信息记录表")
    @PostMapping("/importListAdd")
    //@PreAuthorize("@pms.hasPermission('demo_tdispatchinfo-batch-import')")
    public R<List<ErrorMessage>> importListAdd(@RequestBody MultipartFile file, @RequestParam(required = false)String orderId){
		YifuUser user = SecurityUtils.getUser();
		if (Common.isEmpty(user)){
			return R.failed(CommonConstants.USER_FAIL);
		}
		// 获取redis分布式事务锁
		String key = CacheConstants.PAYMENT_DISPATCH_BATCH_ADD_IMPORT + CommonConstants.DOWN_LINE_STRING + user.getId();
		String requestId;
		try {
			requestId = RedisDistributedLock.getLock(key,"10");
		} catch (Exception e) {
			throw new RuntimeException(ResultConstants.NO_GETLOCK_DATA+CommonConstants.DOWN_LINE_STRING+e.getMessage());
		}
		try {
			if (Common.isNotNull(requestId)) {
				//主动释放锁
				return tDispatchInfoService.importDiy(file.getInputStream(),orderId);
			} else {
				return R.failed(ResultConstants.NO_GETLOCK_DATA);
			}
		}finally {
			//主动释放锁
			RedisDistributedLock.unlock(key, requestId);
		}
    }

    /**
     * 派单信息记录表 批量导出
     * @author hgw
     * @date 2022-7-28 11:01:56
     **/
    @Operation(description = "导出派单信息记录表 hasPermission('tdispatchinfo-export')")
    @PostMapping("/export")
    @PreAuthorize("@pms.hasPermission('tdispatchinfo-export')")
    public void export(HttpServletResponse response, @RequestBody TDispatchInfoSearchVo searchVo) {
		YifuUser user = SecurityUtils.getUser();
		menuUtil.setAuthSql(user, searchVo);
		if (Common.isNotNull(searchVo.getAuthSql())) {
			if (searchVo.getAuthSql().contains(CommonConstants.A_DEPT_ID)) {
				searchVo.setAuthSql(searchVo.getAuthSql().replace(CommonConstants.A_DEPT_ID, "a.SETTLE_DOMAIN"));
			}
			if (searchVo.getAuthSql().contains("1=2 EXISTS")) {
				searchVo.setAuthSql(searchVo.getAuthSql().replace("1=2 EXISTS", "EXISTS"));
			}
		}
		searchVo.setCreateBy(user.getId());
		tDispatchInfoService.listExport(response,searchVo);
    }

	/**
	 * 派单审核记录批量导出
	 * @author huyc
	 * @date 2022-10-25 15:01:56
	 **/
	@Operation(description = "导出派单审核记录 hasPermission('tdispatchinfo-export')")
	@PostMapping("/auditExport")
	@PreAuthorize("@pms.hasPermission('tdispatchinfo-export')")
	public void auditExport(HttpServletResponse response, @RequestBody TDispatchInfoSearchVo searchVo,
							@RequestParam(required = false,name = "mId") String mId) {
		searchVo.setDeleteFlag(CommonConstants.ZERO_STRING);
		YifuUser user = SecurityUtils.getUser();
		searchVo.setStatus(CommonConstants.ONE_STRING);
		// SSC派单组-1659015946137583618L  SSC审核组-1659016108176130049L
		long roleId = 1659016108176130049L;
		boolean isSsc =	tDispatchInfoService.haveRole(user, roleId);
		if (isSsc) {
			searchVo.setStatus(CommonConstants.FIVE_STRING);
			searchVo.setNoCreateUser(user.getId());
		}
		searchVo.setMId(mId);
		menuUtil.setAuthSql(user, searchVo);
		if (Common.isNotNull(searchVo.getAuthSql())) {
			if (searchVo.getAuthSql().contains(CommonConstants.A_DEPT_ID)) {
				searchVo.setAuthSql(searchVo.getAuthSql().replace(CommonConstants.A_DEPT_ID, "a.SETTLE_DOMAIN"));
			}
			if (searchVo.getAuthSql().contains("1=2 EXISTS")) {
				searchVo.setAuthSql(searchVo.getAuthSql().replace("1=2 EXISTS", "EXISTS"));
			}
		}
		searchVo.setCreateBy(user.getId());
		tDispatchInfoService.listAuditExport(response,searchVo);
	}

	/**
	 * 派单信息记录表 批量导入-派减
	 *
	 * @author fxj
	 * @date 2022-07-15 11:38:05
	 **/
	@SneakyThrows
	@Operation(description = "派单信息记录表 批量导入-派减 hasPermission('demo_tdispatchinfo-batch-reduce')")
	@SysLog("派单信息记录表 批量导入-派减")
	@PostMapping("/importListReduce")
	//@PreAuthorize("@pms.hasPermission('demo_tdispatchinfo-batch-reduce')")
	public R<List<ErrorMessage>> importListReduce(@RequestBody MultipartFile file, @RequestParam(required = false)String orderId){
		YifuUser user = SecurityUtils.getUser();
		if (Common.isEmpty(user)){
			return R.failed(CommonConstants.USER_FAIL);
		}
		// 获取redis分布式事务锁
		String key = CacheConstants.PAYMENT_DISPATCH_BATCH_REDUCE_IMPORT + CommonConstants.DOWN_LINE_STRING + user.getId();
		String requestId;
		try {
			requestId = RedisDistributedLock.getLock(key,"10");
		} catch (Exception e) {
			throw new RuntimeException(ResultConstants.NO_GETLOCK_DATA+CommonConstants.DOWN_LINE_STRING+e.getMessage());
		}
		try {
			if (Common.isNotNull(requestId)) {
				//主动释放锁
				return tDispatchInfoService.importReduceDiy(file.getInputStream(),orderId);
			} else {
				return R.failed(ResultConstants.NO_GETLOCK_DATA);
			}
		}finally {
			//主动释放锁
			RedisDistributedLock.unlock(key, requestId);
		}
	}

	/**
	 * @Author huyc
	 * @Description 单个派减
	 * @Date 16:54 2023/3/9
	 * @Param
	 * @return
	 **/
	@Operation(description = "单个派减")
	@SysLog("单个派减")
	@PostMapping("/reduceSocialAndFund")
	public R<List<ErrorMessage>> reduceSocialAndFund(@RequestBody TDispatchReduceVo excelVOList,
													 @RequestParam(required = false) String orderId) {
		List<TDispatchReduceVo> list = new ArrayList<>();
		list.add(excelVOList);
		YifuUser user = SecurityUtils.getUser();
		List<ErrorMessage> errorMessageList = new ArrayList<>();
		tDispatchInfoService.batchReduceDispatch(list, errorMessageList, user, orderId);
		return R.ok(errorMessageList);
	}

	/**
	 * @Author fxj
	 * @Description 派单申请批量审核
	 * @Date 16:54 2022/7/25
	 * @Param
	 * @return
	**/
	@Operation(description = "派单申请批量审核，传参派单ID hasPermission('wxhr:tdispatchinfo_addApplyAudit') auditStatus:1审核通过 2审核不通过")
	@SysLog("派单申请批量审核")
	@PostMapping("/addApplyAudit")
	//@PreAuthorize("@pms.hasPermission('wxhr:tdispatchinfo_addApplyAudit')")
	public R<List<ErrorMessage>> addApplyAudit(@RequestBody List<String> idList,
									@RequestParam(name = "auditStatus", required = true) String auditStatus,
									@RequestParam(name = "auditRemark", required = false) String auditRemark,
									@RequestParam(name = "remark", required = false) String remark) {
		YifuUser user = SecurityUtils.getUser();
		if (Common.isEmpty(user)){
			return R.failed(CommonConstants.USER_FAIL);
		}
		// 获取redis分布式事务锁
		String key = CacheConstants.DISPATCH_BATCH_AUDIT + CommonConstants.DOWN_LINE_STRING + user.getId();
		String requestId;
		try {
			requestId = RedisDistributedLock.getLock(key,"10");
		} catch (Exception e) {
			throw new RuntimeException(ResultConstants.NO_GETLOCK_DATA+CommonConstants.DOWN_LINE_STRING+e.getMessage());
		}
		try {
			if (Common.isNotNull(requestId)) {
				//主动释放锁
				return  tDispatchInfoService.addApplyAudit(idList,auditStatus,auditRemark,remark);
			} else {
				return R.failed(ResultConstants.NO_GETLOCK_DATA);
			}
		}finally {
			//主动释放锁
			RedisDistributedLock.unlock(key, requestId);
		}

	}

	/**
	 * 派单申请办理
	 * hgw社保办理
	 * @param handleStatus 1 办理成功 2 办理失败
	 * @param handleRemark
	 * @param typeSub 0 社保 1  公积金
	 * @param socialType （1养老 2医疗 3失业 4工伤 5生育 6大病）
	 * @return
	 * @Author fxj
	 * @Date 2019-09-27
	 **/
	@Operation(description = "派单批量办理，传参派单ID hasPermission('wxhr:tdispatchinfo_addApplyHandle') handleStatus 1 办理成功 2 办理失败")
	@SysLog("派单批量办理")
	@PostMapping("/addApplyHandle")
	//@PreAuthorize("@pms.hasPermission('wxhr:tdispatchinfo_addApplyHandle')")
	public R<List<ErrorMessage>> addApplyHandle(@RequestBody List<String> idList,
									 @RequestParam(name = "typeSub", required = true) String typeSub,
									 @RequestParam(name = "handleStatus", required = true) String handleStatus,
									 @RequestParam(name = "handleRemark", required = false) String handleRemark,
									 @RequestParam(name = "socialType", required = false) String socialType,
									 @RequestParam(name = "remark", required = false) String remark) {
		YifuUser user = SecurityUtils.getUser();
		if (Common.isEmpty(user)){
			return R.failed(CommonConstants.USER_FAIL);
		}
		// 获取redis分布式事务锁
		String key = CacheConstants.DISPATCH_BATCH_HANDLED + CommonConstants.DOWN_LINE_STRING + user.getId();
		String requestId;
		try {
			requestId = RedisDistributedLock.getLock(key,"10");
		} catch (Exception e) {
			throw new RuntimeException(ResultConstants.NO_GETLOCK_DATA+CommonConstants.DOWN_LINE_STRING+e.getMessage());
		}
		try {
			if (Common.isNotNull(requestId)) {
				//主动释放锁
				return tDispatchInfoService.addApplyHandle(idList,typeSub,handleStatus,handleRemark,socialType,remark);
			} else {
				return R.failed(ResultConstants.NO_GETLOCK_DATA);
			}
		}finally {
			//主动释放锁
			RedisDistributedLock.unlock(key, requestId);
		}
	}

	/**
	 * 社保批量办理导入
	 * @author huyc
	 * @date 2023-05-15 11:38:05
	 **/
	@SneakyThrows
	@Operation(description = "社保批量办理导入")
	@SysLog("社保批量办理导入")
	@PostMapping("/importSocialHandler")
	public R<List<ErrorMessage>> importSocialHandler(@RequestBody MultipartFile file,@RequestParam String mId){
		YifuUser user = SecurityUtils.getUser();
		if (Common.isEmpty(user)){
			return R.failed(CommonConstants.USER_FAIL);
		}
		// 获取redis分布式事务锁
		String key = CacheConstants.PAYMENT_DISPATCH_BATCH_ADD_IMPORT + CommonConstants.DOWN_LINE_STRING + user.getId();
		String requestId;
		try {
			requestId = RedisDistributedLock.getLock(key,"10");
		} catch (Exception e) {
			throw new RuntimeException(ResultConstants.NO_GETLOCK_DATA+CommonConstants.DOWN_LINE_STRING+e.getMessage());
		}
		try {
			if (Common.isNotNull(requestId)) {
				//主动释放锁
				return tDispatchInfoService.importSocialHandler(file.getInputStream(),mId);
			} else {
				return R.failed(ResultConstants.NO_GETLOCK_DATA);
			}
		}finally {
			//主动释放锁
			RedisDistributedLock.unlock(key, requestId);
		}
	}

	/**
	 * @Author fxj
	 * @Description  导出 社保花名册
	 * @Date 17:40 2022/7/27
	 * @Param
	**/
	@PostMapping("/doexportSocialRecordRoster")
	@Operation(description = "导出社保花名册 hasPermission('wxhr:tdispatchinfo_doexportSocialRecordRoster')")
	@SysLog("导出社保花名册信息")
	//@PreAuthorize("@pms.hasPermission('wxhr:tdispatchinfo_doexportSocialRecordRoster')")
	public void doexportSocialRecordRoster(HttpServletResponse response, HttpServletRequest request,
										   @RequestBody  SocialHandleSearchVo searchVo) {
		searchVo.setDeleteFlag(CommonConstants.ZERO_STRING);
		YifuUser user = SecurityUtils.getUser();
		menuUtil.setAuthSql(user, searchVo);
		if (Common.isNotNull(searchVo.getAuthSql()) && searchVo.getAuthSql().contains(CommonConstants.A_DEPT_ID)) {
			searchVo.setAuthSql(searchVo.getAuthSql().replace(CommonConstants.A_DEPT_ID, "a.SETTLE_DOMAIN"));
		}
		searchVo.setCreateBy(user.getId());
		tDispatchInfoService.doexportSocialRecordRoster(response,searchVo,searchVo.getIdStr(),null);
	}

	/**
	 * @Author fxj
	 * @Description 导出 公积金变更清册
	 * @Date 20:05 2022/7/27
	 * @Param
	 * @return
	**/
	@PostMapping("/doexportFundRecordChange")
	@Operation(description = "导出公积金变更清册 hasPermission('wxhr:tdispatchinfo_doexportFundRecordChange')")
	@SysLog("导出公积金变更清册")
	@PreAuthorize("@pms.hasPermission('wxhr:tdispatchinfo_doexportFundRecordChange')")
	public void doexportFundRecordChange(HttpServletResponse response, HttpServletRequest request,
										 @RequestBody SocialHandleSearchVo searchVo) {
		YifuUser user = SecurityUtils.getUser();
		menuUtil.setAuthSql(user, searchVo);
		if (Common.isNotNull(searchVo.getAuthSql()) && searchVo.getAuthSql().contains(CommonConstants.A_DEPT_ID)) {
			searchVo.setAuthSql(searchVo.getAuthSql().replace(CommonConstants.A_DEPT_ID, "a.SETTLE_DOMAIN"));
		}
		searchVo.setCreateBy(user.getId());
		tDispatchInfoService.doexportFundRecordChange(response, searchVo.getIdStr(),searchVo);
	}
	/**
	 * @Author fxj
	 * @Description 导出公积金补缴清册
	 * @Date 20:05 2022/7/27
	 * @Param
	 * @return
	**/
	@GetMapping("/doExportFundSupplementaryRecord")
	@Operation(description = "导出公积金补缴清册 hasPermission('wxhr:tdispatchinfo_doExportFundSupplementaryRecord')")
	@SysLog("导出公积金补缴清册")
	@PreAuthorize("@pms.hasPermission('wxhr:tdispatchinfo_doExportFundSupplementaryRecord')")
	public R<List<FundSupplementaryExportVo>> doExportFundSupplementaryRecord(HttpServletResponse response, HttpServletRequest request,
																			  @RequestParam(name = "idStr", required = false) String idStr,
																			  @RequestBody SocialHandleSearchVo searchVo) {
		// 获取项目权限 TODO
		List<String> settleDomains = null;
		// 获取自定义sql TODO
		String sql = CommonConstants.EMPTY_STRING;
		return tDispatchInfoService.getFundSupplementaryRecords(idStr,searchVo,settleDomains,sql);
	}

	/**
	 * 获取社保和公积金派减日期
	 * @Author hgw
	 * @Date 2020-08-25
	 * @return
	 **/
	@SysLog("B端获取社保和公积金派减日期")
	@PostMapping(value = "/inner/getSocialAndFundReduceInfo")
	@Inner
	public SocialAndFundReduceVo getSocialAndFundReduceInfo(@RequestBody SocialAndFundReduceVo vo) {
		if (Common.isNotNull(vo.getEmpId())) {
			return tDispatchInfoService.getSocialAndFundReduceInfo(vo.getEmpId());
		}
		return new SocialAndFundReduceVo();
	}

	/**
	 * @param importVo
	 * @Description: 单个派增
	 * @Author: hgw
	 * @Date: 2023/3/10 15:35
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<java.lang.Boolean>
	 **/
	@Operation(summary = "单个派增 权限：social_dispatchinfo_add", description = "单个派增")
	@PostMapping("/dispatchAdd")
	@PreAuthorize("@pms.hasPermission('social_dispatchinfo_add')")
	public R<List<ErrorMessage>> dispatchAdd(@RequestBody TDispatchImportVo importVo) {
		return tDispatchInfoService.dispatchAdd(importVo);
	}

	/**
	 * @Author fxj
	 * @Description  公积金批量办理
	 * @Date 15:29 2023/5/8
	 * @Param
	 * @return
	**/
	@SneakyThrows
	@Operation(summary = "单个派增 权限：social_dispatchinfo_add", description = "单个派增")
	@PostMapping("/fundImportHandle")
	//@PreAuthorize("@pms.hasPermission('fund_import_handle')")
	public R<List<ErrorMessage>> fundImportHandle(@RequestBody MultipartFile file, @RequestParam(required = true)String mId) {
		YifuUser user = SecurityUtils.getUser();
		if (Common.isEmpty(user)) {
			return R.failed(CommonConstants.USER_FAIL);
		}
		// 获取redis分布式事务锁
		String key = CacheConstants.FUND_IMPORT_HANDLE_LOCK + CommonConstants.DOWN_LINE_STRING + user.getId();
		String requestId;
		try {
			requestId = RedisDistributedLock.getLock(key, "10");
		} catch (Exception e) {
			throw new RuntimeException(ResultConstants.NO_GETLOCK_DATA + CommonConstants.DOWN_LINE_STRING + e.getMessage());
		}
		try {
			if (Common.isNotNull(requestId)) {
				//主动释放锁
				TDispatchInfo tDispatchInfo = new TDispatchInfo();
				tDispatchInfo.setMId(mId);
				tDispatchInfo.setMenuInfo(mId);
				tDispatchInfo.setDeleteFlag(CommonConstants.ZERO_STRING);
				menuUtil.setAuthSql(user, tDispatchInfo);
				if (Common.isNotNull(tDispatchInfo.getAuthSql()) && tDispatchInfo.getAuthSql().contains(CommonConstants.A_DEPT_ID)) {
					tDispatchInfo.setAuthSql(tDispatchInfo.getAuthSql().replace(CommonConstants.A_DEPT_ID, "a.SETTLE_DOMAIN"));
				}
				tDispatchInfo.setCreateBy(user.getId());
				return tDispatchInfoService.fundImportHandle(file.getInputStream(),tDispatchInfo);
			} else {
				return R.failed(ResultConstants.NO_GETLOCK_DATA);
			}
		} finally {
			//主动释放锁
			RedisDistributedLock.unlock(key, requestId);
		}
	}

	/**
	 * 社保花名册导出标识变更为否
	 * @param  id
	 * @return R
	 */
	@Operation(summary = "社保花名册导出标识变更为否", description = "社保花名册导出标识变更为否")
	@SysLog("社保花名册导出标识变更为否" )
	@PostMapping("/updateExportSocialFlagById")
	public R<Boolean> updateExportSocialFlagById(@RequestParam(value = "id",required = true) String id
			,@RequestParam(value = "status",required = true) String status) {
		if (!CommonConstants.ZERO_STRING.equals(status)&& !CommonConstants.ONE_STRING.equals(status)){
			return R.failed(CommonConstants.PARAM_IS_NOT_EMPTY);
		}
		return tDispatchInfoService.updateExportSocialFlagById(id,status);
	}
	/**
	 * 公积金变更清册导出标识变更为否
	 * @param  id
	 * @return R
	 */
	@Operation(summary = "公积金变更清册导出标识变更为否", description = "公积金变更清册导出标识变更为否")
	@SysLog("公积金变更清册导出标识变更为否" )
	@PostMapping("/updateExportFundFlagById")
	public R<Boolean> updateExportFundFlagById(@RequestParam(value = "id",required = true) String id
			,@RequestParam(value = "status",required = true) String status) {
		if (!CommonConstants.ZERO_STRING.equals(status)&& !CommonConstants.ONE_STRING.equals(status)){
			return R.failed(CommonConstants.PARAM_IS_NOT_EMPTY);
		}
		return tDispatchInfoService.updateExportFundFlagById(id,status);
	}
}
