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

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysDictItem;
import com.yifu.cloud.plus.v1.yifu.archives.constants.EmployeeConstants;
import com.yifu.cloud.plus.v1.yifu.archives.entity.FddContractAttachInfo;
import com.yifu.cloud.plus.v1.yifu.archives.service.FddContractAttachInfoService;
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.ErrorMessage;
import com.yifu.cloud.plus.v1.yifu.common.core.util.ExcelUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import com.yifu.cloud.plus.v1.yifu.common.dapr.config.DaprUpmsProperties;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.HttpDaprUtil;
import com.yifu.cloud.plus.v1.yifu.common.log.annotation.SysLog;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.security.access.prepost.PreAuthorize;
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 org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 法大大合同附属信息表
 *
 * @author fxj
 * @date 2022-06-28 16:24:12
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/fddcontractattachinfo" )
@Tag(name = "法大大合同附属信息表管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
@Slf4j
@EnableConfigurationProperties(DaprUpmsProperties.class)
public class FddContractAttachInfoController {

    private final FddContractAttachInfoService fddContractAttachInfoService;

	private final DaprUpmsProperties daprUpmsProperties;

    /**
     * 分页查询
     * @param page 分页对象
     * @param fddContractAttachInfo 法大大合同附属信息表
     * @return
     */
    @Operation(summary = "分页查询", description = "分页查询")
    @GetMapping("/page" )
    public R getFddContractAttachInfoPage(Page page, FddContractAttachInfo fddContractAttachInfo) {
        return R.ok(fddContractAttachInfoService.getFddContractAttachInfoPage(page, fddContractAttachInfo));
    }

    /**
     * 通过id查询法大大合同附属信息表
     * @param id id
     * @return R
     */
    @Operation(summary = "通过id查询", description = "通过id查询：hasPermission('demo_fddcontractattachinfo_get')")
    @GetMapping("/{id}" )
    public R getById(@PathVariable("id" ) String id) {
        return R.ok(fddContractAttachInfoService.getById(id));
    }

    /**
     * 新增法大大合同附属信息表
     * @param fddContractAttachInfo 法大大合同附属信息表
     * @return R
     */
    @Operation(summary = "新增法大大合同附属信息表", description = "新增法大大合同附属信息表：hasPermission('demo_fddcontractattachinfo_add')")
    @SysLog("新增法大大合同附属信息表" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('demo_fddcontractattachinfo_add')" )
    public R save(@RequestBody FddContractAttachInfo fddContractAttachInfo) {
        return R.ok(fddContractAttachInfoService.save(fddContractAttachInfo));
    }

    /**
     * 修改法大大合同附属信息表
     * @param fddContractAttachInfo 法大大合同附属信息表
     * @return R
     */
    @Operation(summary = "修改法大大合同附属信息表", description = "修改法大大合同附属信息表：hasPermission('demo_fddcontractattachinfo_edit')")
    @SysLog("修改法大大合同附属信息表" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('demo_fddcontractattachinfo_edit')" )
    public R updateById(@RequestBody FddContractAttachInfo fddContractAttachInfo) {
        return R.ok(fddContractAttachInfoService.updateById(fddContractAttachInfo));
    }

    /**
     * 通过id删除法大大合同附属信息表
     * @param id id
     * @return R
     */
    @Operation(summary = "通过id删除法大大合同附属信息表", description = "通过id删除法大大合同附属信息表：hasPermission('demo_fddcontractattachinfo_del')")
    @SysLog("通过id删除法大大合同附属信息表" )
    @DeleteMapping("/{id}" )
    @PreAuthorize("@pms.hasPermission('demo_fddcontractattachinfo_del')" )
    public R removeById(@PathVariable String id) {
        return R.ok(fddContractAttachInfoService.removeById(id));
    }

	/**
	 * @param jsonString
	 * @Author: huyc
	 * @Date: 2022/6/30
	 * @Description: 法大大合同基础信息更新
	 * @return: com.yifu.cloud.v1.common.core.util.R<java.lang.Boolean>
	 **/
	@Operation(summary = "法大大合同基础信息新增", description = "法大大合同基础信息新增")
	@SysLog("法大大合同基础信息新增")
	@PostMapping("/batchAddFddEmpInfo")
	public R batchAddFddEmpInfo(@RequestBody String jsonString) {

		R<Map<String,List<SysDictItem>>> res = null;

		ExcelUtil<FddContractAttachInfo> util1 = null;
		try {
//			// 调用字典服务，渲染字典值
//			res = HttpDaprUtil.invokeMethodPost(daprUpmsProperties.getAppUrl(), daprUpmsProperties.getAppId()
//					, "/dict/inner/getDictList", null, Map.class, SecurityConstants.FROM_IN);
//
//			Map<String, String> dicMap = new HashMap<>();
//			if (null != res.getData().get("data")) {
//				for (SysDictItem dict : res.getData().get("data")) {
//					dicMap.put(dict.getType() + CommonConstants.DOWN_LINE_STRING + dict.getLabel(), dict.getValue());
//				}
//			}

			jsonString = URLDecoder.decode(jsonString, CommonConstants.UTF8).replace("=", "");
			util1 = new ExcelUtil<>(FddContractAttachInfo.class);
			//传参字典数据MAP具体见方法实现
			util1.getJsonStringToList(jsonString, null);
			if (null != util1.getErrorInfo() && !util1.getErrorInfo().isEmpty()) {
				return R.failed(util1.getErrorInfo(),"数据异常");
			} else {
				if (null != util1.getEntityList()) {
					List<ErrorMessage> errorInfo = fddContractAttachInfoService.batchAdd(util1.getEntityList());
					Map<String,Object> variableMap = new HashMap<>();
					Map<Integer,Object> map = new HashMap<>();
					boolean allExitContract = errorInfo.stream().allMatch(e-> e.getMessage().equals("存在“在用”的合同"));
					if (allExitContract) {
						variableMap.put("allMatch","true");
						for (ErrorMessage errorMessage :errorInfo){
							map.put(errorMessage.getLineNum(),util1.getEntityList().get(errorMessage.getLineNum()-2));
						}
						variableMap.put("data",map);
						return R.ok(variableMap);
					}
					return new R<>(CommonConstants.dingleDigitIntArray[1], "", errorInfo);
				} else {
					return R.ok(null,"无数据可导入");
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			return R.failed("导入数据失败");
		}
	}

	/**
	 * @param jsonString
	 * @Author: huyc
	 * @Date: 2022/6/30
	 * @Description: 法大大合同基础信息更新
	 * @return: com.yifu.cloud.v1.common.core.util.R<java.lang.Boolean>
	 **/
	@Operation(summary = "法大大合同基础信息更新", description = "法大大合同基础信息更新")
	@SysLog("法大大合同基础信息更新")
	@PostMapping("/batchUpdateFddEmpInfo")
	public R batchUpdateFddEmpInfo(@RequestBody String jsonString) {

		R<List<SysDictItem>> res = null;

		ExcelUtil<FddContractAttachInfo> util1 = null;

		try {
			// 调用字典服务，渲染字典值
			res = HttpDaprUtil.invokeMethodPost(daprUpmsProperties.getAppUrl(), daprUpmsProperties.getAppId()
					, "/dict/inner/getDictList", null, Map.class, SecurityConstants.FROM_IN);

			Map<String, String> dicMap = new HashMap<>();
			if (null != res.getData()) {
				for (SysDictItem dict : res.getData()) {
					dicMap.put(dict.getType() + CommonConstants.DOWN_LINE_STRING + dict.getLabel(), dict.getValue());
				}
			}

			jsonString = URLDecoder.decode(jsonString, CommonConstants.UTF8).replace("=", "");
			util1 = new ExcelUtil<>(FddContractAttachInfo.class);
			//传参字典数据MAP具体见方法实现
			util1.getJsonStringToList(jsonString, dicMap);
			if (null != util1.getErrorInfo() && !util1.getErrorInfo().isEmpty()) {
				return R.failed(util1.getErrorInfo(),"");
			} else {
				if (null != util1.getEntityList()) {
					List<ErrorMessage> errorInfo = fddContractAttachInfoService.batchUpdate(util1.getEntityList());
					return R.ok(errorInfo,"数据导入解析成功！");
				} else {
					return R.ok(null,EmployeeConstants.NO_DATA_UPDATE);
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			return R.failed(EmployeeConstants.DATA_UPDATE_FAIL);
		}
	}

	/**
	 * @param entityList
	 * @Author: huyc
	 * @Date: 2022/06/30
	 * @Description: 批量发送法大大电子合同定稿任务
	 * @return: com.yifu.cloud.v1.common.core.util.R<java.lang.String>
	 **/
	@Operation(summary = "批量发送法大大电子合同定稿任务", description = "批量发送法大大电子合同定稿任务")
	@SysLog("批量发送法大大电子合同定稿任务")
	@PostMapping("/sendTask")
	public R sendTask(@RequestBody List<FddContractAttachInfo> entityList) {
		if (null == entityList) {
			return R.failed("数据为空！");
		}
		List<ErrorMessage> errorInfo = fddContractAttachInfoService.sendTask(entityList);
		return R.ok(errorInfo);
	}
}
