package com.ruixuan.salesLeads.service.impl;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.ruixuan.common.core.domain.ResultResponse;
import com.ruixuan.common.core.page.TableDataInfo;
import com.ruixuan.common.utils.DateUtils;
import com.ruixuan.common.utils.PageUtils;
import com.ruixuan.common.utils.StringUtils;
import com.ruixuan.common.utils.file.FileTypeUtils;
import com.ruixuan.salesLeads.listener.ImportExcelListener;
import com.ruixuan.salesLeads.mapper.SaleClueDistributionInfoMapper;
import com.ruixuan.salesLeads.mapper.SaleClueInfoMapper;
import com.ruixuan.salesLeads.mapper.SaleClueRecordInfoMapper;
import com.ruixuan.salesLeads.mapper.SaleQuotaInfoMapper;
import com.ruixuan.salesLeads.pojo.SaleClueDistributionInfoPojo;
import com.ruixuan.salesLeads.pojo.SaleClueInfoPojo;
import com.ruixuan.salesLeads.pojo.SaleClueRecordInfoPojo;
import com.ruixuan.salesLeads.pojo.SaleQuotaInfoPojo;
import com.ruixuan.salesLeads.pojo.vo.SaleRecordVo;
import com.ruixuan.salesLeads.pojo.vo.SaleTaskInfoVo;
import com.ruixuan.salesLeads.service.ISaleClueInfoService;
import com.ruixuan.salesLeads.utils.CsvImportUtil;
import com.ruixuan.system.domain.SysAreaInfo;
import com.ruixuan.system.domain.SysIndustryInfo;
import com.ruixuan.system.mapper.SysAreaInfoMapper;
import com.ruixuan.system.mapper.SysIndustryInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * ***************************************************
 *
 * @Auther: zianY
 * @Descipion: demo测试
 * @CreateDate: 2022-05-19
 * ****************************************************
 */
@Service
@Slf4j
public class SaleClueInfoServiceImpl implements ISaleClueInfoService {


    @Autowired
    private SaleClueInfoMapper saleClueInfoMapper;


    @Autowired
    private SaleQuotaInfoMapper saleQuotaInfoMapper;

    @Autowired
    private SysIndustryInfoMapper sysIndustryInfoMapper;

    @Autowired
    private SysAreaInfoMapper sysAreaInfoMapper;

    @Autowired
    private SaleClueRecordInfoMapper saleClueRecordInfoMapper;


    @Autowired
    private SaleClueDistributionInfoMapper saleClueDistributionInfoMapper;






    /**
     * Author: zianY
     * Description: 销售线索添加
     * 支持excel 和 csv 文件上传
     *------------
     * @param file
     * @param salesLeadsType 销售线索类型1:50W低潜;2:50W中高潜;3:200W高潜;4:200W-500w;5:500W
     * @param uploadDate 时间 格式为202205
     * @param createUserId
     *------------
     * Return com.ruixuan.common.core.domain.ResultResponse
     */
    @Override
    public ResultResponse importSaleExcelOrCsv(MultipartFile file, int salesLeadsType, Long uploadDate, Long createUserId){

        List<Map<String,String>> dataList = new ArrayList<>();

        //文件类型
        String fileType = FileTypeUtils.gerFileTypeXlsOrCsv(file);

        try {




        if (StringUtils.equals("excel",fileType)){
            //读取Excel
            EasyExcel.read(file.getInputStream(),null,
                        new ImportExcelListener()).sheet().headRowNumber(1).doRead();
            //头 信息
            //Map<Integer, String> headList = ImportExcelListener.importHeadList;
            //结果集
            dataList = ImportExcelListener.importDataList;

        }

        if (StringUtils.equals("csv",fileType)){
            dataList = CsvImportUtil.readCSV(file);
        }
        //处理数据结果
        resultData(dataList,salesLeadsType,uploadDate,createUserId);

        //excel 清除监听数据
        ImportExcelListener.importDataList.clear();
        ImportExcelListener.importHeadList.clear();

        }catch (Exception e){
            //excel 清除监听数据
            ImportExcelListener.importDataList.clear();
            ImportExcelListener.importHeadList.clear();
            log.error("上传文件出现了问题。{}",e.toString());
            e.printStackTrace();
            return ResultResponse.error("上传文件失败。");
        }

        return ResultResponse.successMsg("保存成功",null);
    }


    /**
     * 处理销售线索 数据结果
     * @param dataList
     * @param salesLeadsType
     * @param uploadDate
     * @param createUserId
     */
    public void resultData(List<Map<String,String>> dataList,int salesLeadsType,Long uploadDate,Long createUserId){
        List<SaleClueInfoPojo> clueList = new ArrayList<>();
        List<SaleQuotaInfoPojo> quotaList = new ArrayList<>();
        for (Map<String, String> dataMap : dataList) {

            if(StringUtils.isEmpty(dataMap)){
                continue;
            }
            //log.info("datamap----{}",dataMap);

            if (!dataMap.containsKey("sellerId")){
                continue;
            }

            if (dataMap.get("sellerId").isEmpty()){
                //log.info("sellerId----{}",dataMap.get("sellerId"));
                continue;
            }

            //log.info("datamap----{}",dataMap);
            SaleClueInfoPojo clue = new SaleClueInfoPojo();
            SaleQuotaInfoPojo quota = new SaleQuotaInfoPojo();

            clue.setSalesLeadsType(salesLeadsType);

            clue.setSellerId(Long.valueOf(dataMap.get("sellerId")));
            clue.setSellerName(dataMap.get("sellerName"));
            clue.setFans(Long.valueOf(dataMap.get("fans")));
            clue.setTelephone(StringUtils.isEmpty(dataMap.get("telephone")) ? "" : dataMap.get("telephone"));
            clue.setProviderFlag(dataMap.get("providerFlag"));
            clue.setTransitionFlag(dataMap.get("transitionFlag"));
            clue.setCreateUserId(createUserId);
            clue.setUploadDate(uploadDate);

            SaleRecordVo recordVo = saleClueInfoMapper.selectSaleClueInfoBySellerId(clue.getSellerId());
            clue.setState(StringUtils.isNotNull(recordVo) ? recordVo.getState() : 1);
            clue.setSaleId(StringUtils.isNotNull(recordVo) && StringUtils.isNotNull(recordVo.getSaleId()) ? recordVo.getSaleId() : 0L);
            clue.setOfflineSaleFlag(StringUtils.isNotNull(recordVo) ? recordVo.getOfflineSaleFlag() : 1);


            //查询行业
            SysIndustryInfo industryInfo = sysIndustryInfoMapper.getIndustryInfoByName(dataMap.get("industryId"));
            clue.setIndustryId(StringUtils.isNull(industryInfo) ? 0 : industryInfo.getId());
            //根据城市查询 省市id
            SysAreaInfo areaInfo = sysAreaInfoMapper.getAreaInfoByName(dataMap.get("cityId"));
            clue.setProvinceId(areaInfo == null ? 0 : areaInfo.getParentCode());
            clue.setCityId(areaInfo == null ? 0 : areaInfo.getCode());

            if (StringUtils.isNotEmpty(dataMap.get("NearlyThirtyDays"))){
                quota.setNearlyThirtyDays(dataMap.get("NearlyThirtyDays"));

            }

            if (StringUtils.isNotEmpty(dataMap.get("gmv"))){
                quota.setGmvMonth(Long.valueOf(dataMap.get("gmvMonth")));
                quota.setGmv(dataMap.get("gmv"));
            }

            if (StringUtils.isNotEmpty(dataMap.get("mtd"))){
                quota.setMtdDate(Long.valueOf(dataMap.get("mtdDate")));
                quota.setMtd(dataMap.get("mtd"));
            }

            if (StringUtils.isNotEmpty(dataMap.get("NearlyThirtyDays")) ||
                    StringUtils.isNotEmpty(dataMap.get("gmv")) ||
                    StringUtils.isNotEmpty(dataMap.get("mtd"))){
                quota.setCreateUserId(createUserId);
                quota.setSellerId(Long.valueOf(dataMap.get("sellerId")));
            }



            if (StringUtils.isNotNull(clue)){
                clueList.add(clue);
            }
            if (StringUtils.isNotNull(quota.getSellerId())){
                quotaList.add(quota);
            }




        }


        if (clueList.size() > 0){
            //销售线索
            saleClueInfoMapper.replaceSaleClueInfoBatch(clueList);
        }
        if (quotaList.size() > 0){
            //线索-额度
            saleQuotaInfoMapper.replaceSaleQuotaInfoBatch(quotaList);
        }




    }




    /**
     *
     * @description: 销售线索列表查询
     *
     * @param sellerName 卖家昵称
     * @param uploadDate 年月
     * @param distributionSaleFlag 是否分配销售 0-否 1-是
     * @param industryId 行业id
     * @param fansType 粉丝量级 1:0~50w 2:50W~200W 3:200W~500W 4:500W以上
     * @param userId
     * @return: com.ruixuan.common.core.domain.ResultResponse<java.util.List<com.ruixuan.salesLeads.pojo.SaleClueInfoPojo>>
     * @author: zianY
     */
    @Override
    public ResultResponse selectSaleClueInfoList(String sellerName, Long uploadDate, String distributionSaleFlag, String industryId, String fansType, String state,String salesLeadsType,Long userId) throws Exception {

        PageUtils.startPage();
        List<SaleClueInfoPojo> saleList =  saleClueInfoMapper.selectSaleClueInfoList(sellerName,uploadDate,distributionSaleFlag,industryId,fansType,state,salesLeadsType, userId);
        saleList.forEach(clue ->{
            clue.setFirstRecord(saleClueRecordInfoMapper.getSaleClueRecordNumber(clue.getSellerId(),1));
            clue.setSecondRecord(saleClueRecordInfoMapper.getSaleClueRecordNumber(clue.getSellerId(),2));

            //近30天 gmv mtd
            SaleQuotaInfoPojo quotaInfoPojo = saleQuotaInfoMapper.getSaleQuotaInfoBySellerId(clue.getSellerId());
            if (StringUtils.isNotNull(quotaInfoPojo)){
                clue.setNearlyThirtyDays(quotaInfoPojo.getNearlyThirtyDays());
                clue.setGmvMonth(quotaInfoPojo.getGmvMonth());
                clue.setGmv(quotaInfoPojo.getGmv());
                clue.setMtdDate(quotaInfoPojo.getMtdDate());
                clue.setMtd(quotaInfoPojo.getMtd());
            }


        });
        return ResultResponse.successMsg("查询成功。",new TableDataInfo(saleList,new Long(new PageInfo(saleList).getTotal()).intValue()));
    }


    /**
     *
     * @description: 销售线索任务列表查询
     *
     * @param sellerName 模糊查询
     * @param state 状态 1-未开始 2-进行中 3-已结束
     * @param userId  当前用户id
     * @return: com.ruixuan.common.core.domain.ResultResponse<java.util.List<com.ruixuan.salesLeads.pojo.SaleClueInfoPojo>>
     * @author: zianY
     */
    @Override
    public ResultResponse selectSaleClueTaskList(String sellerName,Integer state, Long userId) {
        PageUtils.startPage();
        List<SaleClueInfoPojo> saleList =  saleClueInfoMapper.selectSaleClueTaskList(sellerName,state, userId);

        saleList.forEach(cluePojo -> {
            //获取最新一条记录信息
            List<SaleClueRecordInfoPojo> list = saleClueRecordInfoMapper.selectDistributionList(cluePojo.getSellerId());
            cluePojo.setRecordTask(StringUtils.isEmpty(list) ? null : list.get(list.size()-1));
        });


        return ResultResponse.successMsg("查询成功。",new TableDataInfo(saleList,new Long(new PageInfo(saleList).getTotal()).intValue()));
    }



    /**
     *
     * @description: 销售线索-分配-显示数据信息
     *
     * @param sellerIds 卖家id
     * @return: com.ruixuan.common.core.domain.ResultResponse<java.util.List<com.ruixuan.salesLeads.pojo.SaleClueInfoPojo>>
     * @author: zianY
     */
    @Override
    public ResultResponse<List<SaleClueInfoPojo>> selectSaleClueInfoBySellers(List<Long> sellerIds){
        List<SaleClueInfoPojo> saleList =  saleClueInfoMapper.selectSaleClueInfoBySellers(sellerIds);
        return ResultResponse.successMsg("查询成功。",saleList);
    }


    /**
     *
     * @description: 销售线索-分配
     *
     * @param sellerIds 销售线索ids
     * @param saleId 销售id
     * @param createUserId
     * @return: com.ruixuan.common.core.domain.ResultResponse
     * @author: zianY
     */
    @Override
    public ResultResponse saleClueDistribution(List<String> sellerIds, Long saleId,Long createUserId){

         sellerIds.forEach(sellerId -> {
             //销售线索id查询
             SaleRecordVo saleInfo = saleClueInfoMapper.selectSaleClueInfoById(Integer.valueOf(sellerId));

             //修改销售线索 销售
             saleClueInfoMapper.updateSaleClueSale(saleInfo.getSellerId(),saleId,1);
             // 修改线索 状态
             saleClueInfoMapper.updateSaleClueState(saleInfo.getSellerId(),2);
             //添加 分配记录
             saleClueDistributionInfoMapper.insertSaleClueDistribution(new SaleClueDistributionInfoPojo(saleInfo.getSellerId(),saleId,createUserId));
         });

        return ResultResponse.successMsg("分配销售成功。",null);
    }



    /**
     *
     * @description:销售线索任务-查询用户代办以及本周完成的数量汇总
     *
     * @param userId
     * @return: com.ruixuan.common.core.domain.ResultResponse
     * @author: zianY
     */
    @Override
    public ResultResponse getTaskNumber(Long userId){
         Map<String,Integer> resultMap = new HashMap<>();
         //获取当前周的开始和截至时间
         Map<String,String> map = DateUtils.getWeekBeginAndEnd();

         //本周有意向合作
         int complete = saleClueRecordInfoMapper.selectSaleClueIntention(userId,map.get("begin"),map.get("end"));
         //用户代办-包括未开始与进行中
         int noStarted = saleClueInfoMapper.selectSaleClueComplete(userId);

         resultMap.put("complete",complete);
         resultMap.put("noStarted",noStarted);

        return ResultResponse.successMsg("销售汇总查询成功。",resultMap);
    }


    /**
     * 销售线索任务-回显线索详情
     * @param sellerId
     * @return
     */
    @Override
    public ResultResponse getSaleTaskInfoBySellerId(Long sellerId){

        SaleTaskInfoVo saleTaskInfoVo = new SaleTaskInfoVo();
          //线索详情
        SaleRecordVo saleInfo = saleClueInfoMapper.selectSaleClueInfoBySellerId(sellerId);
         //记录信息
        List<SaleClueRecordInfoPojo> recordList = saleClueRecordInfoMapper.selectDistributionList(sellerId);

        saleTaskInfoVo.setSaleRecordVo(saleInfo);
        saleTaskInfoVo.setRecordList(recordList);
        saleTaskInfoVo.setNextNum(StringUtils.isEmpty(recordList) ? 1 : recordList.size()+1);

        return ResultResponse.successMsg("查询成功。",saleTaskInfoVo);
    }


    /**
     * 销售线索任务-新增跟进记录
     * @param recordInfoPojo
     * @return
     */
    @Override
    public ResultResponse insertSaleTaskRecord(SaleClueRecordInfoPojo recordInfoPojo){

        //新增跟进记录
        saleClueRecordInfoMapper.insertSaleRedord(recordInfoPojo);

        //修改线索状态
        //是否继续跟进 1-继续跟进 2-意向合作 3-跟进完成无合作
        if (recordInfoPojo.getContinueFlag() == 1){
            //线索状态 1-未开始 2-进行中 3-已结束
            saleClueInfoMapper.updateSaleClueState(recordInfoPojo.getSellerId(),2);
        }

        if (recordInfoPojo.getContinueFlag() == 2){
            //意向合作 1-不合作可跟进 2-添加微信 3-操盘合作 4-服务商合作 5-金牛合作 6-无法添加微信
            if (StringUtils.equals(recordInfoPojo.getIntendedCooperation(),"1")
                    || StringUtils.isEmpty(recordInfoPojo.getIntendedCooperation())){
                saleClueInfoMapper.updateSaleClueState(recordInfoPojo.getSellerId(),2);
            }else{
                saleClueInfoMapper.updateSaleClueState(recordInfoPojo.getSellerId(),3);
            }
        }

        if (recordInfoPojo.getContinueFlag() == 3){
            saleClueInfoMapper.updateSaleClueState(recordInfoPojo.getSellerId(),3);
        }
        return ResultResponse.successMsg("新增跟进记录成功。",null);
    }





    /**
     *
     * @description: 销售线索-转面销/电销
     *
     * @param sellerId 卖家id
     * @param offlineSaleFlag 类型1-电销 2-面销
     * @param saleId 销售人员
     * @param createUserId
     * @return: com.ruixuan.common.core.domain.ResultResponse
     */
    @Override
    public ResultResponse saleClueToOffline(Long sellerId,int offlineSaleFlag,Long saleId,Long createUserId){
        saleClueInfoMapper.updateSaleClueOfflineFlag(sellerId,offlineSaleFlag,saleId);
        return ResultResponse.successMsg("成功。",null);
    }








}
