package com.ruoyi.ibs.task.service.impl;

import com.ruoyi.common.core.domain.entity.CustInfoBusiness;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.ibs.customerselect.mapper.CustInfoBusinessMapper;
import com.ruoyi.ibs.list.domain.CustInfoMerchant;
import com.ruoyi.ibs.list.domain.CustInfoRetail;
import com.ruoyi.ibs.list.mapper.CustInfoMerchantMapper;
import com.ruoyi.ibs.list.mapper.CustInfoRetailMapper;
import com.ruoyi.ibs.task.domain.dto.AppointmentDTO;
import com.ruoyi.ibs.task.domain.entity.AppointmentInfo;
import com.ruoyi.ibs.task.domain.entity.SecondVisit;
import com.ruoyi.ibs.task.domain.vo.ProductInfoVO;
import com.ruoyi.ibs.task.domain.vo.SearchAppointmentCustVO;
import com.ruoyi.ibs.task.domain.vo.SecondVisitVO;
import com.ruoyi.ibs.task.mapper.AppointmentMapper;
import com.ruoyi.ibs.task.service.AppointmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Service
@Slf4j
public class AppointmentServiceImpl implements AppointmentService {

    @Resource
    private AppointmentMapper appointmentMapper;
    @Resource
    private CustInfoBusinessMapper custInfoBusinessMapper;
    @Resource
    private CustInfoMerchantMapper custInfoMerchantMapper;
    @Resource
    private CustInfoRetailMapper custInfoRetailMapper;

    /**
     * 预约客户
     *
     * @param appointmentDTO
     * @return
     */
    @Override
    public int appointmentCust(AppointmentDTO appointmentDTO) {
        String subDeptId = SecurityUtils.getHeadId();
        String durationDays = appointmentMapper.selectDictValueByDictLabel(subDeptId);
        AppointmentInfo appointmentInfo = new AppointmentInfo();
        BeanUtils.copyProperties(appointmentDTO, appointmentInfo);
        appointmentInfo.setBelongUserId(String.valueOf(SecurityUtils.getUserId()));
        LocalDateTime localDateTime = LocalDateTime.now();
        appointmentInfo.setStartTime(localDateTime);
        appointmentInfo.setCompleteTime(localDateTime.plusDays(Integer.parseInt(durationDays)));
        appointmentInfo.setCreateBy(SecurityUtils.getUsername());
        appointmentInfo.setUserName(SecurityUtils.getUsername());
        appointmentInfo.setNickName(SecurityUtils.getLoginUser().getUser().getNickName());
        appointmentInfo.setCustType(appointmentDTO.getCustType());
        String deptType = SecurityUtils.getLoginUser().getUser().getDept().getDeptType();
        if (deptType.equals("outlet")) {
            appointmentInfo.setOutletId(SecurityUtils.getDeptId().toString());
            appointmentInfo.setDeptId(SecurityUtils.getLoginUser().getUser().getDept().getParentId().toString());
        }else {
            appointmentInfo.setDeptId(SecurityUtils.getDeptId().toString());
        }
        return appointmentMapper.insertAppointment(appointmentInfo);
    }

    /**
     * 搜索要预约的客户
     *
     * @param custIdc
     * @return
     */
    @Override
    public SearchAppointmentCustVO searchAppointmentCust(String custIdc) {
        SearchAppointmentCustVO searchAppointmentCustVo = new SearchAppointmentCustVO();

        CustInfoMerchant custInfoMerchant = custInfoMerchantMapper.selectCustInfoMerchantBySocialCreditCode(custIdc);
        if (custInfoMerchant != null) {
            searchAppointmentCustVo.setCustType("1");
            searchAppointmentCustVo.setCustName(custInfoMerchant.getCustName());
            searchAppointmentCustVo.setCustIdc(custInfoMerchant.getCustIdc());
        } else{
            CustInfoBusiness custInfoBusiness = custInfoBusinessMapper.selectCustInfoBusinessBySocialCreditCode(custIdc);
            if (custInfoBusiness != null) {
                searchAppointmentCustVo.setCustType("2");
                searchAppointmentCustVo.setCustName(custInfoBusiness.getCustName());
                searchAppointmentCustVo.setCustIdc(custInfoBusiness.getCustIdc());
            }else {
                CustInfoRetail custInfoRetail = custInfoRetailMapper.selectCustInfoRetailBycustIdc(custIdc);
                if (custInfoRetail == null){
                    throw new ServiceException("搜索不到该客户");
                }
                searchAppointmentCustVo.setCustType("0");
                searchAppointmentCustVo.setCustName(custInfoRetail.getCustName());
                searchAppointmentCustVo.setCustIdc(custInfoRetail.getCustIdc());
            }
        }

        String subDeptId = SecurityUtils.getHeadId();
        String durationDays = appointmentMapper.selectDictValueByDictLabel(subDeptId);
        searchAppointmentCustVo.setDurationDays(durationDays);

        AppointmentInfo appointmentInfo = appointmentMapper.selectAppointmentByCustIdc(custIdc);
        if (appointmentInfo == null) {
            searchAppointmentCustVo.setStatus(0);
        } else {
            searchAppointmentCustVo.setStatus(1);
            throw new ServiceException("当前客户已被预约");
        }
        return searchAppointmentCustVo;
    }

    /**
     * 认领客户
     *
     * @param custIdc
     * @return
     */
    @Override
    public String claimCust(String custIdc) {

        Long userId = SecurityUtils.getUserId();
        AppointmentInfo appointmentInfo = new AppointmentInfo();
        appointmentInfo.setCustIdc(custIdc);
        appointmentInfo.setBelongUserId(String.valueOf(userId));
        String deptType = SecurityUtils.getLoginUser().getUser().getDept().getDeptType();
        if (deptType.equals("outlet")) {
            appointmentInfo.setOutletId(SecurityUtils.getDeptId().toString());
            appointmentInfo.setDeptId(SecurityUtils.getLoginUser().getUser().getDept().getParentId().toString());
        }else {
            appointmentInfo.setDeptId(SecurityUtils.getDeptId().toString());
        }
        appointmentInfo.setUserName(SecurityUtils.getUsername());
//        appointmentInfo.setCompleteTime(LocalDateTime.now());
        appointmentInfo.setNickName(SecurityUtils.getLoginUser().getUser().getNickName());
        appointmentMapper.updateAppointment(appointmentInfo);
        return "认领成功";
    }

    /**
     * 搜索要认领的客户
     *
     * @param custIdc
     * @return
     */
    @Override
    public List<AppointmentInfo> searchClaimCustList(String custIdc) {
        List<AppointmentInfo> unClaimList = appointmentMapper.selectUnClaimListByCustIdc(custIdc);
        if (unClaimList == null || unClaimList.isEmpty()){
            throw new ServiceException("当前客户已无产品可认领");
        }
        return unClaimList;
    }

    /**
     * 查询我预约的客户列表
     *
     * @return
     */
    @Override
    public List<AppointmentInfo> appointmentCustList() {
        String userRole = SecurityUtils.userRole();
        HashMap<String,Object> param = new HashMap<>();
        param.put("userRole",userRole);
        if (userRole.equals("branch")){
            param.put("deptId",SecurityUtils.getDeptId());
        }
        if (userRole.equals("outlet")){
            param.put("outletId",SecurityUtils.getDeptId());
        }
        param.put("userName",SecurityUtils.getUsername());
        return appointmentMapper.selectAppointmentListByUserName(param);
    }

    /**
     * 查询我认领的客户列表
     *
     * @return
     */
    @Override
    public List<AppointmentInfo> claimCustList() {
        String userRole = SecurityUtils.userRole();
        HashMap<String,Object> param = new HashMap<>();
        param.put("userRole",userRole);
        if (userRole.equals("branch")){
            param.put("deptId",SecurityUtils.getDeptId());
        }
        if (userRole.equals("outlet")){
            param.put("outletId",SecurityUtils.getDeptId());
        }
        param.put("userName",SecurityUtils.getUsername());
        return appointmentMapper.selectClaimListByUserName(param);
    }

    /**
     * 查询所有产品列表
     *
     */
    @Override
    public List<ProductInfoVO> getAllProds(){
        return appointmentMapper.selectAllProds();
    }

    /**
     * 查询该客户已被认领的产品列表
     *
     * @param custIdc
     * @return
     */
    @Override
    public List<ProductInfoVO> getCustProdDetail(String custIdc) {
        return appointmentMapper.selectCustProdDetail(custIdc);
    }

    /**
     * 查询该客户经理认领该客户的产品列表
     *
     * @param custIdc
     * @return
     */
    @Override
    public List<ProductInfoVO> getclaimCustDetail(String custIdc) {
        String userName = SecurityUtils.getUsername();
        return appointmentMapper.selectClaimCustDetail(userName, custIdc);
    }

    /**
     * 二次回访
     *
     * @param appointmentDTO
     * @return
     */
    @Override
    public int secondVisit(AppointmentDTO appointmentDTO, Date visitTime){
        SecondVisit secondVisit = new SecondVisit();
        secondVisit.setFromUserName(SecurityUtils.getUsername());
        secondVisit.setFromNickName(SecurityUtils.getLoginUser().getUser().getNickName());
        secondVisit.setCustId(appointmentDTO.getCustIdc());
        secondVisit.setCustName(appointmentDTO.getCustName());
        secondVisit.setCustType(appointmentDTO.getCustType());
        secondVisit.setSecondVisitTime(visitTime);
        secondVisit.setCreateBy(SecurityUtils.getUsername());
        return appointmentMapper.secondVisit(secondVisit);
    }

    /**
     * 获取今日二次回访列表
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<SecondVisitVO> getTodaySecondVisits() {
        LocalDate today = LocalDate.now();
        String username = SecurityUtils.getUsername();
        appointmentMapper.updateSecondVisitReadTime(username);
        return appointmentMapper.selectTodaySecondVisits(username, today);
    }

    /**
     * 资源助力(与二次走访在一个表second_visit)
     *
     * @param appointmentDTO
     * @return
     */
    @Override
    public int resourceAssist(AppointmentDTO appointmentDTO, String userName, String nickName) {
        SecondVisit resourceAssist = new SecondVisit();
        resourceAssist.setFromUserName(SecurityUtils.getUsername());
        resourceAssist.setFromNickName(SecurityUtils.getLoginUser().getUser().getNickName());
        resourceAssist.setToUserName(userName);
        resourceAssist.setToNickName(nickName);
        resourceAssist.setCustId(appointmentDTO.getCustIdc());
        resourceAssist.setCustName(appointmentDTO.getCustName());
        resourceAssist.setCustType(appointmentDTO.getCustType());
        resourceAssist.setApplyRemark(appointmentDTO.getApplyRemark());
        resourceAssist.setCreateBy(SecurityUtils.getUsername());
        return appointmentMapper.secondVisit(resourceAssist);
    }

    /**
     * 获取资源助力列表
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<SecondVisitVO> getResourceAssistList(){
        String username = SecurityUtils.getUsername();
        appointmentMapper.updateResourceAssistReadTime(username);
        return appointmentMapper.selectResourceAssistList(username);
    }

    @Override
    public int resourceAssistFeedback(SecondVisit secondVisit){
        secondVisit.setUpdateBy(SecurityUtils.getUsername());
        secondVisit.setUpdateTime(new Date());
        return appointmentMapper.resourceAssistFeedback(secondVisit);
    }

}
