package org.linlinjava.jz.admin.service;

import com.google.common.collect.Lists;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.util.CollectionUtils;
import org.linlinjava.jz.admin.util.SecurityHelper;
import org.linlinjava.jz.core.util.ResponseUtil;
import org.linlinjava.jz.db.domain.*;
import org.linlinjava.jz.db.dto.JzTicketActionDto;
import org.linlinjava.jz.db.service.*;
import org.linlinjava.jz.db.util.RandUtil;
import org.linlinjava.jz.db.util.TicketStatusConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客户信息管理
 */
@Service
public class AdminCustomerService {

    private final Log logger = LogFactory.getLog(AdminCustomerService.class);

    @Autowired
    private CustomerClientService customerClientService;

    @Autowired
    private JzCustomerFnService fnService;
    @Autowired
    private JzTicketService jzTicketService;
    @Autowired
    private AdminBookOrderService adminBookOrderService;
    @Autowired
    private JzCalllogService jzCalllogService;
    @Autowired
    private JzCalllogRecordService jzCalllogRecordService;
    @Autowired
    private JzDmChannelService channelService;
    @Autowired
    private JzTicketActionService jzTicketActionService;
    @Autowired
    private JzSysUserService jzSysUserService;
    @Autowired
    private JzSkillGroupService jzSkillGroupService;

    @Autowired
    private JzCustomerFnService customerFnService;
    @Autowired
    private JzOrderService jzOrderService;
    @Autowired
    private JzTicketConsultService consultService;
    @Autowired
    private JzDmTicketConsultTypeService jzDmTicketConsultTypeService;
    @Autowired
    private JzGoodsCategoryService jzGoodsCategoryService;

    public Object list(String username, String mobile, Integer type, Integer page, Integer limit, String sort, String order) {

        List<CustomerClient> userList = customerClientService.querySelective(username, mobile, type, page, limit, sort, order);
        return ResponseUtil.okList(userList);
    }

    /**
     * @param customer 客户信息
     * @param fns      亲情号码
     * @return
     */
    @Transactional
    public Object create(CustomerClient customer, List<String> fns) {
        customer.setCustomerNo("M" + RandUtil.getRandomNum(9));
        customer.setUpdateTime(LocalDateTime.now());
        int admin = SecurityHelper.getAdminId();
        customer.setCreateUser(Integer.toString(admin));
        int id = customerClientService.add(customer);
        if (fns != null && fns.size() > 0) {
            for (String mobile : fns) {
                CustomerFn fn = new CustomerFn();
                fn.setCustomerId(id);
                fn.setMobile(mobile);
                fn.setCreateUser(SecurityHelper.getAdminId());
                fn.setUpdateUser(SecurityHelper.getAdminId());
                fnService.add(fn);
            }
        }
        return ResponseUtil.ok(id);
    }

    @Transactional
    public Object update(CustomerClient customer, List<String> fns) {
        customer.setUpdateTime(LocalDateTime.now());
        customerClientService.updateById(customer);
        if (fns != null && fns.size() > 0) {
            for (String mobile : fns) {
                if (fnService.findByMobile(customer.getId().intValue(), mobile) != null) {
                    continue;
                }
                CustomerFn fn = new CustomerFn();
                fn.setCustomerId(customer.getId().intValue());
                fn.setMobile(mobile);
                fn.setCreateUser(SecurityHelper.getAdminId());
                fn.setUpdateUser(SecurityHelper.getAdminId());
                fnService.add(fn);
            }
        }
        return ResponseUtil.ok();
    }

    /**
     * 根据手机号返回客户信息，有可能会存在多条
     *
     * @param mobile
     * @return
     */
    public Map<String, Object> findByMobile(String mobile) {
        Map<String, Object> data = new HashMap<>(16);
        CustomerClient customerClient = customerClientService.findUserByMobile(mobile);
        if (null != customerClient) {
            //亲情号
            List<CustomerFn> fns = fnService.queryByCustomerId(customerClient.getId().intValue());
            //工单
            List<JzTicket> ticketList = jzTicketService.selectTicketByMobile(mobile);
            //服务单
            List<JzBookOrder> jzBookOrders = adminBookOrderService.queryByPhone(mobile);
            //电访记录
            List<JzCalllog> jzCalllogs = jzCalllogService.queryByCustomerId(customerClient.getId().intValue());
            //话务记录
            List<JzCalllogRecord> jzCalllogRecords = jzCalllogRecordService.queryCustomerId(customerClient.getId().intValue());
            data.put("user", customerClient);
            data.put("fns", fns);
            data.put("ticketList", ticketList);
            data.put("jzBookOrders", jzBookOrders);
            data.put("jzCalllogs", jzCalllogs);
            data.put("jzCalllogRecords", jzCalllogRecords);
        }

        return data;
    }

    /**
     * 返回客户详情
     *
     * @param id
     * @return
     */
    public Map<String, Object> detail(int id) {
        //客户
        CustomerClient customerClient = customerClientService.findById(id);
        //亲情号
        List<CustomerFn> fns = fnService.queryByCustomerId(id);
        //工单
        List<JzTicket> ticketList = jzTicketService.selectTicketByCustomerId(customerClient.getId().intValue());

        ticketList.forEach(item -> {
            //归属技能组
            if (null != item.getSkillGroupId()) {
                JzSkillGroup skillGroup = jzSkillGroupService.findById(item.getSkillGroupId());
                item.setSkillGroupName(null != skillGroup ? skillGroup.getName() : "");
            }

            //处理时长
            if (!item.getStatus().equals(TicketStatusConstant.STATUS_COMPLETED)) {
                Duration duration = Duration.between(item.getCreateTime(), LocalDateTime.now());
                item.setHandleTime((int) duration.getSeconds());
            }

            //咨询内容
            List<JzTicketConsult> consultList = consultService.queryByTocketId(item.getId());
            List<String> list = Lists.newArrayList();
            consultList.forEach(item1 -> {
                JzDmTicketConsultType jzDmTicketConsultType = jzDmTicketConsultTypeService.queryById(item1.getConsultId());
                if(null!=jzDmTicketConsultType) {
                	list.add(jzDmTicketConsultType.getPath());
                }
            });
            item.setTicketConsultTypes(list);

            //投诉产品
            if (item.getGoodsId() != null && item.getGoodsId() > 0) {
                JzGoodsCategory jzGoodsCategory = jzGoodsCategoryService.selectById(item.getGoodsId());
                if (null != jzGoodsCategory) {
                    JzGoodsCategory jzGoodsCategory1 = jzGoodsCategoryService.selectById(jzGoodsCategory.getPid());
                    item.setProductName(jzGoodsCategory1.getName() + "->" + jzGoodsCategory.getName());
                }
            }

            //最后处理人
            SysUser sysUser = jzSysUserService.findAdmin(item.getUpdateUser());
            item.setUpdateUserName(null != sysUser ? sysUser.getUserName() : "");

            //工单记录
            List<JzTicketActionDto> jzTicketActionDtos = jzTicketActionService.selectByTicketId(item.getId());
            item.setJzTicketActions(jzTicketActionDtos);
        });

        //服务单

        //List<JzBookOrder> jzBookOrders = adminBookOrderService.queryByPhone(customerClient.getTel());
        List<JzOrder> jzOrders = jzOrderService.findByUserId(id);
        //电访记录
        List<JzCalllog> jzCalllogs = jzCalllogService.queryByCustomerId(id);
        //话务记录
        List<JzCalllogRecord> jzCalllogRecords = jzCalllogRecordService.queryCustomerId(id);
        //客户来源
        JzDmChannel channel = channelService.queryById(customerClient.getChannelId() == null ? -1 : customerClient.getChannelId());

        Map<String, Object> data = new HashMap<>(16);
        data.put("user", customerClient);
        data.put("fns", fns);
        data.put("ticketList", ticketList);
        data.put("jzOrders", jzOrders);
        data.put("jzCalllogs", jzCalllogs);
        data.put("jzCalllogRecords", jzCalllogRecords);
        data.put("channel", channel);
        return data;
    }


    /**
     * 返回客户详情
     *
     * @param id
     * @return
     */
    public Map<String, Object> read(int id) {
        CustomerClient customerClient = customerClientService.findById(id);
        List<CustomerFn> fns = fnService.queryByCustomerId(id);
        Map<String, Object> data = new HashMap<>(16);
        data.put("user", customerClient);
        data.put("fns", fns);
        return data;
    }

    /**
     * 电话条进电时使用 如果没有客户 直接新增一个
     *
     * @param mobile
     * @return
     */
    public Object findOrAdd(String mobile) {
        CustomerClient customerClients = customerClientService.findUserByMobile(mobile);
        if (customerClients != null) {
            return ResponseUtil.ok(customerClients.getId());
        } else {
            SysUser admin = (SysUser) SecurityUtils.getSubject().getPrincipal();
            CustomerClient customer = new CustomerClient();
            customer.setCustomerNo("M" + RandUtil.getRandomNum(9));
            customer.setTel(mobile);
            customer.setSource("IB");
            customer.setCreateUser(admin.getUserName());
            customer.setCreateTime(LocalDateTime.now());
            customer.setUpdateTime(LocalDateTime.now());
            customer.setCustomerType((short) 0);
            int id = customerClientService.add(customer);
            return ResponseUtil.ok(id);
        }
    }

}
