package com.fs.qw.controller;

import com.alibaba.fastjson.JSON;
import com.fs.common.annotation.Log;
import com.fs.common.annotation.RepeatSubmit;
import com.fs.common.core.domain.R;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.model.LoginUser;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.ServletUtils;
import com.fs.company.domain.Company;
import com.fs.company.domain.CompanyUser;
import com.fs.company.mapper.CompanyUserMapper;
import com.fs.company.service.ICompanyUserService;
import com.fs.qw.domain.QwExternalContact;
import com.fs.qw.domain.QwExternalContactTransferCompanyAudit;
import com.fs.qw.domain.QwUser;
import com.fs.qw.mapper.QwCompanyMapper;
import com.fs.qw.mapper.QwExternalContactMapper;
import com.fs.qw.param.QwFsUserParam;
import com.fs.qw.param.QwUserBingParam;
import com.fs.qw.param.QwUserListParam;
import com.fs.qw.service.IQwDeptService;
import com.fs.qw.service.IQwExternalContactTransferCompanyAuditService;
import com.fs.qw.service.IQwUserService;
import com.fs.qw.vo.QwOptionsVO;
import com.fs.qw.vo.QwUserVO;
import com.fs.qwApi.domain.QwExternalContactAllListResult;
import com.fs.qwApi.domain.inner.ExternalContact;
import com.fs.qwApi.domain.inner.ExternalContactInfo;
import com.fs.qwApi.domain.inner.FollowInfo;
import com.fs.qwApi.param.QwExternalListParam;
import com.fs.qwApi.service.QwApiService;
import com.fs.voice.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 企微用户Controller
 *
 * @author fs
 * @date 2024-06-20
 */
@RestController
@RequestMapping("/qw/user")
public class QwUserController extends BaseController {
    @Autowired
    private IQwUserService qwUserService;

    @Autowired
    private IQwExternalContactTransferCompanyAuditService auditService;

    @Autowired
    private ICompanyUserService companyUserService;

    @Autowired
    private CompanyUserMapper companyUserMapper;

    @Autowired
    private QwApiService qwApiService;

    @Autowired
    private QwCompanyMapper qwCompanyMapper;

    @Autowired
    private IQwDeptService qwDeptService;

    @Autowired
    private QwExternalContactMapper qwExternalContactMapper;

    @GetMapping("/getQwUserAll")
    public AjaxResult getQwUserAll(){
        return AjaxResult.success(qwUserService.getQwUserAll());
    }

    /**
     * 获取企微信息
     * **/
    @GetMapping("/getQwUserInfo")
    public R getQwUserInfo(QwFsUserParam param){
        return R.ok().put("data",qwUserService.getQwUserInfo(param));
    }

   @GetMapping("/getMyQwCompanyList")
    public R getMyQwCompanyList()
    {
        List<QwOptionsVO> list = qwUserService.selectQwCompanyListOptionsVOAll();
        return  R.ok().put("data",list);
    }

    /**
     * 绑定企微用户
     */
    @PreAuthorize("@ss.hasPermi('qw:user:bind')")
    @Log(title = "企微用户", businessType = BusinessType.UPDATE)
    @PutMapping("/bindQwUser")
    @RepeatSubmit
    public R bindQwUser(@RequestBody QwUserBingParam qwUserParam)
    {
        CompanyUser companyUser = companyUserService.selectCompanyUserById(qwUserParam.getCompanyUserId());

        String qwUserIdCompanyStr = companyUser.getQwUserId();
        Set<String> qwUserIdCompanySet = new HashSet<>();
        if (!StringUtil.strIsNullOrEmpty(qwUserIdCompanyStr)) {
            String[] qwUserId = qwUserIdCompanyStr.split(",");
            qwUserIdCompanySet = Arrays.stream(qwUserId)
                    .filter(id -> !id.isEmpty())
                    .collect(Collectors.toSet());
        }

        if (companyUser!=null){

            //选择的企业微信账号为“”
            if (StringUtil.strIsNullOrEmpty(qwUserParam.getId())&&qwUserParam.getCompanyUserId()!=null){
                //制空企业微信的绑定
                qwUserService.updateUserByUserId(qwUserParam.getCompanyUserId());

                //制空销售的绑定
                companyUserMapper.updateCompanyUserByNullQwUserID(companyUser.getUserId());

            }else {
                String idParam = qwUserParam.getId();
                String[] splitParam = idParam.split(",");
                Set<String> splitParamSet = Arrays.stream(splitParam)
                        .filter(s -> !s.isEmpty())
                        .collect(Collectors.toSet());

                // 找出在 qwUserIdCompanySet 中存在但在 splitParamSet 中不存在的元素
                Set<String> difference = new HashSet<>(qwUserIdCompanySet);
                difference.removeAll(splitParamSet);

                //制空绑定
                if (!difference.isEmpty()){
                    difference.forEach(id->{
                        qwUserService.updateUnBindUserById(id);
                    });

                }


                for (String paramId : splitParamSet) {
                    QwUser qu= qwUserService.selectQwUserById(Long.parseLong(paramId));
                    if (qu.getCompanyUserId()!=null&&!qu.getCompanyUserId().equals(qwUserParam.getCompanyUserId())){
                        return R.error( qu.getQwUserName()+"已经被其他人绑定，请先解绑");
                    }


                    CompanyUser user = new CompanyUser();
                    user.setQwUserId(qwUserParam.getId());
                    user.setUserId(companyUser.getUserId());
                    user.setQwStatus(1);
                    companyUserMapper.updateCompanyUser(user);



                    qu.setCompanyUserId(qwUserParam.getCompanyUserId());
                    qu.setStatus(1);
                    qu.setCompanyId(companyUser.getCompanyId());
                    qwUserService.updateQwUser(qu);

                }

                //同步最后单独跑/先不异步了pp
                for (String paramId : splitParamSet){

                    //如果销售没绑定过，全刷,否则只同步新的增加的
                    if (StringUtil.strIsNullOrEmpty(qwUserIdCompanyStr)){
                        updateAndSyncQwUser(paramId, companyUser);

                    }
                    else if (!StringUtil.strIsNullOrEmpty(qwUserIdCompanyStr) && !qwUserIdCompanySet.contains(paramId)){
                        updateAndSyncQwUser(paramId, companyUser);
                    }
                }
            }


            return R.ok();
        }
        return R.error("绑定失败");

    }


    private void updateAndSyncQwUser(String paramId, CompanyUser companyUser) {

        QwUser qu= qwUserService.selectQwUserById(Long.parseLong(paramId));

        qwExternalContactMapper.updateBindUserByQwUser(qu.getCorpId(),qu.getQwUserId(),companyUser.getCompanyId(),companyUser.getUserId());

        //根据企微账号和公司id 同步企业微信账号(游标初始为空)
        syncMyQwExternalContact(qu,null);
    }

    public R  syncMyQwExternalContact(QwUser qwUser,String getNextCursor )  {

        String qwUserId = qwUser.getQwUserId();
        String corpId = qwUser.getCorpId();
        Long companyId = qwUser.getCompanyId();

        QwExternalListParam param = new QwExternalListParam();
        param.setLimit(100);
        param.setUserid_list(Arrays.asList(qwUserId));
        param.setCursor(getNextCursor);

        QwExternalContactAllListResult list = qwApiService.getAllExternalcontactList(param, corpId);

        logger.info("批量获取客户详情" + list);

        if (list.getErrcode() == 0) {
            List<ExternalContactInfo> externalContactList = list.getExternal_contact_list();
            for (ExternalContactInfo externalContactInfo : externalContactList) {

                ExternalContact externalContact = externalContactInfo.getExternal_contact();
                FollowInfo followInfo = externalContactInfo.getFollow_info();
                QwExternalContact qwExternalContact = qwExternalContactMapper.selectQwExternalContactUserIdAndExternalIdAndCompanyId(externalContact.getExternal_userid(), qwUserId, corpId);
                logger.info("客户详情" + qwExternalContact);

                if (qwExternalContact == null) {
                    qwExternalContact = new QwExternalContact();
                    qwExternalContact.setUserId(qwUserId); // 设置属于用户ID
                    qwExternalContact.setExternalUserId(externalContact.getExternal_userid()); // 设置外部联系人ID


                    qwExternalContact.setCorpId(corpId); // 设置企业ID
                    qwExternalContact.setCompanyId(companyId); // 设置公司ID
                }


                // 设置公共属性
                qwExternalContact.setCompanyUserId(qwUser.getCompanyUserId());
                qwExternalContact.setQwUserId(qwUser.getId());
                qwExternalContact.setName(externalContact.getName()); // 设置名称
                qwExternalContact.setAvatar(externalContact.getAvatar()); // 设置头像
                qwExternalContact.setType(externalContact.getType()); // 设置外部联系人类型(1微信用户，2企业微信用户)
                qwExternalContact.setGender(externalContact.getGender()); // 设置性别 (0-未知, 1-男性, 2-女性)
                qwExternalContact.setDescription(followInfo.getDescription()); // 设置描述信息
                qwExternalContact.setRemark(followInfo.getRemark());

//                        if (followInfo.getTag_id() != null && !followInfo.getTag_id().isEmpty()) {
                qwExternalContact.setTagIds(JSON.toJSONString(followInfo.getTag_id())); // 设置标签ID
//                        }

//                        if (followInfo.getRemark_mobiles() != null && !followInfo.getRemark_mobiles().isEmpty()) {
                qwExternalContact.setRemarkMobiles(JSON.toJSONString(followInfo.getRemark_mobiles())); // 设置备注电话号码
//                        }

                qwExternalContact.setState(followInfo.getState());

                if (followInfo.getState() != null && !followInfo.getState().isEmpty()) {
                    String s = "way:" + corpId + ":";
                    if (followInfo.getState().contains(s)) {
                        String wayId = followInfo.getState().substring(followInfo.getState().indexOf(s) + s.length());
                        qwExternalContact.setWayId(Long.parseLong(wayId));
                    }
                }

                qwExternalContact.setRemarkCorpName(followInfo.getRemark_corp_name()); // 设置备注企业名称
                qwExternalContact.setAddWay(followInfo.getAdd_way()); // 设置来源
                qwExternalContact.setOperUserid(followInfo.getOper_userid()); // 设置oper用户ID

                // 根据是否存在记录进行更新或插入
                if (qwExternalContact.getId() != null) {
                    qwExternalContactMapper.updateQwExternalContact(qwExternalContact);
                } else {
                    qwExternalContactMapper.insertQwExternalContact(qwExternalContact);
                }
            }

        }else {
            return R.error("同步失败："+list.getErrmsg());
        }

        if (!StringUtil.strIsNullOrEmpty(list.getNext_cursor())){
            syncMyQwExternalContact(qwUser,list.getNext_cursor());
        }
        return R.ok();
    }


    /**
     * 同步企微用户
     */
    @RepeatSubmit
    @PreAuthorize("@ss.hasPermi('qw:user:sync')")
    @Log(title = "企微用户", businessType = BusinessType.INSERT)
    @PostMapping("sync/{corpId}")
    public R sync(@PathVariable("corpId") String corpId)
    {

        List<String> strings = qwCompanyMapper.selectQwCompanyCorpIdListByAll();
        for (String string : strings) {

            if (string.equals(corpId)){
                qwUserService.syncQwUser(string);
                qwDeptService.insertOrUpdateQwDept(string);
                logger.info("同步完成");
            }
        }
        return R.ok();
    }

    /**
     * 获取企微用户详细信息
     */

    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(qwUserService.selectQwUserVOById(id));
    }
    /**
     * 批量查询 企微用户详细信息
     */
    @GetMapping(value = "/getInfo/{ids}")
    public AjaxResult getInfoByIds(@PathVariable("ids") Long[] ids)
    {
        return AjaxResult.success(qwUserService.selectQwUserVOByIds(ids));
    }

    @RepeatSubmit
    @PreAuthorize("@ss.hasPermi('qw:user:sync')")
    @Log(title = "同步企微用户名称", businessType = BusinessType.INSERT)
    @PostMapping("syncName/{corpId}")
    public R syncName(@PathVariable("corpId") String corpId)
    {
        List<String> strings = qwCompanyMapper.selectQwCompanyCorpIdListByAll();
        for (String string : strings) {
            if (string.equals(corpId)){
                qwUserService.syncQwUserName(string);
            }
        }
        return R.ok();
    }


    /**
     * 查询企微用户列表
     */

    @GetMapping("/userList")
    public TableDataInfo userList(QwUserListParam qwUser)
    {
        startPage();
        List<QwUserVO> list = qwUserService.selectAllQwUserListVO(qwUser);
        return getDataTable(list);
    }
}
