package com.fs.qw;

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.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.course.param.FsUserCourseListUParam;
import com.fs.course.service.IFsUserCourseStudyService;
import com.fs.course.vo.FsUserCourseStudyListUVO;
import com.fs.crm.param.CrmMyCustomerListQueryParam;
import com.fs.crm.service.ICrmCustomerService;
import com.fs.crm.vo.CrmMyCustomerListQueryVO;
import com.fs.core.security.LoginUser;
import com.fs.core.web.service.TokenService;
import com.fs.qw.dto.GetQwRepeatDataDTO;
import com.fs.qw.vo.GetQwRepeatDataVO;
import com.fs.store.service.IFsUserService;
import com.fs.qw.domain.QwExternalContact;
import com.fs.qw.param.*;
import com.fs.qw.service.IQwExternalContactInfoService;
import com.fs.qw.service.IQwExternalContactService;
import com.fs.qw.vo.QwExternalContactVO;
import com.fs.qw.vo.QwFsUserVO;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.ApiOperation;
import org.codehaus.jettison.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;


/**
 * 企业微信客户Controller
 *
 * @author fs
 * @date 2024-06-20
 */
@RestController
@RequestMapping("/qw/externalContact")
public class QwExternalContactController extends BaseController
{
    @Autowired
    private IQwExternalContactService qwExternalContactService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IFsUserService fsUserService;
    @Autowired
    private IFsUserCourseStudyService courseStudyService;
    @Autowired
    private ICrmCustomerService crmCustomerService;

    @Autowired
    private IQwExternalContactInfoService qwExternalContactInfoService;
    /**
     * 查询企业微信客户列表
     */


    @PreAuthorize("@ss.hasPermi('qw:externalContact:list')")
    @GetMapping("/list")
    public TableDataInfo list(QwExternalContactParam qwExternalContact)
    {
        startPage();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        qwExternalContact.setCompanyId(loginUser.getCompany().getCompanyId());
        List<QwExternalContactVO> list = qwExternalContactService.selectQwExternalContactListVO(qwExternalContact);
        return getDataTable(list);
    }

    /**
     * 企微获取重粉数据
     */
    @PostMapping("/qwRepeatData")
    public R getQwRepeatData(@RequestBody GetQwRepeatDataDTO dto){
        List<GetQwRepeatDataVO> qwRepeatData = qwExternalContactService.getQwRepeatData(dto);
        return R.ok().put("data",qwRepeatData);
    }
    /**
     * 同步企业微信客户
     */
    @PreAuthorize("@ss.hasPermi('qw:externalContact:add')")
    @Log(title = "同步企业微信客户", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@RequestBody QwExternalContact qwExternalContact) throws IOException {

        return qwExternalContactService.syncQwExternalContact(qwExternalContact.getCorpId());
    }

    @PreAuthorize("@ss.hasPermi('qw:externalContact:myList')")
    @GetMapping("/myList")
    public TableDataInfo myList(QwExternalContactParam qwExternalContact)
    {
        if(qwExternalContact.getQwUserId()==null){
            return null;
        }
        startPage();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        qwExternalContact.setCompanyId(loginUser.getCompany().getCompanyId());
        List<QwExternalContactVO> list = qwExternalContactService.selectQwExternalContactListVO(qwExternalContact);
        return getDataTable(list);
    }

    @Log(title = "同步我的企业微信客户", businessType = BusinessType.INSERT)
    @GetMapping("/syncMyExternalContact/{id}")
    public R  syncMyExternalContact(@PathVariable("id") Long id ) throws IOException {
        return qwExternalContactService.syncMyQwExternalContact(id);
    }

    @Log(title = "新客同步", businessType = BusinessType.INSERT)
    @GetMapping("/syncAddMyExternalContact/{id}")
    public R  syncAddMyExternalContact(@PathVariable("id") Long id ) throws IOException {
        return qwExternalContactService.syncAddMyQwExternalContact(id);
    }

    /**
     * 导出企业微信客户列表
     */
    @PreAuthorize("@ss.hasPermi('qw:externalContact:export')")
    @Log(title = "企业微信客户", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(QwExternalContactParam qwExternalContact)
    {
        if (qwExternalContact.getQwUserId()==null){
            return AjaxResult.success();
        }
        List<QwExternalContactVO> list = qwExternalContactService.selectQwExternalContactListVO(qwExternalContact);
        ExcelUtil<QwExternalContactVO> util = new ExcelUtil<QwExternalContactVO>(QwExternalContactVO.class);
        return util.exportExcel(list, "企业微信客户数据");
    }

    /** 统计预期发送消息人员的客户总数 */
    @PostMapping("/expectQwGroupMsgCountCustomer")
    public R expectQwGroupMsgCountCustomer(@RequestBody QwCountCustomerParam userIdList){


        return qwExternalContactService.expectQwGroupMsgCountCustomer(userIdList);
    }

    /**
     * 获取企业微信客户详细信息
     */
//    @PreAuthorize("@ss.hasPermi('qw:externalContact:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(qwExternalContactService.selectQwExternalContactById(id));
    }

    @GetMapping(value = "getUserInfo/{id}")
    public R getUserInfo(@PathVariable("id") Long id)
    {
        return R.ok().put("data",qwExternalContactInfoService.selectQwExternalContactInfoByExternalContactId(id));
    }



    @PreAuthorize("@ss.hasPermi('qw:externalContact:addUnassigned')")
    @Log(title = "同步待转接", businessType = BusinessType.INSERT)
    @PostMapping("/addUnassigned")
    public R addUnassigned(@RequestBody QwExternalContact qwExternalContact)
    {
        return qwExternalContactService.syncQwExternalContactUnassigned(qwExternalContact.getCorpId());
    }

    @PreAuthorize("@ss.hasPermi('qw:externalContact:addTag')")
    @Log(title = "添加标签", businessType = BusinessType.INSERT)
    @PostMapping("/addTag")
    public R addTag(@RequestBody QwExternalContactAddTagParam Param) throws JSONException {

        return qwExternalContactService.addUserTag(Param);
    }
    @PreAuthorize("@ss.hasPermi('qw:externalContact:delTag')")
    @Log(title = "移除标签", businessType = BusinessType.INSERT)
    @PostMapping("/delTag")
    public R delTag(@RequestBody QwExternalContactAddTagParam Param)
    {

        return qwExternalContactService.delUserTag(Param);
    }

    @PreAuthorize("@ss.hasPermi('qw:externalContact:transfer')")
    @Log(title = "企业微信客户", businessType = BusinessType.UPDATE)
    @PutMapping("/resignedTransfer")
    public R resignedTransfer(@RequestBody ResignedTransferParam param)
    {


        return qwExternalContactService.resignedTransfer(param);
    }

    /**
    * 在职转接 分配客户
    */
    @PreAuthorize("@ss.hasPermi('qw:externalContact:transfer')")
    @Log(title = "企业微信客户", businessType = BusinessType.UPDATE)
    @PutMapping("/transfer")
    public R transfer(@RequestBody TransferParam param)
    {

        return qwExternalContactService.transfer(param);
    }
    /**
     * 修改企业微信客户
     */
    @PreAuthorize("@ss.hasPermi('qw:externalContact:edit')")
    @Log(title = "企业微信客户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody QwExternalContact qwExternalContact)
    {

        return toAjax(qwExternalContactService.updateQwExternalContact(qwExternalContact));
    }

    @PreAuthorize("@ss.hasPermi('qw:externalContact:edit')")
    @Log(title = "企业微信客户", businessType = BusinessType.UPDATE)
    @PutMapping("/editStatus")
    public AjaxResult editStatus(@RequestBody QwExternalContact qwExternalContact)
    {

        return toAjax(qwExternalContactService.updateQwExternalContactStatus(qwExternalContact));
    }

    /**
     *  企业微信客户与企业客户绑定
     */
    @PutMapping("/editbindCustomer")
    public AjaxResult editbindCustomer(@RequestBody QwExternalContact qwExternalContact)
    {

        return toAjax(qwExternalContactService.updateQwExternalContactBindCustomer(qwExternalContact));
    }

    /**
    * 绑定小程序用户
    */
    @PutMapping("/bindUserId")
    public R bindUserId(@RequestBody QwExternalContact qwExternalContact)
    {
        return qwExternalContactService.updateQwExternalContactBindUserId(qwExternalContact);
    }

    /**
     * 解除绑定小程序用户
     */
    @PreAuthorize("@ss.hasPermi('qw:externalContact:unBindUserId')")
    @Log(title = "解除绑定小程序用户", businessType = BusinessType.UPDATE)
    @GetMapping("/unBindUserId/{id}")
    public R unBindUserId(@PathVariable("id") Long id)
    {
        return qwExternalContactService.updateQwExternalContactUnBindUserId(id);
    }
    /**
     * 删除企业微信客户
     */
    @PreAuthorize("@ss.hasPermi('qw:externalContact:remove')")
    @Log(title = "企业微信客户", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(qwExternalContactService.deleteQwExternalContactByIds(ids));
    }



    @ApiOperation("获取我的客户列表")
    @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());
        param.setCorpId(param.getCorpId());
        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);

    }

    /**
     * 获取小程序的客户
     */
    @GetMapping("/getMiniCustomer")
    public  TableDataInfo getMiniCustomer(QwFsUserParam qwFsUserParam){
        startPage();
        List<QwFsUserVO> list = fsUserService.selectQwFsUserListVO(qwFsUserParam);
        if (list==null||list.size()==0){
            list = fsUserService.selectQwFsUserListVO(qwFsUserParam);
        }
//        if (list != null) {
//            for (QwFsUserVO vo : list) {
//                if(vo.getPhone()!=null){
//                    vo.setPhone(decryptAutoPhoneMk(vo.getPhone()));
//                }
//            }
//        }
        return getDataTable(list);
    }

    /**
    * 获取CRM在学课程记录
    */
    @GetMapping("/getCourseStudyList")
    public TableDataInfo getMyCourseList(FsUserCourseListUParam param)
    {

        startPage();
        List<FsUserCourseStudyListUVO> list= courseStudyService.selectFsUserCourseStudyListUVO(param);
        return getDataTable(list);
    }

    /**
     * 设置客户-课节SOP
     */
    @PostMapping("/setCustomerCourseSop")
    public R setCustomerCourseSop(@RequestBody QwFsCustomerCourseSopParam param){

//        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
//        Long companyId = loginUser.getCompany().getCompanyId();
//        param.setCompanyId(companyId);
        return   qwExternalContactService.setCustomerCourseSop(param);
    }

    /**
    * 查询是否已经设置过客户-某个课节的SOP
    */
    @GetMapping("/getCustomerCourseSop")
    public Boolean getCustomerCourseSop(QwFsCustomerCourseSopGetParam param){
//
//        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
//        Long companyId = loginUser.getCompany().getCompanyId();
//        param.setCompanyId(companyId);

        return   qwExternalContactService.getCustomerCourseSop(param);
    }

    /**
    * 批量设置客户-课节SOP
    */
    @PostMapping("/setCustomerCourseSopList")
    public R setCustomerCourseSopList(@RequestBody QwFsCustomerCourseSopListParam param){

//        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
//        Long companyId = loginUser.getCompany().getCompanyId();
//        param.setCompanyId(companyId);

        return  qwExternalContactService.setCustomerCourseSopList(param);
    }

}
