/*
 *    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.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysDict;
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.redis.RedisDistributedLock;
import com.yifu.cloud.plus.v1.yifu.common.core.util.*;
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.social.constants.PreDispatchConstants;
import com.yifu.cloud.plus.v1.yifu.social.entity.TPreDispatchInfo;
import com.yifu.cloud.plus.v1.yifu.social.service.TPreDispatchInfoService;
import com.yifu.cloud.plus.v1.yifu.social.vo.TPreDispatchExportVo;
import com.yifu.cloud.plus.v1.yifu.social.vo.TPreDispatchReduceVo;
import com.yifu.cloud.plus.v1.yifu.social.vo.TPreDispatchUpdateVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 预派单记录
 *
 * @author huyc
 * @date 2022-07-14 18:53:42
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/tpredispatchinfo" )
@Tag(name = "预派单记录管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
@Slf4j
public class TPreDispatchInfoController {

    private final  TPreDispatchInfoService tPreDispatchInfoService;

	private final MenuUtil menuUtil;

    /**
     * 简单分页查询
     * @param page 分页对象
     * @param tPreDispatchInfo 预派单记录
     * @return
     */
	@Operation(summary = "简单分页查询", description = "简单分页查询")
    @GetMapping("/page")
    public R<IPage<TPreDispatchInfo>> getTPreDispatchInfoPage(Page<TPreDispatchInfo> page, TPreDispatchInfo tPreDispatchInfo) {
		YifuUser user = SecurityUtils.getUser();
		menuUtil.setAuthSql(user, tPreDispatchInfo);
		if (Common.isNotNull(tPreDispatchInfo.getAuthSql()) && tPreDispatchInfo.getAuthSql().contains(CommonConstants.A_DEPT_ID)) {
			tPreDispatchInfo.setAuthSql(tPreDispatchInfo.getAuthSql().replace(CommonConstants.A_DEPT_ID, "a.DEPART_ID_ADD"));
		}
        return  new R<>(tPreDispatchInfoService.getTPreDispatchInfoPage(page,tPreDispatchInfo));
    }
    /**
     * 不分页查询
     * @param tPreDispatchInfo 预派单记录
     * @return
     */
    @Operation(summary = "不分页查询", description = "不分页查询")
    @PostMapping("/noPage" )
    public R<List<TPreDispatchInfo>> getTPreDispatchInfoNoPage(@RequestBody TPreDispatchInfo tPreDispatchInfo) {
        return R.ok(tPreDispatchInfoService.list(Wrappers.query(tPreDispatchInfo)));
    }

    /**
     * 通过id查询预派单记录
     * @param id id
     * @return R
     */
    @Operation(summary = "通过id查询", description = "通过id查询：hasPermission('social_tpredispatchinfo_get')")
    @GetMapping("/{id}" )
    public R<TPreDispatchInfo> getById(@PathVariable("id" ) String id) {
        return R.ok(tPreDispatchInfoService.getById(id));
    }

    /**
     * 新增预派单记录
     * @param tPreDispatchInfo 预派单记录
     * @return R
     */
    @Operation(summary = "新增预派单记录", description = "新增预派单记录：hasPermission('social_tpredispatchinfo_add')")
    @SysLog("新增预派单记录" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('social_tpredispatchinfo_add')" )
    public R<Boolean> save(@RequestBody TPreDispatchInfo tPreDispatchInfo) {
        return R.ok(tPreDispatchInfoService.save(tPreDispatchInfo));
    }

    /**
     * 修改预派单记录
     * @param tPreDispatchInfo 预派单记录
     * @return R
     */
    @Operation(summary = "修改预派单记录", description = "修改预派单记录：hasPermission('social_tpredispatchinfo_edit')")
    @SysLog("修改预派单记录" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('social_tpredispatchinfo_edit')" )
    public R<Boolean> updateById(@RequestBody TPreDispatchInfo tPreDispatchInfo) {
        return tPreDispatchInfoService.update(tPreDispatchInfo);
    }

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

	/**
	 * 修改资料是否提交：0 是 1  否
	 * @Author huyc
	 * @Date 2022-07-18
	 * @param ids
	 * @param status 0 是 1 否
	 * @return R
	 */
	@Operation(summary = "修改资料是否提交", description = "修改资料是否提交：status 0 是 1 否")
	@SysLog("修改资料是否提交")
	@PostMapping("/modifyDataSubmitStatus")
	public R<Boolean> modifyDataSubmitStatus(@RequestParam(value = "ids")String ids,
											 @RequestParam(value = "status")String status) {
		return tPreDispatchInfoService.modifyDataSubmitStatus(ids,status);
	}
	/**
	 * 清空预派单默认的派单合同信息
	 * @Author huyc
	 * @Date 2022-07-18
	 * @param ids
	 * @return R
	 **/
	@Operation(summary = "清空预派单默认的派单合同信息", description = "清空预派单默认的派单合同信息(social_tpredispatchinfo_edit)")
	@SysLog("清空预派单默认的派单合同信息")
	@PostMapping("/clearContractInfo")
	@PreAuthorize("@pms.hasPermission('social_tpredispatchinfo_edit')")
	public R<Boolean> clearContractInfo(@RequestParam(value = "ids")String ids) {
		return tPreDispatchInfoService.clearContractInfo(ids);
	}

	/**
	 * 更新预派单是否派单状态
	 * @Author huyc
	 * @Date 2022-07-18
	 * @param id
	 * @param dispatchFlag 0 派单  1  不派单
	 * @param cancelRemark 不派单 时填写
	 * @return R
	 **/
	@Operation(summary = "更新预派单是否派单状态", description = "更新预派单是否派单状态")
	@SysLog("更新预派单是否派单状态")
	@PostMapping("/updateDispatchFlag")
	public R<Boolean> updateDispatchFlag(@RequestParam(value = "id")String id,
										 @RequestParam(value = "dispatchFlag")String dispatchFlag,
										 @RequestParam(value = "cancelRemark",required = false)String cancelRemark) {
		return tPreDispatchInfoService.updateDispatchFlag(id,dispatchFlag,cancelRemark);
	}

	/**
	 * 单个派单
	 * @Author huyc
	 * @Date 2022-07-18
	 * @param id
	 * @return R
	 */
	@Operation(summary = "单个派单:按创建人和ID", description = "单个派单:按创建人和ID")
	@PostMapping("/dispatchById")
	@PreAuthorize("@pms.hasPermission('social_tpredispatchinfo_dispatch')")
	public R<Boolean> dispatchById(@RequestParam(value = "id")String id) {
		return tPreDispatchInfoService.dispatchById(id);
	}

	/**
	 * 一键派单
	 * @Author huyc
	 * @Date 2022-07-18
	 * @return R
	 */
	@Operation(summary = "一键派单:按创建人查找正常未派单的数据", description = "一键派单:按创建人查找正常未派单的数据")
	@PostMapping("/oneKeyToDispatch")
	@PreAuthorize("@pms.hasPermission('social_tpredispatchinfo_dispatch')")
	public R oneKeyToDispatch(@RequestBody List<String> idList) {
		return tPreDispatchInfoService.oneKeyToDispatch(idList);
	}

	/**
	 * 预派单批量新增派增
	 * @Author huyc
	 * @Date 2022-07-18
	 * @param jsonString
	 * @param socialHouse 社保户
	 * @param departId 项目ID
	 * @return
	 **/
	@Operation(summary = "预派单批量新增派增", description = "预派单批量新增派增")
	@SysLog("预派单批量新增派增")
	@PostMapping("/analysisJsonStringImportAdd")
	@PreAuthorize("@pms.hasPermission('social_tpredispatchinfo_importAddList')")
	public R analysisJsonStringImportAdd(@RequestBody String jsonString,
										 @RequestParam(value = "socialHouse",required = false) String socialHouse,
										 @RequestParam(value = "fundHouse",required = false) String fundHouse
			, @RequestParam String departId) {
		YifuUser user = SecurityUtils.getUser();
		if (null == user || null == user.getId()) {
			return R.failed(CommonConstants.USER_FAIL);
		}
		// 获取redis分布式事务锁
		String key = CacheConstants.PAYMENT_PRE_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());
		}
		if (Common.isNotNull(requestId)) {
			ExcelUtil<TPreDispatchInfo> util1 = null;
			try {
				String json = jsonString.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
				jsonString = URLDecoder.decode(json, CommonConstants.UTF8).replace("=", "");
				util1 = new ExcelUtil<>(TPreDispatchInfo.class);
				util1.getJsonStringToList(jsonString, null);
				List<TPreDispatchInfo> listInfo = util1.getEntityList();
				//用于返回错误信息
				List<ErrorMessage> errorInfo = new ArrayList<>();
				if (null != util1.getErrorInfo() && !util1.getErrorInfo().isEmpty()) {
					for (ErrorMessage errorMessage: util1.getErrorInfo()) {
						errorInfo.add(errorMessage);
					}
				}
				if (null != listInfo && !listInfo.isEmpty()) {
					errorInfo = tPreDispatchInfoService.batchSavePreDisPatchAdd(listInfo, user,socialHouse,fundHouse,
							departId,errorInfo);
				} else {
					errorInfo.add(new ErrorMessage(null, CommonConstants.DATA_CAN_NOT_EMPTY));
				}
				List<ErrorMessage> newErrorList = errorInfo.stream().sorted(Comparator.comparing(ErrorMessage::getLineNum))
						.collect(Collectors.toList());
				return R.ok(newErrorList);
			} catch (Exception e) {
				e.printStackTrace();
				return R.failed(PreDispatchConstants.DATA_IMPORT_ANALYSIS_ERROR);
			}finally {
				//主动释放锁
				RedisDistributedLock.unlock(key, requestId);
			}
		} else {
			return R.failed(ResultConstants.NO_GETLOCK_DATA);
		}
	}

	/**
	 * 预派单批量新增派减
	 * @Author huyc
	 * @Date 2022-07-18
	 * @param jsonString
	 * @return
	 **/
	@Operation(summary = "预派单批量新增派减", description = "预派单批量新增派减")
	@SysLog("预派单批量新增派减")
	@PostMapping("/analysisJsonStringImportReduce")
	@PreAuthorize("@pms.hasPermission('social_tpredispatchinfo_importAddList')")
	public R analysisJsonStringImportReduce(@RequestBody String jsonString) {
		YifuUser user = SecurityUtils.getUser();
		if (null == user || null == user.getId()) {
			return R.failed(CommonConstants.USER_FAIL);
		}
		ExcelUtil<TPreDispatchReduceVo> util1 = null;
		try {
			String json = jsonString.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
			jsonString = URLDecoder.decode(json, CommonConstants.UTF8).replace("=", "");
			util1 = new ExcelUtil<>(TPreDispatchReduceVo.class);
			util1.getJsonStringToList(jsonString, null);
			List<TPreDispatchReduceVo> listInfo = util1.getEntityList();
			//用于返回错误信息
			List<ErrorMessage> errorInfo = new ArrayList<>();
			if (null != util1.getErrorInfo() && !util1.getErrorInfo().isEmpty()) {
				for (ErrorMessage errorMessage: util1.getErrorInfo()) {
					errorInfo.add(errorMessage);
				}
			}
			if (null != listInfo && !listInfo.isEmpty()) {
				tPreDispatchInfoService.batchSavePreDisPatchReduce(listInfo, user, errorInfo);
			} else {
				errorInfo.add(new ErrorMessage(null, CommonConstants.DATA_CAN_NOT_EMPTY));
			}
			List<ErrorMessage> newErrorList = errorInfo.stream().sorted(Comparator.comparing(ErrorMessage::getLineNum))
					.collect(Collectors.toList());
			return R.ok(newErrorList);
		} catch (Exception e) {
			log.error("预派单批量导入派减",e);
			return R.failed(PreDispatchConstants.DATA_IMPORT_ANALYSIS_ERROR);
		}
	}

	/**
	 * 预派单批量更新
	 * @param jsonString
	 * @Author huyc
	 * @Date 2022-07-18
	 * @return
	 **/
	@Operation(summary = "预派单批量更新", description = "预派单批量更新")
	@SysLog("预派单批量更新")
	@PostMapping("/analysisJsonStringUpdate")
	@PreAuthorize("@pms.hasPermission('social:tpredispatchinfo_updateList')")
	public R analysisJsonStringUpdate(@RequestBody String jsonString) {
		YifuUser user = SecurityUtils.getUser();
		if (null == user || null == user.getId()) {
			return R.failed(CommonConstants.USER_FAIL);
		}
		ExcelUtil<TPreDispatchUpdateVo> util1 = null;
		R<List<SysDict>> res = null;
		Map<String, String> dicMap = new HashMap<>();
		try {
			String json = jsonString.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
			jsonString = URLDecoder.decode(json, CommonConstants.UTF8).replace("=", "");
			util1 = new ExcelUtil<>(TPreDispatchUpdateVo.class);
			Map<String, String> dicObj = (Map<String, String>) RedisUtil.redis.opsForValue()
					.get(CacheConstants.DICT_DETAILS
							+ CommonConstants.COLON_STRING
							+ "status_flag");
			if (Common.isNotNull(dicObj)) {
				for (String key : dicObj.keySet()) {
					dicMap.put("status_flag" + CommonConstants.DOWN_LINE_STRING + dicObj.get(key), key);
				}
			}
			util1.getJsonStringToList(jsonString, dicMap);
			List<TPreDispatchUpdateVo> listInfo = util1.getEntityList();
			//用于返回错误信息
			List<ErrorMessage> errorInfo = new ArrayList<>();
			if (null != util1.getErrorInfo() && !util1.getErrorInfo().isEmpty()) {
				for (ErrorMessage errorMessage: util1.getErrorInfo()) {
					errorInfo.add(errorMessage);
				}
			}
			if (null != listInfo && !listInfo.isEmpty()) {
				tPreDispatchInfoService.batchUpdatePreDisPatch(listInfo, user, errorInfo);
			} else {
				errorInfo.add(new ErrorMessage(null, CommonConstants.DATA_CAN_NOT_EMPTY));
			}
			List<ErrorMessage> newErrorList = errorInfo.stream().sorted(Comparator.comparing(ErrorMessage::getLineNum))
					.collect(Collectors.toList());
			return R.ok(newErrorList);
		} catch (Exception e) {
			log.error("预派单批量更新",e);
			return R.failed(PreDispatchConstants.DATA_IMPORT_ANALYSIS_ERROR);
		}
	}

	/**
	 * 预派单查询导出数据的中文字段
	 * @Author huyc
	 * @Date 2022-07-18
	 * @return
	 **/
	@Operation(summary = "预派单查询导出数据的中文字段", description = "预派单查询导出数据的中文字段")
	@GetMapping("/getPreDispatchExportVoFieldName")
	public R<List<String>> getPreDispatchExportVoFieldName() {
		return ExcelUtil.getExportfieldsName(TPreDispatchExportVo.class);
	}

	/**
	 * 导出预派单
	 * @Author huyc
	 * @Date 2022-07-18
	 * @param preDispatchInfo
	 **/
	@PostMapping("/doexportPreDispatch")
	@Operation(summary = "导出预派单", description = "导出预派单")
	@SysLog("导出预派单")
	@PreAuthorize("@pms.hasPermission('social:tpredispatchinfo_doexportPreDispatch')")
	public void doexportPreDispatch(HttpServletResponse response,
									@RequestBody(required = false) TPreDispatchInfo preDispatchInfo) {
		YifuUser user = SecurityUtils.getUser();
		menuUtil.setAuthSql(user, preDispatchInfo);
		if (Common.isNotNull(preDispatchInfo.getAuthSql()) && preDispatchInfo.getAuthSql().contains(CommonConstants.A_DEPT_ID)) {
			preDispatchInfo.setAuthSql(preDispatchInfo.getAuthSql().replace(CommonConstants.A_DEPT_ID, "a.DEPART_ID_ADD"));
		}
		tPreDispatchInfoService.doexportPreDispatch(response,preDispatchInfo);
	}
}
