package com.fs.crm.controller;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import com.fs.common.core.domain.R;
import com.fs.common.utils.OrderUtils;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.company.domain.Company;
import com.fs.company.service.ICompanyService;
import com.fs.core.security.LoginUser;
import com.fs.core.web.service.TokenService;
import com.fs.crm.param.*;
import com.fs.crm.vo.CrmCustomerListVO;
import com.fs.crm.vo.CrmCustomerExportVO;
import com.fs.store.vo.FsStoreOrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.enums.BusinessType;
import com.fs.crm.domain.CrmCustomer;
import com.fs.crm.service.ICrmCustomerService;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 客户Controller
 *
 * @author fs
 * @date 2022-12-21
 */
@RestController
@RequestMapping("/crm/customer")
public class CrmCustomerController extends BaseController
{
    @Autowired
    private ICrmCustomerService crmCustomerService;
    @Autowired
    private ICompanyService companyService;
    @Autowired
    private TokenService tokenService;
    @PreAuthorize("@ss.hasPermi('crm:customer:lineList')")
    @GetMapping("/lineList")
    public TableDataInfo line(CrmCustomer crmCustomer)
    {
        startPage();
        crmCustomer.setIsLine(1);
        List<CrmCustomerListVO> list = crmCustomerService.selectCrmCustomerListVO(crmCustomer);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('crm:customer:addLine')")
    @Log(title = "创建线索客户", businessType = BusinessType.INSERT)
    @PostMapping("/addLine")
    public AjaxResult addLine(@Validated  @RequestBody CrmCustomer crmCustomer)
    {
        crmCustomer.setCustomerCode(OrderUtils.getOrderNo());
        crmCustomer.setIsLine(1);
        crmCustomer.setIsDel(0);
        return toAjax(crmCustomerService.insertCrmCustomer(crmCustomer));
    }

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


    @PreAuthorize("@ss.hasPermi('crm:customer:queryLine')")
    @GetMapping(value = "/queryLine/{customerId}")
    public AjaxResult getLineInfo(@PathVariable("customerId") Long customerId)
    {
        return AjaxResult.success(crmCustomerService.selectCrmCustomerById(customerId));
    }



    @PreAuthorize("@ss.hasPermi('crm:customer:removeLine')")
    @Log(title = "客户", businessType = BusinessType.DELETE)
    @DeleteMapping("/removeLine/{customerIds}")
    public AjaxResult removeLine(@PathVariable Long[] customerIds)
    {
        return toAjax(crmCustomerService.deleteCrmCustomerByIds(customerIds));
    }

    /**
     * 导出客户列表
     */
    @PreAuthorize("@ss.hasPermi('crm:customer:exportLine')")
    @Log(title = "客户", businessType = BusinessType.EXPORT)
    @GetMapping("/exportLine")
    public AjaxResult exportLine(CrmCustomer crmCustomer)
    {
        crmCustomer.setIsLine(1);
        List<CrmCustomerListVO> list = crmCustomerService.selectCrmCustomerListVO(crmCustomer);
        List<CrmCustomerExportVO> exportList=new ArrayList<>();
        for(CrmCustomerListVO customer:list){
            CrmCustomerExportVO vo=new CrmCustomerExportVO();
            vo.setSource(customer.getSource().toString());
            BeanUtils.copyProperties(customer,vo);
            exportList.add(vo);
        }
        ExcelUtil<CrmCustomerExportVO> util = new ExcelUtil<CrmCustomerExportVO>(CrmCustomerExportVO.class);
        return util.exportExcel(exportList, "线索客户");
    }


    @Log(title = "导入线索客户", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('crm:customer:importLine')")
    @PostMapping("/importLineData")
    public AjaxResult importLineData(MultipartFile file) throws Exception
    {
        ExcelUtil<CrmLineCustomerImportParam> util = new ExcelUtil<CrmLineCustomerImportParam>(CrmLineCustomerImportParam.class);
        List<CrmLineCustomerImportParam> list = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = crmCustomerService.importLineCustomer(list, operName);
        return AjaxResult.success(message);
    }

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


    @PreAuthorize("@ss.hasPermi('crm:customer:export')")
    @Log(title = "客户", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(CrmCustomer crmCustomer)
    {
        crmCustomer.setIsLine(0);
        List<CrmCustomerListVO> list = crmCustomerService.selectCrmCustomerListVO(crmCustomer);
        List<CrmCustomerExportVO> exportList=new ArrayList<>();
        for(CrmCustomerListVO customer:list){
            CrmCustomerExportVO vo=new CrmCustomerExportVO();
            if(customer.getSource()!=null){
                vo.setSource(customer.getSource().toString());
            }
            BeanUtils.copyProperties(customer,vo);
            if(customer.getMobile()!=null){
                vo.setMobile(customer.getMobile().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
            }
            exportList.add(vo);
        }
        ExcelUtil<CrmCustomerExportVO> util = new ExcelUtil<CrmCustomerExportVO>(CrmCustomerExportVO.class);
        return util.exportExcel(exportList, "客户");
    }

    //分配客户
    @PreAuthorize("@ss.hasPermi('crm:customer:assign')")
    @PostMapping("/assign")
    public R assign(@RequestBody CrmCustomeAssignCompanyParam crmCustomer) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        return crmCustomerService.assignCompany(crmCustomer,loginUser.getUsername(),loginUser.getUser().getUserId());
    }

    //批量分配客户给公司
    @PreAuthorize("@ss.hasPermi('crm:customer:assign')")
    @PostMapping("/assignCrmToCompany")
    public R assignCrmToCompany(@RequestBody CrmCompanyAssignParam crmCustomer) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        return crmCustomerService.assignCompanys(crmCustomer,loginUser.getUsername(),loginUser.getUser().getUserId());
    }



    @PreAuthorize("@ss.hasPermi('crm:customer:list')")
    @GetMapping("/list")
    public TableDataInfo list(CrmCustomerListQueryParam crmCustomer)
    {
        startPage();
        if(!StringUtils.isEmpty(crmCustomer.getReceiveTimeRange())){
            crmCustomer.setReceiveTimeList(crmCustomer.getReceiveTimeRange().split("--"));
        }
        List<CrmCustomerListVO> list = crmCustomerService.selectCrmCustomerListQueryParam(crmCustomer);
        //List<CrmCustomerListVO> list=crmCustomerService.selectCrmCustomer1();
        if (list != null) {
            for (CrmCustomerListVO vo : list) {
                if(vo.getMobile()!=null){
                    //vo.setMobile(vo.getMobile().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
                }
            }
        }
        return getDataTable(list);
    }


    @PreAuthorize("@ss.hasPermi('crm:customer:query')")
    @GetMapping(value = "/query/{customerId}")
    public R getInfo(@PathVariable("customerId") Long customerId)
    {
        CrmCustomer customer=crmCustomerService.selectCrmCustomerById(customerId);
        Company company=companyService.selectCompanyById(customer.getCompanyId());
        return R.ok().put("customer",customer).put("company",company);
    }

    @PreAuthorize("@ss.hasPermi('crm:customer:query1')")
    @GetMapping(value = "/query1/{customerId}")
    public R getInfo2(@PathVariable("customerId") Long customerId)
    {
        CrmCustomer customer=crmCustomerService.selectCrmCustomerById(customerId);
        if (customer.getMobile()!=null){
            customer.setMobile(customer.getMobile().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
        }
        Company company=companyService.selectCompanyById(customer.getCompanyId());
        return R.ok().put("customer",customer).put("company",company);
    }

    @PreAuthorize("@ss.hasPermi('crm:customer:query2')")
    @GetMapping(value = "/query2/{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:add')")
    @Log(title = "创建客户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody CrmCustomer crmCustomer)
    {
        crmCustomer.setCustomerCode(OrderUtils.getOrderNo());
        crmCustomer.setIsLine(1);
        crmCustomer.setIsDel(0);
        return toAjax(crmCustomerService.insertCrmCustomer(crmCustomer));
    }

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


    @PreAuthorize("@ss.hasPermi('crm:customer:remove')")
    @Log(title = "客户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{customerIds}")
    public AjaxResult remove(@PathVariable Long[] customerIds)
    {
        return toAjax(crmCustomerService.deleteCrmCustomerByIds(customerIds));
    }

    @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);
    }


}
