package com.xxfc.platform.im.biz;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.BaseResponse;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.xxfc.platform.im.dto.CustomerServiceDTO;
import com.xxfc.platform.im.entity.CustomerService;
import com.xxfc.platform.im.mapper.CustomerServiceMapper;
import com.xxfc.platform.im.vo.CustomerServiceVO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

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

/**
 * @author libin
 * @version 1.0
 * @description
 * @data 2019/9/5 9:49
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CustomerServiceBiz extends BaseBiz<CustomerServiceMapper, CustomerService> {

    private final static String INIT_PASSWORD = "12345678";

    private final static String NICK_PRE_NAME = "XXKF";


    private final UserBiz userBiz;

    public CustomerServiceVO findById(Long id) {
        CustomerServiceVO customerServiceVO = new CustomerServiceVO();
        CustomerService customerService = mapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(customerService, customerServiceVO);
        return customerServiceVO;
    }

    /**
     * 添加客服
     *
     * @param customerServiceDTO
     */
    public void addCustomerService(CustomerServiceDTO customerServiceDTO) {
        CustomerService customerService = new CustomerService();
        BeanUtils.copyProperties(customerServiceDTO, customerService);

        if (Objects.isNull(customerServiceDTO.getId())) {
            customerService.setCreateTime(Instant.now().toEpochMilli());
            customerService.setName(String.format("%s%s", NICK_PRE_NAME, customerServiceDTO.getTelphone()));
            customerService.setIsDel(false);
            customerService.setPassword(StringUtils.isEmpty(customerServiceDTO.getPassword()) ? INIT_PASSWORD : customerServiceDTO.getPassword().trim().length() > 0 ? customerServiceDTO.getPassword() : INIT_PASSWORD);
            Map<String, Object> imMap = new HashMap<>(2);
            imMap.put("telephone", customerServiceDTO.getTelphone());
            imMap.put("password", DigestUtils.md5Hex(customerService.getPassword()));
            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);
            mapper.insertSelective(customerService);
        } else {
            customerService.setUpdateTime(Instant.now().toEpochMilli());
            if (!StringUtils.isEmpty(customerServiceDTO.getPassword())) {
                userBiz.updatePasswordByPhone(customerServiceDTO.getTelphone(), customerServiceDTO.getPassword());
            }
            mapper.updateByPrimaryKeySelective(customerService);
        }


    }

    public List<CustomerServiceVO> findAll() {
        List<CustomerServiceVO> customerServiceVOS = new ArrayList<>();

        Example example = new Example(CustomerService.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isDel", 0);
        List<CustomerService> customerServices = mapper.selectByExample(example);

        if (CollectionUtils.isNotEmpty(customerServices)) {
            CustomerServiceVO customerServiceVO;
            for (CustomerService customerService : customerServices) {
                customerServiceVO = new CustomerServiceVO();
                BeanUtils.copyProperties(customerService, customerServiceVO);
                customerServiceVOS.add(customerServiceVO);
            }
        }
        return customerServiceVOS;
    }

    /**
     * 删除客服
     *
     * @param id
     * @param imUserId
     */
    public void updateCustomerServiceIsDelToTrue(Long id, Integer imUserId) {
        CustomerService customerService = new CustomerService();
        customerService.setId(id);
        customerService.setIsDel(true);
        customerService.setUpdateTime(Instant.now().toEpochMilli());
        mapper.updateByPrimaryKeySelective(customerService);
        userBiz.deleteById(imUserId);
    }

    public void updatePasswordByPhone(String telphone, String password) {
        Example example = new Example(CustomerService.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("telphone", telphone);

        CustomerService customerService = new CustomerService();
        customerService.setPassword(DigestUtils.md5Hex(password));
        customerService.setUpdateTime(Instant.now().toEpochMilli());
        mapper.updateByExampleSelective(customerService, example);
    }

    public PageDataVO<CustomerServiceVO> findCustomerServiceWithPage(Integer page, Integer limit) {
        PageDataVO<CustomerServiceVO> dataVO = new PageDataVO<>();

        Example example = new Example(CustomerService.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isDel", false);

        PageDataVO<CustomerService> pageDataVO = PageDataVO.pageInfo(page, limit, () -> mapper.selectByExample(example));
        List<CustomerService> data = pageDataVO.getData();
        if (CollectionUtils.isEmpty(data)) {
            return dataVO;
        }

        List<CustomerServiceVO> customerServiceVOS = new ArrayList<>();
        CustomerServiceVO customerServiceVO;
        for (CustomerService customerService : data) {
            customerServiceVO = new CustomerServiceVO();
            BeanUtils.copyProperties(customerService, customerServiceVO);
            customerServiceVOS.add(customerServiceVO);
        }

        dataVO.setPageSize(pageDataVO.getPageSize());
        dataVO.setPageNum(pageDataVO.getPageNum());
        dataVO.setTotalPage(pageDataVO.getTotalPage());
        dataVO.setTotalCount(pageDataVO.getTotalCount());
        dataVO.setData(customerServiceVOS);
        return dataVO;
    }

    public CustomerServiceDTO findCustomerServiceById(Long id) {
        CustomerServiceDTO customerServiceDTO = new CustomerServiceDTO();
        CustomerService customerService = mapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(customerService, customerServiceDTO);
        return customerServiceDTO;
    }
}
