package com.cftech.consultsheet.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.cftech.base.codingrule.utils.CodingruleUtils;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

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;

    @Autowired
    private CodingruleUtils codingruleUtils;

    static final String [] arr = new String[] {"0", "1"};

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


    @Override
    public Integer updateDate(String consultId, String status, String description) {
        return consultSheetMapper.updateDate(consultId,status,description);
    }

    @Override
    public Integer updateStatus(String consultId, String status) {
        return consultSheetMapper.updateStatus(consultId,status);
    }

    @Override
    public List<ConsultSheet> fetchSearchBy(Conds conds, Sort sort, int page, int pageSize, String 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);
        if (!StringUtils.equals(id,"1")) {
            params.put("id", id);
        }
        return consultSheetMapper.fetchSearchByPage(params);
    }

    @Override
    public JSONObject pollingConsultSheet(ConsultSheet consultSheet) {
        JSONObject retObj = new JSONObject();
        try {
            consultSheet.setConsultId(codingruleUtils.getNumber(consultSheet.getAccountsId(), ConsultSheet.class.getName()));
            if (consultSheetMapper.save(consultSheet) > 0) {
                memberProcess(consultSheet.getOpenId(), consultSheet);
                retObj.put("errerNo", 0);
                retObj.put("errerMsg", "咨询单提交成功，请等待药师审核");
            } else {
                retObj.put("errrNo", 1);
                retObj.put("errorMsg", "咨询单保存失败");
            }
        } 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 serviceId = member.getServiceId();
            Conds userConds = new Conds();
            userConds.equal("t.del_flag", Constants.DEL_FLAG_0);
            userConds.equal("t.id", serviceId);
            Qyuser user = qyuserService.fetchSearchByConds(userConds);
            if (user.getPeakVal() > 0) {//客服峰值大于0
                consultSheet.setServiceId(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) {
        first:for (int i=0, y=arr.length; i<y; i++) {

            Conds conds = new Conds();
            conds.equal("t.del_flag", Constants.DEL_FLAG_0);
            conds.equal("t.user_type", arr[i]);//0:客服; 1:药师
            conds.greatThan("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) {
                if (arr[i].equals("0")) {
                    consultSheet.setServiceId(users.get(0).getId());
                } else {
                    consultSheet.setDoctorId(users.get(0).getId());
                }

                if(users.get(0).getPeakVal() > users.get(0).getAssigned()) {//峰值未满
                    users.get(0).setAssigned(users.get(0).getAssigned() + 1);
                    qyuserService.updateAssigned(users.get(0));
                } else {//峰值已满
                    users.get(0).setUnAssigned(users.get(0).getAssigned() + 1);
                    qyuserService.updateAssigned(users.get(0));
                }
            } else if (users.size() > 1) {
                //当前分配
                second: for (Qyuser user: users) {
                    if (user.getPeakVal() > user.getAssigned()) {//峰值未满

                        if (arr[i].equals("0")) {
                            consultSheet.setServiceId(user.getId());
                        } else {
                            consultSheet.setDoctorId(user.getId());
                        }

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

                //峰值已满
                if (consultSheet.getServiceId() == null) {
                    Conds unconds = new Conds();
                    unconds.equal("t.del_flag", Constants.DEL_FLAG_0);
                    unconds.equal("t.user_type", arr[i]);
                    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);

                        if (arr[i].equals("0")) {
                            consultSheet.setServiceId(user.getId());
                        } else {
                            consultSheet.setDoctorId(user.getId());
                        }

                        //增加分配人数
                        user.setUnAssigned(user.getAssigned() + 1);
                        qyuserService.updateAssigned(user);
                    } else {
                        consultSheet.setDescription(arr[i].equals("0")? "客服": "药师" +"未有对应的咨询单处理人员");
                    }
                }
            } else {
                consultSheet.setDescription(arr[i].equals("0")? "客服": "药师"+ "未有对应的咨询单处理人员");
            }
        }
        return true;
    }
}