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

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
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.SysUser;
import com.yifu.cloud.plus.v1.yifu.archives.entity.MSetttleCustomerUser;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TCustomerInfo;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TSettleDomain;
import com.yifu.cloud.plus.v1.yifu.archives.service.MSetttleCustomerUserService;
import com.yifu.cloud.plus.v1.yifu.archives.service.TSettleDomainService;
import com.yifu.cloud.plus.v1.yifu.archives.utils.ListWrapper;
import com.yifu.cloud.plus.v1.yifu.archives.vo.CustomerForBusinessVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.CustomerOwnerSelectVo;
import com.yifu.cloud.plus.v1.yifu.archives.vo.TSettleDomainVo;
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.EmpBusinessConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.ServiceNameConstants;
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.RedisUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.vo.YifuUser;
import com.yifu.cloud.plus.v1.yifu.common.dapr.util.UpmsDaprUtils;
import com.yifu.cloud.plus.v1.yifu.common.security.util.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * B端接口-客户信息相关
 * @program: master
 * @description: b端控制器
 * @author: pwang
 * @create: 2020-08-25 11:07
 **/
@RestController
@AllArgsConstructor
@RequestMapping(value = "/customerBusiness/customerInfo")
@Tag(name = "B端接口-客户信息相关")
@Slf4j
public class CustomerBusinessContoller {

    private final TSettleDomainService tSettleDomainService;

    private final MSetttleCustomerUserService mSetttleCustomerUserService;

    private static final String CREATE_TIME_COLNUM = "CREATE_TIME"; //客户创建时间

    private final RedisUtil redisUtil;

	private final UpmsDaprUtils upmsDaprUtils;

	private final CacheManager cacheManager;

    /**
     * 简单分页查询
     * @param page 分页对象
     * @param tCustomerInfo 客户信息
     * @return
     */
    @Operation(description = "B端客户单位分页查询")
    @GetMapping("/customerPage")
    public R<IPage<TCustomerInfo>> getCustomerInfoPage(Page<TCustomerInfo> page, TCustomerInfo tCustomerInfo, String customerIdStr) {
        if (Common.isNotNull(customerIdStr)){
            tCustomerInfo.setCustomerIds(Common.initStrToList(customerIdStr,CommonConstants.COMMA_STRING));
        }
        page.addOrder(OrderItem.desc(CREATE_TIME_COLNUM));
        return  tSettleDomainService.getTCustomerInfoPageForB(page,tCustomerInfo);
    }

    /**
     * 简单分页查询
     *
     * @param page          分页对象
     * @param tSettleDomain 结算主体表
     * @return
     */
    @Operation(description = "B端结算主体简单分页查询")
    @GetMapping("/settleDomainPage")
    public R<IPage<TSettleDomainVo>> settleDomainPage(Page<TSettleDomainVo> page, TSettleDomainVo tSettleDomain, String customerIdStr) {
        YifuUser user = SecurityUtils.getUser();
        if(null == user){
            return R.failed(CommonConstants.USER_FAIL);
        }
        // 按客户ID查询结算主体
        if (Common.isNotNull(customerIdStr)){
            tSettleDomain.setCustomerIds(Common.initStrToList(customerIdStr,CommonConstants.COMMA_STRING));
        }else {
            // 按权限查询结算主体
            List<String> settleDomainIds;
            boolean flag = !SecurityUtils.isHaveAllOrg(ServiceNameConstants.CLIENT_ID_HR_B, user);
            if (flag) {
                settleDomainIds = user.getSettleIdList();
                if (Common.isEmpty(settleDomainIds)) {
                    return R.failed(EmpBusinessConstants.noSettleDomainAuth);
                }
                tSettleDomain.setSettleDomainIds(settleDomainIds);
            }
        }
        page.addOrder(OrderItem.desc("CREATE_TIME"));
        return  tSettleDomainService.getTSettleDomainPageB(page, tSettleDomain);
        }
    /**
     * 获取客户下的结算主体（未删除、不是审核不通过的）
	 * name = "customerId", value = "客户id"
     */
    @Operation(description = "获取客户下的结算主体")
    @GetMapping("/getSettleDomain/{customerId}")
    public R<List<TSettleDomain>> getSettleDomain(@PathVariable String customerId) {
        return  new R<>(tSettleDomainService.list(getSettleDomainWrapper(CollUtil.toList(customerId))));
    }

    /**
     * 保存客户结算主体关系
     */
    @Operation(description = "保存客户结算主体关系")
    @PostMapping("/batch/saveMSetttleCustomerUser")
    public R<List<TSettleDomain>> saveMSetttleCustomerUser(@Valid @RequestBody ListWrapper<MSetttleCustomerUser> mSetttleCustomerUser) {
        if(Common.isNotNull(mSetttleCustomerUser.getList())){
            //先删后增
            String userId = mSetttleCustomerUser.getList().get(0).getUserId();
            mSetttleCustomerUserService.remove(Wrappers.<MSetttleCustomerUser>lambdaQuery().eq(MSetttleCustomerUser::getUserId, userId));
            if(mSetttleCustomerUserService.saveBatch(mSetttleCustomerUser.getList())){
                //清除用户缓存
                R<SysUser> simpleUser = upmsDaprUtils.getSimpleUser(userId);
                if(null != simpleUser && null != simpleUser.getData()){
                    SysUser user = simpleUser.getData();
                    redisUtil.remove(ServiceNameConstants.UMPS_SERVICE + "_user_details::" + user.getUsername());
                    if( Common.isNotNull(user.getPhone())){
                        redisUtil.remove(ServiceNameConstants.UMPS_SERVICE + "_user_details_phone::" + user.getPhone());
                    }
					// 清空userinfo
					Objects.requireNonNull(cacheManager.getCache(CacheConstants.USER_DETAILS)).clear();
                }
                return R.ok();
            }else {
                return R.failed("保存失败，数据入库异常！");
            }
        }else{
            return R.failed("保存失败，对象为空！");
        }
    }
    /**
     * 获取用户回显数据
	 * name = "userId", value = "用户id")
     */
    @Operation(description = "获取用户回显数据")
    @GetMapping("/CustomerForBusinessVo/{userId}")
    public R<CustomerForBusinessVo> getCustomerForBusinessVo(@PathVariable String userId) {
        CustomerForBusinessVo result = new CustomerForBusinessVo();
            //查回显数据
            List<MSetttleCustomerUser> list = mSetttleCustomerUserService.list(Wrappers.<MSetttleCustomerUser>lambdaQuery().eq(MSetttleCustomerUser::getUserId, userId));
            if(Common.isNotNull(list)){
                //已有权限的结算主体
                List<String> setttleList = new ArrayList<>();
                List<String> customerList = new ArrayList<>();
                Map<String,String> customerMap = new HashMap<>();
                Map<String,String> settleMap = new HashMap<>();
                for(MSetttleCustomerUser cu :list){
                    settleMap.put(cu.getSettleId(),cu.getSettleId());
                    customerMap.put(cu.getCustomerId(),cu.getCustomerId());
                }
                if (Common.isNotNull(customerMap)){
                    customerList = customerMap.values().stream().collect(Collectors.toList());
                }
                if (Common.isNotNull(settleMap)){
                    setttleList = settleMap.values().stream().collect(Collectors.toList());
                }
                result.setHadSettle(setttleList);
                result.setHadCustomer(customerList);
                // 获取所有有权限的客户信息
                result.setCustomerList(tSettleDomainService.getTCustomerInfoForB(customerList));
                //获取该客户下的主体
                result.setSettleDomainList(tSettleDomainService.list(getSettleDomainWrapper(customerList)));
            }
          return new R<>(result);
    }
    /**
     * 获取结算主体的查询条件（未删除、非审核不通过的）
     * @Author pwang
     * @Date 2020-09-21 14:13
     * @param customerIds
     * @return
     **/
    private LambdaQueryWrapper<TSettleDomain> getSettleDomainWrapper(List<String> customerIds) {
        return Wrappers.<TSettleDomain>lambdaQuery().in(TSettleDomain::getCustomerId,customerIds).eq(TSettleDomain::getDeleteFlag,CommonConstants.ZERO_STRING);
    }

    /**
     * b端获取用户的结算主体 无分页
     * @param settleName, value = "结算主体名称"
     * @param limit, value = "最大返回条数，【1-50】之间的正整数,不传默认为20"
     * @return
     */
    @Operation(description = "获取项目-无分页")
    @GetMapping("/ownSettleDomainNoPage")
    public R<List<TSettleDomain>> ownSettleDomainNoPage(String settleName,Integer limit) {
        YifuUser user = SecurityUtils.getUser();
        if(null == user){
            return R.failed("非法用户！");
        }
        //管理员权限
        if(SecurityUtils.isHaveAllOrg(ServiceNameConstants.CLIENT_ID_HR_B,user)){
            //验证参数
            if(null == limit){
                limit = 20;
            }
            if( CommonConstants.dingleDigitIntArray[0] > limit  || 50 <= limit){
                return R.failed("参数传0到50的整数！");
            }
            //拼接条件
            LambdaQueryWrapper<TSettleDomain> wrapper = Wrappers.<TSettleDomain>lambdaQuery();
            if(Common.isNotNull(settleName)){
                wrapper.like(TSettleDomain::getDepartName,settleName);
            }
            wrapper.last("limit " + limit);
            return new R<>(tSettleDomainService.list(wrapper));
        }else{
            return new R<>(tSettleDomainService.getOwnSettleDomainNoPage(user.getId(),settleName));
        }
    }

    /**
     * b端获取用户的结算主体
	 * @ApiImplicitParam(name = "settleName", value = "结算主体名称"),
	 * @ApiImplicitParam(name = "limit", value = "最大返回条数，【1-50】之间的正整数,不传默认为20"
     */
    @Operation(description = "获取项目")
    @GetMapping("/ownSettleDomain")
    public R<IPage<TSettleDomainVo> > getOwnSettleDomain(Page<TSettleDomainVo> page, TSettleDomainVo vo) {
        YifuUser user = SecurityUtils.getUser();
        if(null == user){
            return R.failed("非法用户！");
        }
        //管理员权限
        /*if(SecurityUtils.isHaveAllOrg(ServiceNameConstants.CLIENT_ID_HR_B,user)){
            return new R(tSettleDomainService.getPage(page, vo));
        }else{
        }*/
		return tSettleDomainService.getOwnSettleDomain(page,user.getId(),vo.getDepartName());
	}

    /**
     * 获取权限内所有客户下拉项
     * @author fxj
     * @date 2021-11-03
     * @param page
     * @param customerName
     * @return
     */
    @Operation(description = "获取权限内所有客户下拉项")
    @GetMapping("/getCustomerOwnerPage")
    public R<IPage<CustomerOwnerSelectVo> > getCustomerOwnerPage(Page<CustomerOwnerSelectVo> page, String customerName) {
		YifuUser user = SecurityUtils.getUser();
		if(null == user){
			return R.failed("非法用户！");
		}
        return  tSettleDomainService.getCustomerOwnerPage(page,customerName,user.getId());
    }
}
