package com.xxfc.platform.im.biz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.BaseResponse;
import com.xxfc.platform.im.dto.CustomerServiceDTO;
import com.xxfc.platform.im.entity.CustomerService;
import com.xxfc.platform.im.model.User;
import com.xxfc.platform.im.repos.CustomerServiceRepository;
import com.xxfc.platform.im.vo.CustomerServiceVO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;

import static org.springframework.data.mongodb.core.query.Query.query;
import static org.springframework.data.mongodb.core.query.Update.update;

/**
 * @author libin
 * @version 1.0
 * @description
 * @data 2019/9/5 9:49
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CustomerServiceMGBiz {

    private final static String INIT_PASSWORD="12345678";

    private final static String NICK_PRE_NAME="XXKF";

    private final CustomerServiceRepository customerServiceRepository;

    private final MongoTemplate mongoTemplate;

    private final UserBiz userBiz;

     public CustomerServiceVO findById(String id){
         CustomerServiceVO customerServiceVO = new CustomerServiceVO();
         customerServiceRepository.findById(id).ifPresent(customerService -> {
             BeanUtils.copyProperties(customerService,customerServiceVO);
         });
         Map<Integer, User> imMap = userBiz.findAllByImUserIds(Arrays.asList(customerServiceVO.getImUserId()));
         User user = imMap.get(customerServiceVO.getImUserId());
         customerServiceVO.setPassword(user.getPassword());
         return customerServiceVO;
     }

    /**
     * 添加客服
     * @param customerServiceDTO
     */
     public void addCustomerService(CustomerServiceDTO customerServiceDTO){
         CustomerService customerService = new CustomerService();
         BeanUtils.copyProperties(customerServiceDTO,customerService);
         customerService.setCreateTime(Instant.now().toEpochMilli());
         customerService.setName(String.format("%s%s",NICK_PRE_NAME,customerServiceDTO.getTelphone()));
         customerService.setIsDel(false);

         Map<String,Object> imMap  = new HashMap<>(2);
         imMap.put("telephone",customerServiceDTO.getTelphone());
         imMap.put("password",INIT_PASSWORD);
         imMap.put("nickname",customerService.getName());
         BaseResponse imResponse = userBiz.register(imMap);
         String imResult = imResponse.getMessage();
         JSONObject jsonObject = JSON.parseObject(imResult);
         Map<String,Object> data = (Map<String, Object>) jsonObject.get("data");
         Object userId = data.get("userId");
         if (Objects.isNull(userId)){
             throw new BaseException("注册失败");
         }
         customerService.setImUserId((Integer)userId);
         customerServiceRepository.save(customerService);
     }

    /**
     *  1: mongoTemplate.find(Query.query(Criteria.where("isDel").is(false)), CustomerService.class);
     *
     *  2. customerServiceRepository.findByIsDelEquals(false);
     * @return
     */
    public List<CustomerServiceVO> findAll() {
          List<CustomerServiceVO> customerServiceVOS = new ArrayList<>();

        CustomerService customer_service = new CustomerService();
        Example<CustomerService> customerServiceExample = Example.of(customer_service, ExampleMatcher.matchingAll());
        List<CustomerService> customerServices = customerServiceRepository.findAll(customerServiceExample);

          CustomerServiceVO customerServiceVO;
         if (CollectionUtils.isNotEmpty(customerServices)){
             List<Integer> imUserIds = customerServices.stream().map(CustomerService::getImUserId).collect(Collectors.toList());
             Map<Integer, User> imMap = userBiz.findAllByImUserIds(imUserIds);
             for (CustomerService customerService : customerServices) {
                  customerServiceVO = new CustomerServiceVO();
                  BeanUtils.copyProperties(customerService,customerServiceVO);
                  User user = imMap.get(customerService.getImUserId());
                   if (Objects.nonNull(user)){
                       customerServiceVO.setPassword(user.getPassword());
                   }
                  customerServiceVOS.add(customerServiceVO);
             }
         }
        return customerServiceVOS;
    }

    /**
     * 删除客服
     * @param id
     * @param imUserId
     */
    public void updateCustomerServiceIsDelToTrue(String id,Integer imUserId){
        Query query = query(Criteria.where("_id").is(id));
        Update update = update("is_del", true).set("update_time",Instant.now().toEpochMilli());
        mongoTemplate.updateFirst(query, update, Map.class, "customer_service");
        userBiz.deleteById(imUserId);
    }
}
