package com.cftech.consultsheet.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.cftech.base.org.model.Qyuser;
import com.cftech.base.org.service.QyuserService;
import com.cftech.consultsheet.dao.ConsultSheetMapper;
import com.cftech.consultsheet.model.ConsultSheet;
import com.cftech.consultsheet.service.ConsultSheetService;
import com.cftech.core.generic.GenericDao;
import com.cftech.core.generic.GenericServiceImpl;
import com.cftech.core.scope.OrderType;
import com.cftech.core.sql.Conds;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.Constants;
import com.cftech.core.util.StringUtils;
import com.cftech.member.model.Member;
import com.cftech.member.service.MemberService;
import com.cftech.order.service.OrderService;
import com.cftech.sys.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 咨询单ServiceImpl
 *
 * @author Licc
 * @date: 2020-09-22 12:06
 */
@Service("consultSheetService")
public class ConsultSheetServiceImpl extends GenericServiceImpl<ConsultSheet> implements ConsultSheetService {

    @Autowired
    @Qualifier("consultSheetMapper")
    private ConsultSheetMapper consultSheetMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private QyuserService qyuserService;

    @Override
    public GenericDao<ConsultSheet> getGenericMapper() {
        return consultSheetMapper;
    }


    @Override
    public List<ConsultSheet> fetchSearchBy(Conds conds, Sort sort, int page, int pageSize, Long id) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("conds", conds);
        params.put("offset", page > 0 ? page : 0);
        params.put("limit", pageSize > 0 ? pageSize : 0);
        params.put("sort", sort);
        params.put("id", id);
        return consultSheetMapper.fetchSearchByPage(params);
    }

    @Transactional
    @Override
    public JSONObject pollingConsultSheet(ConsultSheet consultSheet) {
        JSONObject retObj = new JSONObject();
        try {
            if (consultSheetMapper.save(consultSheet) > 0) {
                memberProcess(consultSheet.getOpenId(), consultSheet);
            }
            retObj.put("errerNo", 0);
            retObj.put("data", 0);
        } catch (Exception e) {
            e.printStackTrace();

            retObj.put("errrNo", 1);
            retObj.put("errorMsg", "提交咨询单" + e.getMessage());
        }
        return retObj;
    }

    /**
     * 咨询单分配流程
     * 复购/首次分配
     * @return
     */
    private boolean memberProcess(String openid, ConsultSheet consultSheet) {
        //1、查询用户是否复购
        Conds conds = new Conds();
        conds.equal("o.del_flag", Constants.DEL_FLAG_0);
        conds.equal("o.openid", openid);
        conds.in("o.status", new String[]{"2", "3", "4"});//2 待发货，3：待收货 4:待付款
        int count = orderService.count(conds);
        if (count > 0) { //复购
            Conds memberConds = new Conds();
            memberConds.equal("del_flag", Constants.DEL_FLAG_0);
            memberConds.equal("open_id", openid);
            Member member = memberService.fetchSearchByConds(conds);

            String customerId = member.getCustomerId();
            Conds userConds = new Conds();
            userConds.equal("t.del_flag", Constants.DEL_FLAG_0);
            userConds.equal("t.id", customerId);
            Qyuser user = qyuserService.fetchSearchByConds(userConds);
            if (user.getPeakVal() > 0) {//客服峰值大于0
                consultSheet.setCustomerId(user.getId());
            } else {//普通轮询
                firstCustomerProcess(consultSheet);
            }


            String doctorId = member.getDoctorId();
            userConds.equal("t.id", doctorId);
            user = qyuserService.fetchSearchByConds(userConds);
            if (user.getPeakVal() > 0) {//药师峰值大于0
                consultSheet.setDoctorId(user.getId());
            } else {//普通轮询
                firstCustomerProcess(consultSheet);
            }
        } else {//首次购买
            firstCustomerProcess(consultSheet);
        }

        return consultSheetMapper.update(consultSheet) > 0;
    }

    /**
     * 咨询单首次购买流程
     * @return
     */
    private boolean firstCustomerProcess(ConsultSheet consultSheet) {
        Conds conds = new Conds();
        conds.equal("t.del_flag", Constants.DEL_FLAG_0);
        conds.equal("t.user_type", "0");
        conds.greatEqual("t.peak_val", 0);
        Sort sort = new Sort("t.assigned", OrderType.ASC);
        List<Qyuser> users = qyuserService.fetchSearchByPage(conds, sort, 0, 0);
        if (users.size() == 1) {
            consultSheet.setCustomerId(users.get(0).getId());
        } else if (users.size() > 1) {
            //当前分配
            for (Qyuser user: users) {
                if (user.getPeakVal() < user.getAssigned()) {
                    consultSheet.setCustomerId(user.getId());

                    //增加分配人数
                    user.setAssigned(user.getAssigned() + 1);
                    qyuserService.updateAssigned(user);
                    break;
                }
            }

            //峰值已满
            if (consultSheet.getCustomerId() == null) {
                Conds unconds = new Conds();
                unconds.equal("t.del_flag", Constants.DEL_FLAG_0);
                unconds.equal("t.user_type", "0");
                unconds.greatEqual("t.peak_val", 0);
                Sort unsort = new Sort("t.un_assigned", OrderType.ASC);
                users = qyuserService.fetchSearchByPage(conds, unsort, 0, 0);
                if (users.size() > 0) {
                    Qyuser user = users.get(0);
                    consultSheet.setCustomerId(user.getId());

                    //增加分配人数
                    user.setAssigned(user.getAssigned() + 1);
                    qyuserService.updateAssigned(user);
                } else {
                    consultSheet.setDescription("未有对应的咨询单处理人员");
                }
            }
        } else {
            consultSheet.setDescription("未有对应的咨询单处理人员");
        }
        return true;
    }
}