package com.yunzhi.marketing.xlk.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunzhi.marketing.base.ResponseBean;
import com.yunzhi.marketing.center.taUser.entity.TaUser;
import com.yunzhi.marketing.center.taUser.mapper.TaUserMapper;
import com.yunzhi.marketing.common.CommConstant;
import com.yunzhi.marketing.common.StringUtils;
import com.yunzhi.marketing.entity.TaBuilding;
import com.yunzhi.marketing.entity.TaPerson;
import com.yunzhi.marketing.entity.TaRecommendCustomer;
import com.yunzhi.marketing.mapper.TaBuildingMapper;
import com.yunzhi.marketing.mapper.TaPersonMapper;
import com.yunzhi.marketing.mapper.TaRecommendCustomerMapper;
import com.yunzhi.marketing.po.MineRecommendCustomerPO;
import com.yunzhi.marketing.po.TaRecommendCustomerPO;
import com.yunzhi.marketing.xlk.dto.*;
import com.yunzhi.marketing.xlk.entity.*;
import com.yunzhi.marketing.xlk.mapper.*;
import com.yunzhi.marketing.xlk.service.IChannelCustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 渠道报备客户表  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2021-07-19
 */
@Service
public class ChannelCustomerServiceImpl extends ServiceImpl<ChannelCustomerMapper, ChannelCustomer> implements IChannelCustomerService {

    @Autowired
    private ChannelCustomerMapper channelCustomerMapper;

    @Autowired
    private TaRecommendCustomerMapper taRecommendCustomerMapper;

    @Autowired
    private CustomerVisitMapper customerVisitMapper;

    @Autowired
    private CustomerPreparatoryMapper customerPreparatoryMapper;

    @Autowired
    private CustomerSignatoryMapper customerSignatoryMapper;

    @Autowired
    private TaPersonMapper taPersonMapper;

    @Autowired
    private TaBuildingMapper taBuildingMapper;

    @Autowired
    private TaUserMapper taUserMapper;

    @Autowired
    private InstitutionMapper institutionMapper;
    /**
     * 审核
     *
     * @param id
     * @param channelCustomerDTO
     * @return
     */
    @Override
    public ResponseBean auditCustomer(String id, ChannelCustomerDTO channelCustomerDTO) {
        ChannelCustomer customer = channelCustomerMapper.selectById(id);
        if ("fail".equals(channelCustomerDTO.getAuditResult())){
            // 审核不通过
            customer.setStatus("3");
            channelCustomerMapper.updateById(customer);
            return ResponseBean.success("审核成功");
        }

        // 保存到访单
        CustomerVisit customerVisit = channelCustomerDTO.getCustomerVisit();
        customerVisit.setBuildingId(customer.getBuildingId());
        customerVisit.setRecommendPerson(customer.getRecommendPerson());
        TaPerson recommendPerson = taPersonMapper.getById(customer.getRecommendPerson());
        if (null != recommendPerson) {
            customerVisit.setRealtyConsultantName(recommendPerson.getName());
        }
        customerVisit.setRealtyConsultant(channelCustomerDTO.getRealtyConsultant());
        TaPerson channelPerson = taPersonMapper.getById(channelCustomerDTO.getRealtyConsultant());
        if (null != channelPerson) {
            customerVisit.setRealtyConsultantName(channelPerson.getName());
        }
        customerVisit.setOrgId(customer.getOrgId());

        // 审核通过 先查看在ta_recommend_customer 手机号是否存在
        LambdaQueryWrapper<TaRecommendCustomer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TaRecommendCustomer::getPhone,customer.getPhone());
        queryWrapper.eq(TaRecommendCustomer::getBuildingId,customer.getBuildingId());
        TaRecommendCustomer recommendCustomer = taRecommendCustomerMapper.selectOne(queryWrapper);
        if (null == recommendCustomer) {
            TaBuilding building = taBuildingMapper.selectById(customer.getBuildingId());
            // 进业务客户表
            TaRecommendCustomer taRecommendCustomer = new TaRecommendCustomer();
            taRecommendCustomer.setName(customer.getName());
            taRecommendCustomer.setPicture(customer.getPicture());
            taRecommendCustomer.setPhone(customer.getPhone());
            taRecommendCustomer.setSex(customer.getSex());
            taRecommendCustomer.setRecommendPerson(customer.getRecommendPerson());
            taRecommendCustomer.setBuildingId(customer.getBuildingId());
            taRecommendCustomer.setIntention(building.getBuildingName());
            taRecommendCustomer.setReportRecommendStatus(CommConstant.RECOMMENDED);
            taRecommendCustomer.setVerifyStatus(CommConstant.VERIFY_AGREE);
            taRecommendCustomer.setCreateDate(LocalDateTime.now());
            taRecommendCustomer.setReportDate(LocalDateTime.now());
            taRecommendCustomer.setOrgId(customer.getOrgId());
            taRecommendCustomer.setPersonId(customer.getPersonId());
            taRecommendCustomer.setEntryType(CommConstant.ENTRY_VERIFY);
            taRecommendCustomer.setStatus(CommConstant.CUSTOMER_VISITE);
            taRecommendCustomer.setRealtyConsultant(channelCustomerDTO.getRealtyConsultant());
            taRecommendCustomer.setCirculationTime(LocalDateTime.now());
            taRecommendCustomer.setInstitutionId(customer.getInstitutionId());
            taRecommendCustomerMapper.insert(taRecommendCustomer);
            // 审核通过
            customer.setStatus("2");
            customer.setCustomerId(taRecommendCustomer.getCustomerId());
            customerVisit.setCustomerId(taRecommendCustomer.getCustomerId());
            customer.setVisitDate(LocalDateTime.now());
            customer.setName(customerVisit.getName());
            channelCustomerMapper.updateById(customer);
        }else if (StringUtils.isEmpty(recommendCustomer.getRealtyConsultant()) &&
                (StringUtils.isEmpty(recommendCustomer.getRecommendPerson()) || recommendCustomer.getRecommendPerson().equals(customer.getRecommendPerson()))){
            // 审核通过
            customer.setStatus("2");
            customer.setCustomerId(recommendCustomer.getCustomerId());
            customerVisit.setCustomerId(recommendCustomer.getCustomerId());
            customer.setVisitDate(LocalDateTime.now());
            customer.setRealtyConsultant(channelCustomerDTO.getRealtyConsultant());
            customer.setName(customerVisit.getName());
            channelCustomerMapper.updateById(customer);
            // 修改状态为确认到访状态
            recommendCustomer.setRecommendPerson(customer.getRecommendPerson());
            recommendCustomer.setVerifyStatus(CommConstant.VERIFY_AGREE);
            recommendCustomer.setStatus(CommConstant.CUSTOMER_VISITE);
            recommendCustomer.setRealtyConsultant(channelCustomerDTO.getRealtyConsultant());
            recommendCustomer.setCirculationTime(LocalDateTime.now());
            taRecommendCustomerMapper.updateById(recommendCustomer);
        }else {
            return ResponseBean.error("此客户是私客或已被报备", ResponseBean.ERROR_UNAVAILABLE);
        }


        customerVisit.setCreateDate(LocalDateTime.now());
        customerVisitMapper.insert(customerVisit);

        return ResponseBean.success("审核成功");
    }

    /**
     * 驻场确认到访
     *
     * @param
     * @param params
     * @return
     */
    @Override
    public ResponseBean markingChannelCustomer(MarkingChannelCustomerDTO params) {
        CustomerVisit customerVisit = params.getCustomerVisit();
        // 渠道推荐的客户
        if ("report".equals(params.getType())) {
            ChannelCustomer customer = channelCustomerMapper.selectById(params.getId());

            customerVisit.setBuildingId(customer.getBuildingId());
            customerVisit.setRecommendPerson(customer.getRecommendPerson());
            TaPerson recommendPerson = taPersonMapper.getById(customer.getRecommendPerson());
            if (null != recommendPerson) {
                customerVisit.setRealtyConsultantName(recommendPerson.getName());
            }
            customerVisit.setRealtyConsultant(params.getRealtyConsultant());
            TaPerson channelPerson = taPersonMapper.getById(params.getRealtyConsultant());
            if (null != channelPerson) {
                customerVisit.setRealtyConsultantName(channelPerson.getName());
            }
            customerVisit.setOrgId(customer.getOrgId());

            // 审核通过 先查看在ta_recommend_customer 手机号是否存在
            LambdaQueryWrapper<TaRecommendCustomer> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TaRecommendCustomer::getPhone,customer.getPhone());
            queryWrapper.eq(TaRecommendCustomer::getBuildingId,customer.getBuildingId());
            TaRecommendCustomer recommendCustomer = taRecommendCustomerMapper.selectOne(queryWrapper);
            if (null == recommendCustomer) {
                TaBuilding building = taBuildingMapper.selectById(customer.getBuildingId());
                // 进业务客户表
                TaRecommendCustomer taRecommendCustomer = new TaRecommendCustomer();
                taRecommendCustomer.setName(customerVisit.getName());
                taRecommendCustomer.setPicture(customer.getPicture());
                taRecommendCustomer.setPhone(customer.getPhone());
                taRecommendCustomer.setSex(customer.getSex());
                taRecommendCustomer.setRecommendPerson(customer.getRecommendPerson());
                taRecommendCustomer.setBuildingId(customer.getBuildingId());
                taRecommendCustomer.setIntention(building.getBuildingName());
                taRecommendCustomer.setReportRecommendStatus(CommConstant.RECOMMENDED);
                taRecommendCustomer.setVerifyStatus(CommConstant.VERIFY_AGREE);
                taRecommendCustomer.setCreateDate(LocalDateTime.now());
                taRecommendCustomer.setReportDate(LocalDateTime.now());
                taRecommendCustomer.setOrgId(customer.getOrgId());
                taRecommendCustomer.setPersonId(customer.getPersonId());
                taRecommendCustomer.setEntryType(CommConstant.ENTRY_VERIFY);
                taRecommendCustomer.setStatus(CommConstant.CUSTOMER_VISITE);
                taRecommendCustomer.setRealtyConsultant(params.getRealtyConsultant());
                taRecommendCustomer.setCirculationTime(LocalDateTime.now());
                taRecommendCustomer.setInstitutionId(customer.getInstitutionId());
                taRecommendCustomerMapper.insert(taRecommendCustomer);

                // 审核通过
                customer.setStatus(CommConstant.CHANNEL_CUSTOMER_AGREE);
                customer.setVisitDate(LocalDateTime.now());
                customer.setCustomerId(taRecommendCustomer.getCustomerId());
                customerVisit.setCustomerId(taRecommendCustomer.getCustomerId());
                customer.setName(customerVisit.getName());
                channelCustomerMapper.updateById(customer);
            }else if (StringUtils.isEmpty(recommendCustomer.getRealtyConsultant()) &&
                    (StringUtils.isEmpty(recommendCustomer.getRecommendPerson()) || recommendCustomer.getRecommendPerson().equals(customer.getRecommendPerson()))){
                // 审核通过
                customer.setStatus(CommConstant.CHANNEL_CUSTOMER_AGREE);
                customer.setVisitDate(LocalDateTime.now());
                customer.setCustomerId(recommendCustomer.getCustomerId());
                customerVisit.setCustomerId(recommendCustomer.getCustomerId());
                customer.setName(customerVisit.getName());
                channelCustomerMapper.updateById(customer);

                // 修改状态为确认到访状态
                recommendCustomer.setRecommendPerson(customer.getRecommendPerson());
                recommendCustomer.setVerifyStatus(CommConstant.VERIFY_AGREE);
                recommendCustomer.setStatus(CommConstant.CUSTOMER_VISITE);
                recommendCustomer.setRealtyConsultant(params.getRealtyConsultant());
                recommendCustomer.setCirculationTime(LocalDateTime.now());
                recommendCustomer.setName(customerVisit.getName());
                taRecommendCustomerMapper.updateById(recommendCustomer);
            }
        }else if ("customer".equals(params.getType())) {
            // 置业顾问 经纪人推荐的客户
            TaRecommendCustomer taRecommendCustomer = taRecommendCustomerMapper.selectById(params.getId());
            taRecommendCustomer.setVerifyStatus(CommConstant.VERIFY_AGREE);
            taRecommendCustomer.setStatus(CommConstant.CUSTOMER_VISITE);
            taRecommendCustomer.setCirculationTime(LocalDateTime.now());
            customerVisit.setCustomerId(taRecommendCustomer.getCustomerId());
            taRecommendCustomerMapper.updateById(taRecommendCustomer);
        }else {
            return ResponseBean.error("请输入正确的类型参数", ResponseBean.ERROR_UNAVAILABLE);
        }

        // 保存到访单
        customerVisit.setCreateDate(LocalDateTime.now());
        customerVisitMapper.insert(customerVisit);

        return ResponseBean.success("审核成功");
    }

    /**
     * 驻场 无效报备
     *
     * @param params
     * @return
     */
    @Override
    public ResponseBean invalidCustomerUpdate(MarkingChannelCustomerDTO params) {// 渠道推荐的客户
        if ("report".equals(params.getType())) {
            ChannelCustomer customer = channelCustomerMapper.selectById(params.getId());
            // 审核不通过 先查看在ta_recommend_customer 手机号是否存在
            LambdaQueryWrapper<TaRecommendCustomer> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TaRecommendCustomer::getPhone,customer.getPhone());
            queryWrapper.eq(TaRecommendCustomer::getBuildingId,customer.getBuildingId());
            TaRecommendCustomer recommendCustomer = taRecommendCustomerMapper.selectOne(queryWrapper);
            if (null != recommendCustomer) {
                // 审核不通过
                recommendCustomer.setRecommendPerson(customer.getRecommendPerson());
                recommendCustomer.setVerifyStatus(CommConstant.VERIFY_DISAGREE);
                recommendCustomer.setBuildingId(null);
                recommendCustomer.setRealtyConsultant(null);
                recommendCustomer.setRecommendPerson(null);
                taRecommendCustomerMapper.updateById(recommendCustomer);
            }else {
                TaRecommendCustomer taRecommendCustomer = new TaRecommendCustomer();
                taRecommendCustomer.setName(customer.getName());
                taRecommendCustomer.setPicture(customer.getPicture());
                taRecommendCustomer.setPhone(customer.getPhone());
                taRecommendCustomer.setSex(customer.getSex());
                taRecommendCustomer.setRecommendPerson(null);
                taRecommendCustomer.setBuildingId(null);
                taRecommendCustomer.setReportRecommendStatus(CommConstant.RECOMMENDED);
                taRecommendCustomer.setVerifyStatus(CommConstant.VERIFY_AGREE);
                taRecommendCustomer.setCreateDate(LocalDateTime.now());
                taRecommendCustomer.setReportDate(LocalDateTime.now());
                taRecommendCustomer.setOrgId(customer.getOrgId());
                taRecommendCustomer.setPersonId(customer.getPersonId());
                taRecommendCustomer.setEntryType(null);
                taRecommendCustomer.setStatus(CommConstant.CUSTOMER_VISITE);
                taRecommendCustomer.setRealtyConsultant(null);
                taRecommendCustomer.setCirculationTime(LocalDateTime.now());
                taRecommendCustomer.setInstitutionId(customer.getInstitutionId());
                taRecommendCustomerMapper.insert(taRecommendCustomer);
                customer.setCustomerId(taRecommendCustomer.getCustomerId());
            }
            customer.setStatus(CommConstant.CHANNEL_CUSTOMER_DISAGREE);
            channelCustomerMapper.updateById(customer);
            return ResponseBean.success("审核成功");
        }
        return ResponseBean.error("无效操作", ResponseBean.ERROR_UNAVAILABLE);
    }

    @Override
    public IPage<ChannelCustomer> getProfileList(IPage<ChannelCustomer> pg,
                                                 Integer orgId,
                                                 String buildingId,
                                                 String name,
                                                 String phone,
                                                 String recommendPersonName,
                                                 String recommendPhone,
                                                 String status, String type, Integer userId,
                                                 List<String> institutions) {
        return channelCustomerMapper.getProfileList(pg, orgId, buildingId, name, phone, recommendPersonName, recommendPhone, status, type, institutions);
    }

    /**
     * 驻场认筹
     *
     * @param params
     * @return
     */
    @Override
    public ResponseBean preparatoryCustomer(MarkingPreparatoryCustomerDTO params) {
        TaRecommendCustomer taRecommendCustomer = taRecommendCustomerMapper.selectById(params.getCustomerId());
        taRecommendCustomer.setStatus(CommConstant.CUSTOMER_PREPARATORY);
        taRecommendCustomerMapper.updateById(taRecommendCustomer);

        LambdaQueryWrapper<ChannelCustomer> channelCustomerLambdaQueryWrapper = new LambdaQueryWrapper<>();
        channelCustomerLambdaQueryWrapper.eq(ChannelCustomer::getCustomerId,params.getCustomerId());
        ChannelCustomer customer = channelCustomerMapper.selectOne(channelCustomerLambdaQueryWrapper);
        customer.setPreparatoryDate(LocalDateTime.now());
        channelCustomerMapper.updateById(customer);

        CustomerPreparatory customerPreparatory = params.getCustomerPreparatory();
        customerPreparatory.setCreateDate(LocalDateTime.now());
        customerPreparatory.setBuildingId(customer.getBuildingId());
        customerPreparatory.setRecommendPerson(customer.getRecommendPerson());
        TaPerson recommendPerson = taPersonMapper.getById(customer.getRecommendPerson());
        if (null != recommendPerson) {
            customerPreparatory.setRealtyConsultantName(recommendPerson.getName());
        }
        customerPreparatory.setRealtyConsultant(taRecommendCustomer.getRealtyConsultant());
        TaPerson channelPerson = taPersonMapper.getById(taRecommendCustomer.getRealtyConsultant());
        if (null != channelPerson) {
            customerPreparatory.setRealtyConsultantName(channelPerson.getName());
        }
        customerPreparatory.setOrgId(customer.getOrgId());
        customerPreparatoryMapper.insert(customerPreparatory);
        return ResponseBean.success("审核成功");
    }

    /**
     * 驻场结佣金
     *
     * @param params
     * @return
     */
    @Override
    public ResponseBean commissionCustomer(MarkingCommissionCustomerDTO params) {
        CustomerSignatory customerSignatory = params.getCustomerSignatory();
        TaRecommendCustomer taRecommendCustomer = taRecommendCustomerMapper.selectById(params.getCustomerId());
        taRecommendCustomer.setStatus(CommConstant.CUSTOMER_COMMISSION);
        taRecommendCustomerMapper.updateById(taRecommendCustomer);

        LambdaQueryWrapper<ChannelCustomer> channelCustomerLambdaQueryWrapper = new LambdaQueryWrapper<>();
        channelCustomerLambdaQueryWrapper.eq(ChannelCustomer::getCustomerId,params.getCustomerId());
        ChannelCustomer customer = channelCustomerMapper.selectOne(channelCustomerLambdaQueryWrapper);
        customer.setCommissionDate(LocalDateTime.now());
        channelCustomerMapper.updateById(customer);

        customerSignatory.setBuildingId(customer.getBuildingId());
        customerSignatory.setRecommendPerson(customer.getRecommendPerson());
        TaPerson recommendPerson = taPersonMapper.getById(customer.getRecommendPerson());
        if (null != recommendPerson) {
            customerSignatory.setRealtyConsultantName(recommendPerson.getName());
        }
        customerSignatory.setRealtyConsultant(taRecommendCustomer.getRealtyConsultant());
        TaPerson channelPerson = taPersonMapper.getById(taRecommendCustomer.getRealtyConsultant());
        if (null != channelPerson) {
            customerSignatory.setRealtyConsultantName(channelPerson.getName());
        }
        customerSignatory.setOrgId(customer.getOrgId());
        customerSignatory.setCreateDate(LocalDateTime.now());
        customerSignatory.setType("commission");
        customerSignatoryMapper.insert(customerSignatory);
        return ResponseBean.success("审核成功");
    }

    /**
     * 驻场签约
     *
     * @param params
     * @return
     */
    @Override
    public ResponseBean signatoryCustomer(MarkingSignatoryCustomerDTO params) {
        CustomerSignatory customerSignatory = params.getCustomerSignatory();
        TaRecommendCustomer taRecommendCustomer = taRecommendCustomerMapper.selectById(params.getCustomerId());
        taRecommendCustomer.setStatus(CommConstant.CUSTOMER_SIGNED);
        taRecommendCustomer.setRealtyConsultant(customerSignatory.getRealtyConsultant());
        taRecommendCustomerMapper.updateById(taRecommendCustomer);

        LambdaQueryWrapper<ChannelCustomer> channelCustomerLambdaQueryWrapper = new LambdaQueryWrapper<>();
        channelCustomerLambdaQueryWrapper.eq(ChannelCustomer::getCustomerId,params.getCustomerId());
        ChannelCustomer customer = channelCustomerMapper.selectOne(channelCustomerLambdaQueryWrapper);
        customer.setSignedDate(LocalDateTime.now());
        customer.setRealtyConsultant(customerSignatory.getRealtyConsultant());
        channelCustomerMapper.updateById(customer);

        customerSignatory.setCreateDate(LocalDateTime.now());
        customerSignatory.setBuildingId(customer.getBuildingId());
        customerSignatory.setRecommendPerson(customer.getRecommendPerson());
        TaPerson recommendPerson = taPersonMapper.getById(customer.getRecommendPerson());
        if (null != recommendPerson) {
            customerSignatory.setRealtyConsultantName(recommendPerson.getName());
        }
        customerSignatory.setRealtyConsultant(taRecommendCustomer.getRealtyConsultant());
        TaPerson channelPerson = taPersonMapper.getById(taRecommendCustomer.getRealtyConsultant());
        if (null != channelPerson) {
            customerSignatory.setRealtyConsultantName(channelPerson.getName());
        }
        customerSignatory.setOrgId(customer.getOrgId());
        customerSignatory.setType("signatory");
        customerSignatoryMapper.insert(customerSignatory);
        return ResponseBean.success("审核成功");
    }

    /**
     * 查询经纪人的我的客户列表
     *
     * @param pageNumber
     * @param pageSize
     * @param recommendCustomerDTO
     * @return
     */
    @Override
    public ResponseBean getCustomersIRecommended(int pageNumber, int pageSize, RecommendCustomerDTO recommendCustomerDTO) {
        IPage<MineRecommendCustomerPO> page = new Page<MineRecommendCustomerPO>(pageNumber, pageSize);
        IPage<MineRecommendCustomerPO> customersIRecommended = channelCustomerMapper.getCustomersIRecommended(page, recommendCustomerDTO);
        return ResponseBean.success(customersIRecommended);
    }

    @Override
    public ChannelCustomer getMoreInfoById(String id) {
        return channelCustomerMapper.getMoreInfoById(id);
    }
}
