package com.reptileclient.jlifeapp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.reptileclient.jlifeapp.dao.hm.HmTokenMapper;
import com.reptileclient.jlifeapp.dao.jz.CustomerClientMapper;
import com.reptileclient.jlifeapp.dao.jz.JzbmLeadMapper;
import com.reptileclient.jlifeapp.dao.jz.SysCityMapper;
import com.reptileclient.jlifeapp.dao.region.RegionStoreMapper;
import com.reptileclient.jlifeapp.entity.hm.CustomerClue;
import com.reptileclient.jlifeapp.entity.hm.HMOpenClueInfo;
import com.reptileclient.jlifeapp.entity.hm.ServerOrderClue;
import com.reptileclient.jlifeapp.entity.jz.CustomerClient;
import com.reptileclient.jlifeapp.entity.jz.JzbmLead;
import com.reptileclient.jlifeapp.service.HMClueSyncService;
import com.reptileclient.jlifeapp.service.HmPhoneDecryptService;
import com.reptileclient.jlifeapp.util.OkHttpUtil;
import lombok.extern.slf4j.Slf4j;
import me.ihxq.projects.pna.PhoneNumberInfo;
import me.ihxq.projects.pna.PhoneNumberLookup;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class HMClueSyncServiceImpl implements HMClueSyncService {

    @Autowired
    private HmPhoneDecryptService phoneDecryptService;

    @Resource
    private HmTokenMapper hmTokenMapper;


    @Resource
    private CustomerClientMapper customerClientMapper;


    @Resource
    private RegionStoreMapper regionStoreMapper;


    @Resource
    private JzbmLeadMapper jzbmLeadMapper;

    @Resource
    private SysCityMapper cityMapper;


    /**
     * 同步盒马线索分为2类，
     * 1、 公共线索池线索
     * 2 服务单中支付金额为0.01的订单
     */
    @Override
    public void syncClue() {
        String token = hmTokenMapper.selectAll().getToken();
        LocalDateTime now = LocalDateTime.now();
        String startTime = now.plusHours(-3).withMinute(0).withSecond(0).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String endTime = now.plusDays(5).withHour(23).withMinute(59).withSecond(59).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        try {
            // 公共线索池线索
//            List<CustomerClue> openClueInfo = getOpenClueInfo(token, startTime, endTime);
            //服务单
            List<CustomerClue> serveOrderClue = getServeOrderClueInfo(token, startTime, endTime);
//            openClueInfo.addAll(serveOrderClue);
            addCustomerClueList(serveOrderClue);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    private List<CustomerClue> getServeOrderClueInfo(String token, String startTime, String endTime) throws IOException {
        String serveClueInfo = OkHttpUtil.getServeOrderClueInfo(token, startTime, endTime, 1);
        if (serveClueInfo.startsWith("{") && serveClueInfo.endsWith("}")) {
            JSONObject jsonObject = JSON.parseObject(serveClueInfo);
            if (jsonObject.getBoolean("success")) {
                JSONObject data = jsonObject.getJSONObject("data");
                Integer total = data.getInteger("total");
                Integer pageSize = data.getInteger("pageSize");
                Integer totalPage = total / pageSize + 1;
                Integer currentPage = data.getInteger("pageNum");
                List<ServerOrderClue> serverOrderClues = data.getJSONArray("list").toJavaList(ServerOrderClue.class);
                while (currentPage < totalPage) {
                    serveClueInfo = OkHttpUtil.getServeOrderClueInfo(token, startTime, endTime, currentPage + 1);
                    if (serveClueInfo.startsWith("{") && serveClueInfo.endsWith("}")) {
                        jsonObject = JSON.parseObject(serveClueInfo);
                        if (jsonObject.getBoolean("success")) {
                            data = jsonObject.getJSONObject("data");
                            if (data.containsKey("list") && total > 0) {
                                serverOrderClues.addAll(data.getJSONArray("list").toJavaList(ServerOrderClue.class));
                            }
                        }
                    }
                    currentPage++;
                }
                return setServeOtherClueInfo(serverOrderClues);
            }
        }
        return new ArrayList<>();
    }

    /**
     * 补充线索需要的 归属地、来源、服务模式、服务城市、服务区域 及备注
     *
     * @param serverOrderClues
     * @return
     */
    private List<CustomerClue> setServeOtherClueInfo(List<ServerOrderClue> serverOrderClues) {
//        预约找保姆/钟点工 中介服务 鲸致生活 0.01元
//        代班钟点工服务（代3-10天） 中介服务 鲸致生活 不限金额
//        保姆中介服务费 鲸致生活【勿拍】1元
//        代班保姆服务（代3-10天） 中介服务 鲸致生活 不限金额
        List<ServerOrderClue> temp = serverOrderClues.stream()
                .filter(a -> (
                        Objects.equals(a.getPayFee(), "0.01") &&
                                StringUtils.contains(a.getItemName(), "预约找保姆")) ||
                        (StringUtils.contains(a.getItemName(), "代班钟点工服务"))
                        || (StringUtils.contains(a.getItemName(), "代班保姆服务"))
//                        || (Objects.equals(a.getPayFee(), "1.00") &&
//                        StringUtils.contains(a.getItemName(), "保姆中介服务费"))
                )
                .collect(Collectors.toList());
        List<CustomerClue> clues = new ArrayList<>();
        List<String> cityList = Arrays.asList("北京", "上海", "南京", "深圳", "苏州", "杭州", "青岛", "重庆", "成都", "广州");

        for (ServerOrderClue serverOrderClue : temp) {
            CustomerClue customerClue = new CustomerClue();
            customerClue.setResource("盒马app");
            customerClue.setCustomerName(serverOrderClue.getUserName());
            String phone = phoneDecryptService.getPhoneByTradeNo("phone", String.valueOf(serverOrderClue.getBookOrderNo()), "BOOK_ORDER");
            customerClue.setCustomerTel(phone);
            customerClue.setCustomerAddr(serverOrderClue.getAddress());
            String cityName = serverOrderClue.getShopName().substring(0, 2);
            Long cityId;
            if (cityList.contains(cityName)) {
                cityId = regionStoreMapper.selectCityIdByCityName(cityName);
                customerClue.setServiceCity(cityId);
                customerClue.setRegionId(regionStoreMapper.selectByCityId(cityId));
            } else {
                customerClue.setServiceCity(1L);
                customerClue.setRegionId(1L);
                customerClue.setRemark("此线索所在城市非北京、上海、南京、深圳、苏州、杭州、青岛、重庆、成都、广州,所在城市为：" + cityName);
            }
            String itemName = serverOrderClue.getItemName();
            if (itemName.contains("保姆/钟点工")) {
                customerClue.setServiceModel(2);
            } else if (itemName.contains("代班钟点工服务")) {
                customerClue.setServiceModel(5);
            } else if (itemName.contains("代班保姆服务")) {
                customerClue.setServiceModel(6);
            } else if (itemName.contains("钟点工")) {
                customerClue.setServiceModel(1);
            } else if (itemName.contains("保姆")) {
                customerClue.setServiceModel(2);
            } else if (itemName.contains("月嫂")) {
                customerClue.setServiceModel(4);
            } else if (itemName.contains("搬家")) {
                customerClue.setServiceModel(7);
            } else {
                customerClue.setServiceModel(2); //其他全部归类为 白班保姆
            }
            customerClue.setWorkContent(serverOrderClue.getRemark());
            clues.add(customerClue);
        }

        return clues;
    }

    private List<CustomerClue> getOpenClueInfo(String token, String startTime, String endTime) throws IOException {
        String openClueInfo = OkHttpUtil.getOpenClueInfo(startTime, endTime, token);
        if (openClueInfo.startsWith("{") && openClueInfo.endsWith("}")) {
            JSONObject jsonObject = JSON.parseObject(openClueInfo);
            if (jsonObject.getBoolean("success")) {
                JSONObject pageInfo = jsonObject.getJSONObject("data").getJSONObject("pageInfo");
                if (pageInfo.containsKey("list") && pageInfo.getInteger("endRow") > 0) {
                    List<HMOpenClueInfo> clueInfos = pageInfo.getJSONArray("list").toJavaList(HMOpenClueInfo.class);
                    return setOpenClueInfo(clueInfos);
                }
            }
        }

        return new ArrayList<>();
    }

    /**
     * 补充 归属地、来源、服务模式  服务城市  服务区域 备注
     * clueId: 8545
     * clueNick: "黄女士"
     * createTime: "2021-11-22 17:05:06"
     * intentionType: 2
     * intentionTypeName: "保姆"
     * status: 1
     * statusDesc: "待分配"
     * userId: "45141029"
     * userPhone: "18616210916"
     *
     * @param clueInfos
     */
    private List<CustomerClue> setOpenClueInfo(List<HMOpenClueInfo> clueInfos) {
        PhoneNumberLookup phoneNumberLookup = new PhoneNumberLookup();
        List<CustomerClue> clues = new ArrayList<>();
        List<String> cityList = Arrays.asList("北京", "上海", "南京", "深圳", "苏州", "杭州", "青岛", "重庆", "成都", "广州");
        for (HMOpenClueInfo clueInfo : clueInfos) {
            PhoneNumberInfo found;
            CustomerClue customerClue = new CustomerClue();
            customerClue.setResource("盒马-转介绍");
            customerClue.setCustomerName(clueInfo.getClueNick()); //客户姓名
            customerClue.setCustomerTel(clueInfo.getUserPhone()); //客户手机号
            try {
                found = phoneNumberLookup.lookup(clueInfo.getUserPhone()).get();
                String province = found.getAttribution().getProvince();// 省
                String city = found.getAttribution().getCity();// 市
                if (cityList.contains(city)) {
                    customerClue.setCustomerAddr(province + "-" + city);
                    Long cityId = regionStoreMapper.selectCityIdByCityName(city);
                    customerClue.setServiceCity(cityId); //服务城市
                    Long regionId = regionStoreMapper.selectByCityId(cityId);
                    customerClue.setRegionId(regionId);  //线索区域
                } else {
                    customerClue.setServiceCity(1L);
                    customerClue.setRegionId(1L);
                    customerClue.setCustomerAddr("上海"); //非 业务城市。
                    customerClue.setRemark("此线索手机号归属地非北京、上海、南京、深圳、苏州、杭州、青岛、重庆、成都、广州，原归属地：" + province + "省" + city + "市");
                }
            } catch (Exception e) {
                customerClue.setServiceCity(1L);
                customerClue.setRegionId(1L);
                customerClue.setCustomerAddr("上海"); //未解析固定写死 上海
                customerClue.setRemark("此线索归属地异常，需要坐席协助");
            }
            // 1 钟点工 2 保姆 4 月嫂 7 搬家
            String intentionTypeName = clueInfo.getIntentionTypeName(); //服务类型
            if ("月嫂".equals(intentionTypeName)) {
                customerClue.setServiceModel(4);
            } else if ("保姆".equals(intentionTypeName)) {
                customerClue.setServiceModel(2);
            } else if ("搬家".equals(intentionTypeName)) {
                customerClue.setServiceModel(7);
            } else if ("保洁".equals(intentionTypeName)) {
                customerClue.setServiceModel(1); //盒马 公共线索池里的保洁 线索放入钟点工
            }
            clues.add(customerClue);
        }
        return clues;
    }

    public void addCustomerClueList(List<CustomerClue> customerClues) {
        for (CustomerClue customerClue : customerClues) {
            addCustomerClue(customerClue);
        }
    }

    public void addCustomerClue(CustomerClue customerClue) {
        customerClue.setCustomerTel(customerClue.getCustomerTel().replace(" ", "").trim());
        if (!StringUtils.isEmpty(customerClue.getCustomerTel())) {
            Long customerId = insertCustomerClient(customerClue.getCustomerTel(),
                    customerClue.getCustomerName(), customerClue.getCustomerAddr());
            JzbmLead lead = new JzbmLead();
            lead.setCustomerId(customerId);
            lead.setSourceId(554);
            lead.setSourceName("盒马-转介绍");
            lead.setServiceCity(customerClue.getServiceCity().intValue());
            lead.setServiceContent(customerClue.getWorkContent());
            switch (customerClue.getServiceModel()) {
                case 1:
                    lead.setServiceModel(10);
                    break;
                case 4:
                    lead.setServiceModel(20);
                    break;
                case 5:
                    lead.setServiceModel(30);
                    break;
                case 6:
                    lead.setServiceModel(31);
                    break;
                default:
                    lead.setServiceModel(11);
                    break;
            }
            lead.setServiceCityName(cityMapper.selectByPrimaryKey(customerClue.getServiceCity()).getCityName());
            lead.setCustomerName(customerClue.getCustomerName());
            lead.setCustomerTel(customerClue.getCustomerTel());
            lead.setCustomerAddr(customerClue.getCustomerAddr());
            lead.setState(1);
            lead.setCreateId(1L);
            lead.setCreateTime(LocalDateTime.now());
            lead.setCreateUser("管理员");
            int count = jzbmLeadMapper.selectByCustomerTelAndServiceModel(lead.getCustomerTel(), lead.getServiceModel(), lead.getServiceCity());
            if (count == 0) {
                lead.setLeadNo(generateLeadNo());
                jzbmLeadMapper.insert(lead);
            }
        }
    }

    private String generateLeadNo() {
        String kitNo = "SS"; //三嫂业务
        String maxNo = jzbmLeadMapper.selectMaxNo(kitNo);
        if (StringUtils.isEmpty(maxNo)) {
            return kitNo + "0000001";
        }
        return kitNo + String.format("%07d", Integer.parseInt(maxNo) + 1);
    }

    private Long insertCustomerClient(String phone, String userName, String address) {
        CustomerClient customerClient = customerClientMapper.selectByTel(phone);
        if (null == customerClient) {
            customerClient = new CustomerClient();
            customerClient.setCustomerNo(customerClientMapper.selectCustomerNo());
            customerClient.setTel(phone);
            customerClient.setCustomerAddr(address);
            if (StringUtils.isNotBlank(userName)) {
                customerClient.setCustomerName(userName);
            }
            customerClient.setChannelId(4); //盒马-转介绍 对应的渠道id
            customerClient.setSource("盒马-转介绍");
            customerClientMapper.insertSelective(customerClient);
        }
        return customerClient.getId();
    }
}
