package com.fs.crm.controller;

import com.fs.common.annotation.DataScope;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.OrderUtils;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.company.domain.CompanyUser;
import com.fs.company.service.ICompanyUserService;
import com.fs.crm.param.CrmCompanyLineCustomerImportParam;
import com.fs.core.security.LoginUser;
import com.fs.core.web.service.TokenService;
import com.fs.crm.domain.CrmCustomer;
import com.fs.crm.param.*;
import com.fs.crm.service.ICrmCustomerService;
import com.fs.crm.service.ICrmCustomerUserService;
import com.fs.crm.vo.*;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 客户Controller
 *
 * @author fs
 * @date 2022-12-21
 */
@RestController
@RequestMapping("/crm/customer")
public class CrmCustomerController extends BaseController
{
    @Autowired
    private ICrmCustomerService crmCustomerService;
    @Autowired
    ICompanyUserService companyUserService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    ICrmCustomerUserService crmCustomerUserService;

    @ApiOperation("获取线索客户")
    @PreAuthorize("@ss.hasPermi('crm:customer:lineList')")
    @GetMapping("/getLineCustomerList")
    public TableDataInfo getLineCustomerList(CrmLineCustomerListQueryParam param)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        List<CrmLineCustomerListQueryVO> list = crmCustomerService.selectCrmLineCustomerListQuery(param);
        if (list != null) {
            for (CrmLineCustomerListQueryVO vo : list) {
                if(vo.getMobile()!=null){
                    vo.setMobile(vo.getMobile().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                }
            }
        }
        return getDataTable(list);
    }

    @ApiOperation("获取公海客户")
    @PreAuthorize("@ss.hasPermi('crm:customer:fullList')")
    @GetMapping("/getFullCustomerList")
    @DataScope(deptAlias = "c",userAlias = "c")
    public TableDataInfo getFullCustomerList(CrmFullCustomerListQueryParam param)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        param.setCompanyId(loginUser.getCompany().getCompanyId());
//        if(loginUser.getCompany().getCompanyId()==116){   // 河北湘银信息咨询服务有限公司（JZ-1）客户假删除不显示
//            param.setCompanyId(0L);
//        }
        List<CrmFullCustomerListQueryVO> list = crmCustomerService.selectCrmFullCustomerListQuery(param);
        if (list != null) {
            for (CrmFullCustomerListQueryVO vo : list) {
                if(vo.getMobile()!=null){
                    vo.setMobile(vo.getMobile().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                }

            }
        }
        return getDataTable(list);
    }

    @ApiOperation("获取我的客户列表")
    @PreAuthorize("@ss.hasPermi('crm:customer:myList')")
    @GetMapping("/getMyCustomerList")
    public TableDataInfo getMyCustomerList(CrmMyCustomerListQueryParam param){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        param.setCompanyUserId(loginUser.getUser().getUserId());
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        if(!StringUtils.isEmpty(param.getCreateTimeRange())){
            param.setCustomerCreateTime(param.getCreateTimeRange().split("--"));
        }
        List<CrmMyCustomerListQueryVO> list = crmCustomerService.selectCrmMyCustomerListQuery(param);
        if (list != null) {
            for (CrmMyCustomerListQueryVO vo : list) {
                if(vo.getMobile()!=null){
                    vo.setMobile(vo.getMobile().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                }
            }
        }
        return getDataTable(list);

    }

    @ApiOperation("获取我的协作客户列表")
    @PreAuthorize("@ss.hasPermi('crm:customer:assistList')")
    @GetMapping("/getMyAssistList")
    public TableDataInfo getMyAssistList(CrmMyCustomerListQueryParam param){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        param.setCompanyUserId(loginUser.getUser().getUserId());
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        if(!StringUtils.isEmpty(param.getCreateTimeRange())){
            param.setCustomerCreateTime(param.getCreateTimeRange().split("--"));
        }
        List<CrmMyCustomerListQueryVO> list = crmCustomerService.selectCrmMyAssistListQuery(param);
        if (list != null) {
            for (CrmMyCustomerListQueryVO vo : list) {
                if(vo.getMobile()!=null){
                    vo.setMobile(vo.getMobile().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                }
            }
        }
        return getDataTable(list);

    }

    @ApiOperation("获取客户列表")
    @GetMapping("/getCustomerList")
    @PreAuthorize("@ss.hasPermi('crm:customer:list')")
    public TableDataInfo getCustomerList(CrmCustomerListQueryParam param){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        param.setCompanyId(loginUser.getCompany().getCompanyId());
//        if(loginUser.getCompany().getCompanyId()==116){   // 河北湘银信息咨询服务有限公司（JZ-1）客户假删除不显示
//            param.setCompanyId(0L);
//        }
        if (param.getIsReceive() != null && param.getIsReceive() == 0){
            CrmLineCustomerListQueryParam param1 = new CrmLineCustomerListQueryParam();
            BeanUtils.copyProperties(param,param1);
            List<CrmLineCustomerListQueryVO> list1 = crmCustomerService.selectCrmLineCustomerListQuery(param1);
            if (list1 != null) {
                for (CrmLineCustomerListQueryVO vo : list1) {
                    if(vo.getMobile()!=null){
                        vo.setMobile(vo.getMobile().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                    }

                }
            }
            return getDataTable(list1);
        }else {
            List<CrmCustomerListQueryVO> list = crmCustomerService.selectCrmCustomerListQuery(param);
            if (list != null) {
                for (CrmCustomerListQueryVO vo : list) {
                    if (vo.getMobile() != null) {
                        vo.setMobile(vo.getMobile().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                    }

                }
            }
            return getDataTable(list);
        }
    }
    @ApiOperation("获取客户详情")
    @GetMapping("/getCustomerDetails")
    @PreAuthorize("@ss.hasPermi('crm:customer:query')")
    public R getCustomerDetails(
            HttpServletRequest request,
            @ApiParam(required = true, name = "customerId", value = "客户ID") @RequestParam(value = "customerId", required = false) Long customerId
    ){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        CrmCustomer customer=crmCustomerService.selectCrmCustomerById(customerId);
        Boolean isReceive=false;
        if(customer.getIsReceive()!=null&&customer.getIsReceive()==1&&customer.getReceiveUserId()!=null&&loginUser.getUser().getUserId().equals(customer.getReceiveUserId())){
            isReceive=true;
        }
        return R.ok().put("customer",customer).put("isReceive",isReceive);

    }

    @ApiOperation("获取客户详情")
    @GetMapping("/getCustomerDetails1")
    @PreAuthorize("@ss.hasPermi('crm:customer:query1')")
    public R getCustomerDetails1(
            HttpServletRequest request,
            @ApiParam(required = true, name = "customerId", value = "客户ID") @RequestParam(value = "customerId", required = false) Long customerId
    ){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        CrmCustomer customer=crmCustomerService.selectCrmCustomerById(customerId);
        customer.setMobile(customer.getMobile().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
        Boolean isReceive=false;
        if(customer.getIsReceive()!=null&&customer.getIsReceive()==1&&customer.getReceiveUserId()!=null&&loginUser.getUser().getUserId().equals(customer.getReceiveUserId())){
            isReceive=true;
        }
        return R.ok().put("customer",customer).put("isReceive",isReceive);

    }

    @PreAuthorize("@ss.hasPermi('crm:customer:query2')")
    @GetMapping(value = "/query1/{customerId}")
    public R getInfo1(@PathVariable("customerId") Long customerId)
    {
        CrmCustomer customer=crmCustomerService.selectCrmCustomerById(customerId);
        String mobile = customer.getMobile();
        return R.ok().put("mobile",mobile);
    }

    //分配
    @PreAuthorize("@ss.hasPermi('crm:customer:assignToUser')")
    @PostMapping("/assignToUser")
    public R assignToUser(@RequestBody CrmCustomeAssignParam param)
    {
        if(param.getCustomerIds().size()>1000){
            return R.error("分配数据超出范围,最大1000条");
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        return crmCustomerService.assignToUser(loginUser.getUsername(),loginUser.getUser().getUserId(),param);
    }

    //添加协作人
//    @PreAuthorize("@ss.hasPermi('crm:customer:assistToUser')")
    @PostMapping("/assistToUser")
    public R assistToUser(@RequestBody CrmCustomeAssignParam param)
    {
        if(param.getCustomerIds().size()>1000){
            return R.error("分配数据超出范围,最大1000条");
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        return crmCustomerService.assistToUser(loginUser.getUsername(),loginUser.getUser().getUserId(),param);
    }


    @PreAuthorize("@ss.hasPermi('crm:customer:add')")
    @Log(title = "创建客户", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody CrmCustomer crmCustomer)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        crmCustomer.setCustomerCode(OrderUtils.getOrderNo());
        crmCustomer.setIsDel(0);
        crmCustomer.setIsLine(1);
        crmCustomer.setCompanyId(loginUser.getCompany().getCompanyId());
        crmCustomer.setCreateUserId(loginUser.getUser().getUserId());
        crmCustomer.setDeptId(loginUser.getUser().getDeptId());
        return toAjax(crmCustomerService.insertCrmCustomer(crmCustomer));
    }

    @PreAuthorize("@ss.hasPermi('crm:customer:addMyCustomer')")
    @ApiOperation("添加我的客户")
    @PostMapping("/addMyCustomer")
    public R addMyCustomer(@RequestBody CrmCustomer crmCustomer)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        crmCustomer.setCustomerCode(OrderUtils.getOrderNo());
        crmCustomer.setIsLine(0);
        crmCustomer.setIsDel(0);
        crmCustomer.setIsReceive(0);
        crmCustomer.setStatus(1);
        crmCustomer.setDeptId(loginUser.getUser().getDeptId());
        crmCustomer.setCreateUserId(loginUser.getUser().getUserId());
        crmCustomer.setCompanyId(loginUser.getCompany().getCompanyId());
        if(crmCustomerService.insertCrmCustomer(crmCustomer)>0){
            CompanyUser companyUser=loginUser.getUser();
            CrmCustomeReceiveParam param=new CrmCustomeReceiveParam();
            String operName = companyUser.getNickName();
            param.setCompanyId(companyUser.getCompanyId());
            param.setCompanyUserId(companyUser.getUserId());
            param.setCustomerId(crmCustomer.getCustomerId());
            crmCustomerService.receive(param,operName);
            return R.ok();
        }
        else{
            return R.error();
        }
    }

    /**
     * 修改客户
     */
//    @PreAuthorize("@ss.hasPermi('crm:customer:edit')")
    @Log(title = "客户", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody CrmCustomer crmCustomer) {
        return toAjax(crmCustomerService.updateCrmCustomer(crmCustomer));
    }


    //认领
    @PreAuthorize("@ss.hasPermi('crm:customer:receive')")
    @PostMapping("/receive")
    public R receive(@RequestBody CrmCustomeReceiveParam param)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        param.setCompanyUserId(loginUser.getUser().getUserId());
        param.setDeptId(loginUser.getUser().getDeptId());
        return crmCustomerService.receive(param,operName);
    }

    //回收
    @PreAuthorize("@ss.hasPermi('crm:customer:recover')")
    @PostMapping("/recover")
    public R recover(@RequestBody CrmCustomeRecoverParam param)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        param.setCompanyUserId(loginUser.getUser().getUserId());
        return crmCustomerService.recover(param,operName);
    }

    //分配
    @PreAuthorize("@ss.hasPermi('crm:customer:assignUser')")
    @PostMapping("/assignUser")
    public R assignUser(@RequestBody CrmCustomeAssignUserParam param)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        param.setDeptId(loginUser.getUser().getDeptId());
        return crmCustomerService.assignUser(param,operName);
    }

    @PreAuthorize("@ss.hasPermi('crm:customer:importLine')")
    @PostMapping("/importLineData")
    public AjaxResult importLineData(MultipartFile file) throws Exception
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        ExcelUtil<CrmCompanyLineCustomerImportParam> util = new ExcelUtil<CrmCompanyLineCustomerImportParam>(CrmCompanyLineCustomerImportParam.class);
        List<CrmCompanyLineCustomerImportParam> list = util.importExcel(file.getInputStream());
        if(list.size()>12000){
            return new AjaxResult(500,"导入数据超出范围,最大12000条");
        }
        String operName = loginUser.getUsername();
        String message = crmCustomerService.importCompanyLineCustomer(list, operName,loginUser.getCompany().getCompanyId(),loginUser.getUser().getUserId());
        return AjaxResult.success(message);
    }

    //下载模板
    @GetMapping("/importLineTemplate")
    public AjaxResult importLineTemplate()
    {
        ExcelUtil<CrmCompanyLineCustomerImportParam> util = new ExcelUtil<CrmCompanyLineCustomerImportParam>(CrmCompanyLineCustomerImportParam.class);
        return util.importTemplateExcel("线索客户数据");
    }

    @Log(title = "导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('crm:customer:importVisit')")
    @PostMapping("/importVisitData")
    public AjaxResult importVisitData(MultipartFile file) throws Exception
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        ExcelUtil<CrmCustomerVisitImportParam> util = new ExcelUtil<CrmCustomerVisitImportParam>(CrmCustomerVisitImportParam.class);
        List<CrmCustomerVisitImportParam> list = util.importExcel(file.getInputStream());
        String message = crmCustomerService.importVisitCustomer(list,loginUser.getCompany().getCompanyId());
        return AjaxResult.success(message);
    }
    //下载模板
    @GetMapping("/importVisitTemplate")
    public AjaxResult importVisitTemplate()
    {
        ExcelUtil<CrmCustomerVisitImportParam> util = new ExcelUtil<CrmCustomerVisitImportParam>(CrmCustomerVisitImportParam.class);
        return util.importTemplateExcel("客户跟进");
    }

    @PreAuthorize("@ss.hasPermi('crm:customer:export')")
    @Log(title = "客户", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(CrmCustomerListQueryParam param)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        List<CrmCustomerExportVO> list = crmCustomerService.selectCrmCustomerExportListQuery(param);
        for(CrmCustomerExportVO customer:list){
            if(StringUtils.isNotEmpty(customer.getMobile())){
                if(loginUser.getUser().getUserType().equals("00")){
                }
                else{
                    customer.setMobile(customer.getMobile().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                }

            }
        }
        ExcelUtil<CrmCustomerExportVO> util = new ExcelUtil<CrmCustomerExportVO>(CrmCustomerExportVO.class);
        return util.exportExcel(list, "客户");
    }
    @Log(title = "客户", businessType = BusinessType.EXPORT)
    @PostMapping("/{customerIds}")
    public AjaxResult exportByIds(@PathVariable Long[] customerIds)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        List<CrmCustomerExportVO> list = crmCustomerService.selectCrmCustomerExportListByIds(customerIds);
        for(CrmCustomerExportVO customer:list){
            if(StringUtils.isNotEmpty(customer.getMobile())){
                if(loginUser.getUser().getUserType().equals("00")){
                }
                else{
                    customer.setMobile(customer.getMobile().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                }

            }
        }
        ExcelUtil<CrmCustomerExportVO> util = new ExcelUtil<CrmCustomerExportVO>(CrmCustomerExportVO.class);
        return util.exportExcel(list, "客户");
    }

    @PreAuthorize("@ss.hasPermi('crm:customer:editSource')")
    @PostMapping("/updateCustomerSource")
    public AjaxResult updateCustomerSource(@RequestBody CrmCustomerEditSourceParam param)
    {

        return toAjax(crmCustomerService.updateCrmCustomerSource(param));
    }


    @GetMapping("/getCustomerListByIds")
    public R getCustomerListByIds(@RequestParam("customerIds")String customerIds)
    {
        List<CrmCustomer> customerList=crmCustomerService.selectCrmCustomerListByIds(customerIds);
        return R.ok().put("data",customerList);
    }


    @ApiOperation("查询客户")
    @GetMapping("/getCustomerListBySearch")
    public R getCustomerListBySearch(CrmCustomerSearchParam param){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        List<CrmCustomer> list = crmCustomerService.selectCrmCustomerListBySearch(param);
        return R.ok().put("data",list);
    }

}
