package com.house365.ws.interfaces.impl;

import com.house365.beans.entity.CustomerEntity;
import com.house365.beans.entity.ExternalCustomerCallbackLogEntity;
import com.house365.beans.entity.ExternalCustomerEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.commons.system.HttpClientUtil;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.web.util.MemoryPropertyPlaceholderConfigurer;
import com.house365.ws.beans.request.MapListRequest;
import com.house365.ws.beans.response.MapListResponse;
import com.house365.ws.dao.mapper.ExternalCusCallLogMapper;
import com.house365.ws.dao.mapper.ExternalCustomerMapper;
import com.house365.ws.dao.mapper.UserMapper;
import com.house365.ws.interfaces.server.IExternalCustomerInterface;
import com.house365.ws.system.ReturnResult;
import com.house365.ws.util.OperateLogUtils;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.*;

/**
 * @author Created by Administrator on 2020/6/30.
 */
@Service("externalCustomer")
public class ExternalCustomerImpl implements IExternalCustomerInterface {

    private static final Logger logger = LoggerFactory.getLogger(CustomerCallbackLogImpl.class);
    private final String CRM_URL_PREFIX = "http://218.94.115.131:97";

    @Autowired
    private ExternalCustomerMapper mapper;
    @Autowired
    private ExternalCusCallLogMapper callLogMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OperateLogUtils logUtils;

    @Override
    public ExternalCustomerEntity queryById(int id) {
        return mapper.queryById(id);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int save(ExternalCustomerEntity entity) {
        mapper.save(entity);
        int id = entity.getId();
        //新增客户新增日志
        logUtils.saveExterCustomerLog(entity, 1, entity.getManagerId(), entity.getManagerName());
        return id;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void update(ExternalCustomerEntity entity, UserEntity userEntity) {
        int id = entity.getId();
        ExternalCustomerEntity oldEntity = mapper.queryById(id);
        mapper.update(entity);
        ExternalCustomerEntity newEntity = mapper.queryById(id);
        //调用工具类添加日志方法
        logUtils.extRecordOperateLog(oldEntity, newEntity, id, userEntity.getId(), userEntity.getRealName());
    }

    @Override
    public List<ExternalCustomerEntity> queryByConditions(Map<String, Object> map) {
        List<ExternalCustomerEntity> list = mapper.queryByConditions(map);
        if (CollectionUtils.isNotEmpty(list)) {
            return list;
        }
        return Collections.emptyList();
    }

    @Override
    public MapListResponse list(MapListRequest request) {
        MapListResponse response = new MapListResponse();

        Map<String, Object> map = new HashMap<>(10);
        Map<String, Object> searchParams = request.getSearchParams();
        int start = 100 * (request.getPaging().getCurrentPage() - 1);
        map.put("city", searchParams.get("city"));
        map.put("start", start);
        map.put("limit", 100);
        map.put("name", searchParams.get("name"));
        map.put("phone", searchParams.get("phone"));
        map.put("managerName", searchParams.get("managerName"));
        map.put("content", searchParams.get("remark"));
        map.put("startTime", searchParams.get("createTimeStart"));
        if (null != searchParams.get("createTimeEnd") && StringUtils.isNotBlank(searchParams.get("createTimeEnd").toString())) {
            String endTime = searchParams.get("createTimeEnd") + " 23:59:59";
            map.put("endTime", endTime);
        }
        map.put("callStartTime", searchParams.get("lastCallTimeStart"));
        if (null != searchParams.get("lastCallTimeEnd") && StringUtils.isNotBlank(searchParams.get("lastCallTimeEnd").toString())) {
            String endTime = searchParams.get("lastCallTimeEnd") + " 23:59:59";
            map.put("callEndTime", endTime);
        }
        map.put("buyIntention", searchParams.get("buyIntention"));
        int userId = Integer.valueOf(searchParams.get("userId").toString());
        if (userId != 1) {
            map.put("createId", userId);
        }
        if (null != searchParams.get("orderByTime")) {
            String sort = searchParams.get("orderByTime").toString();
            switch (sort) {
                case "1":
                    map.put("sort", 1);
                    break;
                case "2":
                    map.put("sort", 2);
                    break;
                case "3":
                    map.put("sort", 3);
                    break;
                case "4":
                    map.put("sort", 4);
                    break;
                default:
                    map.put("sort", 1);
                    break;
            }
        } else {
            map.put("sort", 1);
        }

        List<Map<String, Object>> list = mapper.queryList(map);
        if (CollectionUtils.isNotEmpty(list)) {
            for (Map<String, Object> m : list) {
                int customerId = Integer.parseInt(m.get("id").toString());
                Map<String, Object> searchMap = new HashMap<>(5);
                searchMap.put("customerId", customerId);
                List<ExternalCustomerCallbackLogEntity> callLogList = callLogMapper.queryByConditions(searchMap);
                m.put("callbackLogEntities", callLogList);
            }
        }

        int count = mapper.queryCount(map);
        request.getPaging().setRecords(count);
        response.setPaging(request.getPaging());
        response.setObjectList(list);
        response.setResultCode(ReturnResult.SUCCESS.getResultCode());
        response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());

        return response;
    }

    /**
     * 拨打回访电话
     *
     * @param memPhone
     * @param customerId
     * @param userId     唯一标识
     * @return 通过ID获取CustomerCallbackLog响应
     */
    @Override
    public Integer calling(String memPhone, Integer customerId, Integer userId) {
        UserEntity userEntity = userMapper.getById(userId);

        ExternalCustomerCallbackLogEntity callbackLogEntity = new ExternalCustomerCallbackLogEntity();
        callbackLogEntity.setCustomerId(customerId);
        callbackLogEntity.setManagerId(userEntity.getId());
        callbackLogEntity.setManagerName(userEntity.getRealName());
        callbackLogEntity.setCreateTime(new Date());
        callbackLogEntity.setContent("");
        callbackLogEntity.setResult("");
        callbackLogEntity.setCreater(String.valueOf(userId));
        callLogMapper.saveCallBackLog(callbackLogEntity);
        try {
            System.out.println("---------开始进入拨号接口---------");
            List<NameValuePair> nameValuePairList = new ArrayList<>();
            nameValuePairList.add(new BasicNameValuePair("Call", userEntity.getCornet()));
            nameValuePairList.add(new BasicNameValuePair("Dialed", memPhone));
            nameValuePairList.add(new BasicNameValuePair("pid", callbackLogEntity.getId().toString()));
            nameValuePairList.add(new BasicNameValuePair("Tag", "1"));

            System.out.println("---------进入拨号---------");
            System.out.println("---------id---------" + callbackLogEntity.getId());
            System.out.println("---------cornetNew---------" + userEntity.getCornet());
            String result = HttpClientUtil.doGet(CRM_URL_PREFIX + "/CallCenterUnicom/SinglePhone.json",
                    nameValuePairList,
                    10000, "utf-8");
            System.out.println("userEntity.getCornet():" + userEntity.getCornet() + ",,Dialed:" + memPhone + ",,pid:" + callbackLogEntity.getId().toString() + ",,result:" + result);
            logger.info("call single phone call:[{}] dia20181108" +
                            "led [{}] id [{}],result:[{}]", userEntity.getCornet(), memPhone,
                    callbackLogEntity.getId(), result);
        } catch (Exception ex) {
            logger.error("调用打电话接口失败", ex);
            System.out.println("---------cornetNewError---------" + userEntity.getCornet());
        }
        return callbackLogEntity.getId();
    }

    /**
     * 挂断电话
     *
     * @param userId
     * @return 通过ID获取CustomerCallbackLog响应
     */
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public void handUp(Integer callbackLogId, String callContent, String buyIntention, Integer userId, String abandon) {
        try {
            UserEntity userEntity = userMapper.getById(userId);
            ExternalCustomerCallbackLogEntity logEntity = callLogMapper.getById(callbackLogId);
            ExternalCustomerEntity customerEntity = mapper.queryById(logEntity.getCustomerId());
            Date now = new Date();
            logEntity.setContent(callContent);
            //更新calllog
            callLogMapper.update(logEntity);
            customerEntity.setUpdateTime(new Date());
            customerEntity.setBuyIntention(buyIntention);
            //更新回访记录的时候，同时更新会员备注
            customerEntity.setRemark(callContent);
            customerEntity.setLastCallTime(now);
            mapper.update(customerEntity);

            List<NameValuePair> nameValuePairList = new ArrayList<>();
            nameValuePairList.add(new BasicNameValuePair("Call", userEntity.getCornet()));
            String result = HttpClientUtil.doGet(CRM_URL_PREFIX + "/CallCenterUnicom/HandUp.json", nameValuePairList,
                    10000, "utf-8");
            logger.info("handUp phone call:[{}] result:[{}]", userEntity.getCornet(), result);
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error(ex.getMessage(), ex);
        }
    }

    private final static String MD5(String s) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            byte[] strTemp = s.getBytes();
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public String getCRMCustomerURL(Integer customerId, String curId, String curName) {
        String url = "";
        ExternalCustomerEntity ce = mapper.queryById(customerId);

        if (ce != null) {
            Date date = new Date();

            String crmUrl = MemoryPropertyPlaceholderConfigurer.getContextProperty("CRM.CUSTOMER.INFO.URL");
            List<NameValuePair> pairs = new ArrayList<>();
            pairs.add(new BasicNameValuePair("city", ce.getCityCode()));
            pairs.add(new BasicNameValuePair("memphone", ce.getPhone()));
            crmUrl += "&signature=" + MD5("" + (date.getTime() / 1000) + "hgs") + "&timestamp=" + (date.getTime() / 1000);
            crmUrl += "&admin_id=" + curId + "&admin_name=" + curName;
            try {
                URLEncoder.encode(crmUrl, "utf8");
                String res = HttpClientUtil.doPostWithCharset(crmUrl, pairs, "utf8", "utf8");

                JSONObject jsonObject;
                if (StringUtils.isNotBlank(res)) {
                    jsonObject = JSONObject.fromObject(res);
                    if (jsonObject.get("data") != null && "1".equalsIgnoreCase(String.valueOf(jsonObject.get("result")))) {
                        url = String.valueOf(jsonObject.get("data"));
                    }
                }
                logger.info("getExterCRMCusURL :{},url:{}", res, url);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
        return url;
    }

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        return null;
    }

    @Override
    public boolean isControlService() {
        return false;
    }

    @Override
    public boolean isLogService() {
        return false;
    }

    @Override
    public boolean isMonitorService() {
        return false;
    }

    @Override
    public Object rollback() {
        return null;
    }

    @Override
    public void commit() {

    }
}
