package com.yifu.cloud.plus.v1.yifu.salary.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysUser;
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.util.RandomUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.util.RedisUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.util.alisms.AliSmsResult;
import com.yifu.cloud.plus.v1.yifu.common.core.util.alisms.SmsUtil;
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.salary.entity.*;
import com.yifu.cloud.plus.v1.yifu.salary.service.*;
import com.yifu.cloud.plus.v1.yifu.salary.vo.AccountForWxVo;
import com.yifu.cloud.plus.v1.yifu.salary.vo.TSalarySetVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.web.bind.annotation.*;

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


@RestController
@RequiredArgsConstructor
@RequestMapping("/salaryEmployeeSelect")
@Tag(name = "c端员工查询接口工资表")
@EnableConfigurationProperties(DaprUpmsProperties.class)
public class TSalaryAccountPhoneController {

	private final TSalaryAccountService salaryAccountService;

	private final TSalaryAccountItemService salaryAccountItemService;

	private final TSalaryStandardSetService tSalaryStandardSetService;

	private final TSalaryStandardSetDetailService tSalaryStandardSetDetailService;

	private final TSalaryEmployeeService tSalaryEmployeeService;

	// 验证码存缓存里
	private final RedisUtil redisUtil;

	private final DaprUpmsProperties daprUpmsProperties;

	private static final String SORT_COL = "order by SALARY_MONTH desc,id desc";

	private static final String ITEM_SORT_COL = "order by JAVA_FIED_NAME desc,id";

	/**
	 * 只查普通薪资
	 *
	 * @param idNumber 身份证不能为空
	 * @param year     年为空查最新一条返回集合
	 * @return
	 * @Author hgw
	 * @Date 2022-12-12 16:51:13
	 **/
	@Operation(description = "获取工资报账信息")
	@GetMapping("/getSalaryAccount")
	public R<AccountForWxVo> getSalaryAccount(@RequestParam String idNumber, String year) {
		AccountForWxVo result = new AccountForWxVo();
		//处理身份证防止小写干扰
		idNumber = idNumber.toUpperCase();
		//空的查最新一条
		List<Map<String, Object>> sumByAccountId;
		Map<String, Object> map = new HashMap<>();
		if (Common.isEmpty(year)) {
			List<TSalaryAccount> list = salaryAccountService.list(Wrappers.<TSalaryAccount>lambdaQuery()
					.eq(TSalaryAccount::getEmpIdcard, idNumber)
					.eq(TSalaryAccount::getDeleteFlag, CommonConstants.ZERO_INT)
					.eq(TSalaryAccount::getSendStatus, CommonConstants.ONE_STRING)
					.eq(TSalaryAccount::getPaySettleFlag, CommonConstants.ZERO_STRING)
					.last(SORT_COL.concat(CommonConstants.LAST_ONE_SQL)));
			//查实发工资
			if (Common.isNotNull(list)) {
				sumByAccountId = salaryAccountItemService.getSumByAccountId(list);
				getMap(sumByAccountId, map);
				result.setStandAccountSumMap(map);
				result.setStandAccount(list);
			}
		} else {
			List<TSalaryAccount> list = salaryAccountService.list(Wrappers.<TSalaryAccount>lambdaQuery()
					.eq(TSalaryAccount::getEmpIdcard, idNumber)
					.eq(TSalaryAccount::getDeleteFlag, CommonConstants.ZERO_INT)
					.eq(TSalaryAccount::getSendStatus, CommonConstants.ONE_STRING)
					.eq(TSalaryAccount::getPaySettleFlag, CommonConstants.ZERO_STRING)
					.likeRight(TSalaryAccount::getSalaryMonth, year).last(SORT_COL));
			//查实发工资
			if (Common.isNotNull(list)) {
				sumByAccountId = salaryAccountItemService.getSumByAccountId(list);
				getMap(sumByAccountId, map);
				result.setStandAccountSumMap(map);
				result.setStandAccount(list);
			}
		}

		return new R<>(result);
	}

	private void getMap(List<Map<String, Object>> sumByAccountId, Map<String, Object> map) {
		if (Common.isNotNull(sumByAccountId)) {
			for (Map<String, Object> thisMap : sumByAccountId) {
				map.put((String) thisMap.get("key"), thisMap.get("value"));
			}
		}
	}

	/**
	 * @param id   主表id
	 * @param type 查询类型 0 普通工资 1 工程工资
	 * @return
	 * @Author pwang
	 * @Date 2020-08-10 23:26
	 **/
	@Operation(description = "获取工资明细信息")
	@GetMapping("/getSalaryAccountForm")
	public R<TSalarySetVo> getSalaryAccountForm(@RequestParam String id, Integer type) {
		//类型判断
		if (null == type) {
			return R.failed("查询类型不能为空");
		}
		//普通薪资查询
		if (CommonConstants.dingleDigitIntArray[0] == type) {
			TSalaryAccount account = salaryAccountService.getById(id);
			TSalarySetVo setVo = new TSalarySetVo();
			if (account != null) {
				List<TSalaryAccountItem> allTSalaryAccountItem = salaryAccountItemService.list(Wrappers.<TSalaryAccountItem>lambdaQuery()
						.eq(TSalaryAccountItem::getSalaryAccountId, id).last(ITEM_SORT_COL));
				TSalaryStandardSet ss = tSalaryStandardSetService.lambdaQuery()
						.eq(TSalaryStandardSet::getSalaryId, account.getSalaryFormId()).last(CommonConstants.LAST_ONE_SQL).one();
				if (ss != null && Common.isNotNull(ss.getId())) {
					List<TSalaryStandardSetDetail> detail = tSalaryStandardSetDetailService.list(
							Wrappers.<TSalaryStandardSetDetail>query().lambda().eq(TSalaryStandardSetDetail::getSetId, ss.getId())
									.last(" order by order_line asc "));
					ss.setDetailList(detail);
				}
				setVo.setSalarySet(ss);
				setVo.setItemList(allTSalaryAccountItem);
			}
			return new R<>(setVo);
		} else if (CommonConstants.dingleDigitIntArray[1] == type) {
			//工程工资查询 -- c端暂不要求
			return R.failed("暂不支持查工程工资敬请期待");
		} else {
			return R.failed("查询类型错误");
		}
	}

	/**
	 * 根据手机号获取员工信息
	 * hgw 2021-3-9 17:00:04
	 *
	 * @return
	 */
	@Operation(description = "根据手机号获取员工信息")
	@GetMapping("/getInfoByEmpPhone")
	public R<TSalaryEmployee> getInfoByEmpPhone(@RequestParam String empPhone) {
		if (Common.isEmpty(empPhone)) {
			return R.failed("手机号不能为空");
		}
		//查询员工信息
		TSalaryEmployee employee = tSalaryEmployeeService.getOne(Wrappers.<TSalaryEmployee>lambdaQuery()
				.eq(TSalaryEmployee::getEmpPhone, empPhone).last(CommonConstants.LAST_ONE_SQL));
		//判断是查到员工信息
		if (Common.isNotNull(employee) && Common.isNotNull(employee.getEmpIdcard())) {
			return this.getUserCount(employee);
		} else {
			return R.failed("未查到信息，请核实手机号！");
		}
	}

	/**
	 * @Description: 查询身份证是否已被占用
	 * @Author: hgw
	 * @Date: 2022/12/13 15:14
	 * @return: com.yifu.cloud.plus.v1.yifu.common.core.util.R<com.yifu.cloud.plus.v1.yifu.salary.entity.TSalaryEmployee>
	 **/
	private R<TSalaryEmployee> getUserCount(TSalaryEmployee em) {
		SysUser user = new SysUser();
		user.setUsername(em.getEmpIdcard());
		R<Integer> userCount = HttpDaprUtil.invokeMethodPost(daprUpmsProperties.getAppUrl(), daprUpmsProperties.getAppId()
				, "/user/inner/getCountByIdCard", user, Integer.class, SecurityConstants.FROM_IN);
		if (userCount != null && userCount.getData() != null && userCount.getData() > CommonConstants.ZERO_INT) {
			return R.other(CommonConstants.TWO_INT, "该身份已被绑定，请联系客服热线:0551 - 63535213！！");
		}
		return R.ok(em);
	}

	/**
	 * @param phone 手机号
	 * @Description: 发送C端验证码
	 * @Author: hgw
	 * @Date: 2021/3/9 16:48
	 * @return: com.yifu.cloud.v1.common.core.util.R<java.lang.String>
	 **/
	@PostMapping("/sendCCode")
	@ResponseBody
	public R<String> sendCCode(@RequestParam String phone) {
		// 获取验证码
		String code;
		if (null != redisUtil.get(CommonConstants.C_PREFIX.concat(phone))) {
			code = (String) redisUtil.get(CommonConstants.C_PREFIX.concat(phone));
		} else {
			code = RandomUtil.getSix();
		}
		// 发短信
		AliSmsResult result = SmsUtil.sendSms(phone, code);
		// 验证码存缓存
		if (AliSmsResult.SUCCESS_CODE.equals(result.getCode())) {
			redisUtil.set(CommonConstants.C_PREFIX.concat(phone), code, (long) 300);
			return R.ok(null, "验证码已发送");
		} else {
			return R.failed(null == result.getMessage() ? "获取验证码错误，告知管理员，阿里云短信配置错误！" : result.getMessage());
		}
	}

}
