package com.ruixuan.salesLeads.controller;


import com.alibaba.excel.util.ConverterUtils;
import com.alibaba.fastjson.JSONObject;
import com.ruixuan.common.annotation.RateLimiter;
import com.ruixuan.common.core.controller.BaseController;
import com.ruixuan.common.core.domain.ResultResponse;
import com.ruixuan.common.core.redis.RedisCache;
import com.ruixuan.common.utils.DateUtils;
import com.ruixuan.common.utils.StringUtils;
import com.ruixuan.common.utils.file.FileTypeUtils;
import com.ruixuan.common.utils.http.HttpUtil;
import com.ruixuan.salesLeads.listener.ImportExcelListener;
import com.ruixuan.salesLeads.pojo.*;
import com.ruixuan.salesLeads.pojo.vo.SaleRecordVo;
import com.ruixuan.salesLeads.pojo.vo.SaleTaskInfoVo;
import com.ruixuan.salesLeads.service.ISaleClueCallRecordService;
import com.ruixuan.salesLeads.service.ISaleClueInfoService;
import com.ruixuan.salesLeads.service.ITestService;
import com.ruixuan.salesLeads.service.impl.TelephoneRobotServiceImpl;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * ***************************************************
 *
 * @Auther: zianY
 * @Descipion: 销售线索
 * @CreateDate: 2022-05-19
 * ****************************************************
 */


@Slf4j
@Api(tags = "销售线索",description = "saleClueInfoController")
@RestController
@RequestMapping("sale/saleClueInfoController")
public class SaleClueInfoController extends BaseController {


    @Autowired
    private ISaleClueInfoService saleClueInfoServiceImpl;


    @Autowired
    private TelephoneRobotServiceImpl telephoneRobotService;







    @ApiOperation(value = "销售线索上传",notes = "swagger不支持上传,请使用postman上传,支持form-data。文件绑定参数为file")
    @PostMapping(value = "/importSaleExcelOrCsv")
    public ResultResponse importSaleExcelOrCsv(
                                      @ApiParam("文件数组") @RequestParam("file") MultipartFile file,
                                      @ApiParam("销售线索类型1:50W低潜;2:50W中高潜;3:200W高潜;4:200W-500w;5:500W") @RequestParam("salesLeadsType") int salesLeadsType,
                                      @ApiParam("年-月") @RequestParam("uploadDate") String uploadDate,
                                      @ApiParam("创建人") @RequestParam("createUserId") Long createUserId
                                      ) throws Exception{
        if (file.isEmpty()){
            return ResultResponse.error("文件不能为空，请选择文件！");
        }

       if (!FileTypeUtils.fileNameSuffix(file)){
           return ResultResponse.error("请上传正确格式的文件，支持扩展名.xls;.xlsx;.csv");
       }

        Long year = DateUtils.strDateToInt(uploadDate);
        return saleClueInfoServiceImpl.importSaleExcelOrCsv(file,salesLeadsType,year,createUserId);
    }





    @ApiOperation(value = "销售线索列表查询",notes = "销售线索列表查询，查询条件为空时，所对应的字段可以不传。")
    @GetMapping(value = "/selectSaleClueInfoList")
    public ResultResponse<List<SaleClueInfoPojo>> selectSaleClueInfoList(
            @ApiParam("卖家昵称") @RequestParam(value = "sellerName",required = false) String sellerName,
            @ApiParam("年-月") @RequestParam(value = "uploadDate", required = false) String uploadDate,
            @ApiParam("是否分配销售 0-否 1-是") @RequestParam(value = "distributionSaleFlag",required = false)String distributionSaleFlag,
            @ApiParam("行业id") @RequestParam(value = "industryId",required = false)String industryId,
            @ApiParam("粉丝量级 1:0~50w 2:50W~200W 3:200W~500W 4:500W以上") @RequestParam(value = "fansType",required = false)String fansType,
            @ApiParam("状态 1-未开始 2-进行中 3-已结束") @RequestParam(value = "state",required = false)String state,
            @ApiParam("状态 1-未开始 2-进行中 3-已结束") @RequestParam(value = "salesLeadsType",required = false)String salesLeadsType,
            @ApiParam("当前用户id") @RequestParam(value = "userId",required = false) Long userId) throws Exception{

        return saleClueInfoServiceImpl.selectSaleClueInfoList(sellerName,
                StringUtils.isEmpty(uploadDate) ? null : DateUtils.strDateToInt(uploadDate),
                distributionSaleFlag,industryId,fansType,state,salesLeadsType, userId);

    }



    @ApiOperation(value = "销售线索-分配-显示数据信息",notes = "销售线索-分配-显示数据信息(可以传多个卖家id)")
    @GetMapping(value = "/selectSaleClueInfoBySellers")
    public ResultResponse<List<SaleClueInfoPojo>> selectSaleClueInfoBySellers(
            @ApiParam(value = "卖家ids") @RequestParam(value = "sellerIds") List<String> sellerIds){
        List<Long> longList = sellerIds.stream().map(sellerId -> Long.parseLong(sellerId.trim())).collect(Collectors.toList());
        return saleClueInfoServiceImpl.selectSaleClueInfoBySellers(longList);
    }




    @ApiOperation(value = "销售线索-分配",notes = "销售线索-分配-(可以传多个销售线索id，废弃入参传卖家id)")
    @PostMapping(value = "/saleClueDistribution")
    public ResultResponse saleClueDistribution(
            @ApiParam(value = "销售线索ids") @RequestParam(value = "sellerIds") String sellerIds,
            @ApiParam(value = "销售id") @RequestParam(value = "saleId") Long saleId,
            @ApiParam(value = "创建人id") @RequestParam(value = "createUserId") Long createUserId){
        List<String> sellerList = Arrays.asList(StringUtils.split(sellerIds,","));
        return saleClueInfoServiceImpl.saleClueDistribution(sellerList,saleId,createUserId);
    }



    @ApiOperation(value = "销售线索-转面销",notes = "销售线索-转面销")
    @PostMapping(value = "/saleClueToOffline")
    public ResultResponse saleClueToOffline(@ApiParam(value = "卖家id") @RequestParam(value = "sellerId") Long sellerId,
                                            //@ApiParam(value = "类型1-电销 2-面销") @RequestParam(value = "offlineSaleFlag") String offlineSaleFlag,
                                            @ApiParam(value = "销售id") @RequestParam(value = "saleId") Long saleId,
                                            @ApiParam(value = "创建人id") @RequestParam(value = "createUserId") Long createUserId){

        return saleClueInfoServiceImpl.saleClueToOffline(sellerId, 2,saleId,createUserId);

    }







    @ApiOperation(value = "销售线索任务列表查询",notes = "销售线索任务列表查询")
    @GetMapping(value = "/selectSaleClueTaskList")
    public ResultResponse<List<SaleClueInfoPojo>> selectSaleClueTaskList(
            @ApiParam("模糊查询") @RequestParam(value = "sellerName",required = false) String sellerName,
            @ApiParam("状态 1-未开始 2-进行中 3-已结束") @RequestParam(value = "state",required = false)Integer state,
            @ApiParam("当前用户id") @RequestParam(value = "userId") Long userId){

        return saleClueInfoServiceImpl.selectSaleClueTaskList(sellerName,state, userId);

    }




    @ApiOperation(value = "销售线索任务-查询用户代办以及本周完成的数量汇总",notes = "complete-本周完成数量；noStarted-我的待办")
    @GetMapping(value = "/getTaskNumber")
    public ResultResponse getTaskNumber(@ApiParam("当前用户id") @RequestParam(value = "userId") Long userId){
        return saleClueInfoServiceImpl.getTaskNumber(userId);
    }



    @ApiOperation(value = "销售线索任务-回显线索详情",notes = "回显线索详情")
    @GetMapping(value = "/getSaleTaskInfoBySellerId")
    public ResultResponse<SaleTaskInfoVo> getSaleTaskInfoBySellerId(@ApiParam("卖家id") @RequestParam(value = "sellerId") Long sellerId){
        return saleClueInfoServiceImpl.getSaleTaskInfoBySellerId(sellerId);
    }



    @ApiOperation(value = "销售线索任务-新增跟进记录",notes = "销售线索任务-新增跟进记录")
    @PostMapping(value = "/insertSaleTaskRecord")
    public ResultResponse insertSaleTaskRecord(SaleClueRecordInfoPojo recordInfoPojo){

        return saleClueInfoServiceImpl.insertSaleTaskRecord(recordInfoPojo);

    }


    @ApiOperation(value = "销售线索-基础-根据角色显示销售线索分类",notes = "销售线索-基础-根据角色显示销售线索分类(销售线索类型1:50W低潜；2:50W中高潜3:200W高潜4:200W-500w5:500W)")
    @GetMapping(value = "/getSaleTypeByRoleCode")
    public ResultResponse getSaleTypeByRoleCode(@ApiParam("角色code") @RequestParam(value = "roleCode") String roleCode){

        List<Map<String,String>> resultList = new ArrayList<>();
        Map<String,String> map1 = new HashMap<>();
        map1.put("salesLeadsType","1");
        map1.put("salesLeadsName","50W低潜");

        Map<String,String> map2 = new HashMap<>();
        map2.put("salesLeadsType","2");
        map2.put("salesLeadsName","50W中高潜");

        Map<String,String> map3 = new HashMap<>();
        map3.put("salesLeadsType","3");
        map3.put("salesLeadsName","200W高潜");

        Map<String,String> map4 = new HashMap<>();
        map4.put("salesLeadsType","4");
        map4.put("salesLeadsName","200W-500w");

        Map<String,String> map5 = new HashMap<>();
        map5.put("salesLeadsType","5");
        map5.put("salesLeadsName","500W");

        resultList.add(map1);
        resultList.add(map2);
        resultList.add(map3);
        resultList.add(map4);
        resultList.add(map5);

        //电销
        //50w 排第一个

        //面销
        if (roleCode.contains("facePin")){
            resultList.remove(map3);
            //200W 排第一个
            resultList.add(0,map3);
        }

        return ResultResponse.successMsg("查询成功",resultList);

    }




    @ApiOperation(value = "外呼机器人-获取token",notes = "外呼机器人-获取token")
    @PostMapping(value = "/getTelephoneRobotToken")
    public ResultResponse getTelephoneRobotToken(){
        JSONObject jsonObject = telephoneRobotService.getTelephoneRobotToken();
        return ResultResponse.successMsg("外呼机器人获取token成功",jsonObject);
    }



    @Autowired
    private ISaleClueCallRecordService saleClueCallRecordService;



    @ApiOperation(value = "回调地址",notes = "回调地址")
    @PostMapping(value = "/robotCallbackUrl")
    public ResultResponse robotCallbackUrl(@RequestBody JSONObject json){
        log.info("=======推送数据信息开始========");
        return saleClueCallRecordService.saveClueCallInfo(json);
    }




    @ApiOperation(value = "外呼机器人-导入号码",notes = "外呼机器人-导入号码(可以传多个销售线索id,英文逗号分割)")
    @RateLimiter(count = 1)
    @PostMapping(value = "/importRobotTelephone")
    public ResultResponse importRobotTelephone(@ApiParam(value = "销售线索ids,英文逗号分割") @RequestParam(value = "ids") List<Long> sellerIds,
                                               @ApiParam(value = "用户id") @RequestParam(value = "userId") String userId) throws Exception {
        if (sellerIds.size() > 5000){
            return ResultResponse.error("单次最大导入号码数量不能超过5000条！");
        }
        return telephoneRobotService.importRobotTelephone(sellerIds,userId);
    }


    @ApiOperation(value = "外呼机器人-导入的电话记录查询",notes = "外呼机器人-导入的电话记录查询")
    @GetMapping(value = "/getRobotTelephoneRecordList")
    public ResultResponse<List<SaleClueCallRecordPojo>> getRobotTelephoneRecordList(){
        return telephoneRobotService.getRobotTelephoneRecordList();
    }



    @ApiOperation(value = "外呼机器人-通话记录查询",notes = "外呼机器人-通话记录查询")
    @GetMapping(value = "/getRobotTelephoneResultList")
    public ResultResponse<List<SaleClueCallResultPojo>> getRobotTelephoneResultList(@ApiParam("创建时间") @RequestParam(value = "createTime",required = false) String createTime,
                                                                                    @ApiParam("销售线索状态 1-未开始 2-进行中 3-已结束") @RequestParam(value = "state",required = false) Integer state){

        return telephoneRobotService.getRobotTelephoneResultList(createTime,state);
    }





}
