import base64 from '@/utils/base64.js'
import store from '../store'

import { sendSock } from '@/websocket/websocket'
import { generateTaskId } from '@/utils/common'

/**
 * 备(手机客户端、客服客户端)获取通信token请求
 * @param {String} userName 用户名
 * @param {String} password 密码
 * @returns DeviceAuthRsp
 */
export function deviceAuthReq(userName, password) {
  const msg = {
    Id: 1010, // 非必须
    AccessToken: '', // 非必须
    MsgType: 'DeviceAuthReq',
    Content: {
      AuthType: 2,
      Credential: base64.encode(userName + ':' + password)
    }
  }
  sendSock(msg)
}

/**
 * 向服务端发心跳
 * @param {String} token token
 */
export function heartBeatReq(token) {
  const msg = {
    Id: 1001,
    MsgType: 'HeartBeatReq',
    AccessToken: token,
    Content: {}
  }
  console.log('发送心跳', new Date().toLocaleString())
  sendSock(msg)
}

/**
 * 触发手机推送会话列表任务
 * @param {String} WxId 微信id
 * @returns ConversationPushNotice
 */
export function TriggerConversationPushTask(WxId) {
  if (!WxId) return
  const msg = {
    Id: 1232,
    MsgType: 'TriggerConversationPushTask',
    Content: { WxId: WxId }
  }
  sendSock(msg)
}

/**
 * 获取微信的二维码
 * @param {Number} wxid 微信id
 * @returns PullMyQrCodeTaskResultNotice
 */
export function PullMyQrCodeTask(wxid) {
  let msg = {
    Id: 1216,
    AccessToken: '',
    MsgType: 'PullMyQrCodeTask',
    Content: {
      WxId: wxid
    }
  }
  sendSock(msg)
}

/**
 * 触发手机推送微信好友列表任务
 * @param {String} wxid
 * @returns WxFriendPushNotice
 */
export function triggerWechatFriendPushTask(wxid) {
  let msg = {
    Id: 1204,
    AccessToken: '',
    MsgType: 'TriggerWechatFriendPushTask',
    Content: {
      WxId: wxid
    }
  }
  sendSock(msg)
}

/**
 * 添加客户-通过手机号搜索添加微信
 * @param {Number} wxid 微信号
 * @param {String} keyword 搜索关键字
 * @param {String} msg 招呼语, 缺省：我是xxx公司的xxx，添加我的企业微信与我联系吧。
 * @param {String} memo 备注
 * @param {String} labels 标签
 * @returns TaskResultNotice
 */
export function AddCustomerFromSearchTask(wxid, keyword, hiMsg, memo, labels, userId) {
  const content = {
    WxId: wxid,
    Key: keyword,
    Msg: hiMsg,
    Memo: memo,
    Labels: labels,
    TaskId: generateTaskId()
  }
  const msg = {
    Id: 1215,
    AccessToken: '',
    MsgType: 'AddCustomerFromSearchTask',
    Content: content
  }
  sendSock(msg)

  // 任务保存到nedb
  let doc = {}
  for (const key in content) {
    if (content.hasOwnProperty(key)) {
      doc[key] = content[key]
    }
  }
  doc.userId = userId
  doc.result = '指令已发出'
  store.dispatch('tools/UpdateAddCustomerFromSearchTask', doc)
}

/**
 * 添加客户-从微信好友中添加
 * @param {Number} wxid
 * @param {Number} count 添加的个数
 * @param {Number} startIndex 添加的起始位置
 * @param {String} hiMsg 招呼语，缺省：你好这是我的企业微信，以后也可以在这里与我联系。
 * @returns TaskResultNotice
 */
export function addCustomerFromWxTask(wxid, count, startIndex, hiMsg) {
  let content = {
    WxId: wxid,
    Count: count,
    Index: startIndex,
    Msg: hiMsg,
    TaskId: generateTaskId()
  }
  let msg = { Id: 1214, AccessToken: '', MsgType: 'AddCustomerFromWxTask', Content: content }
  sendSock(msg)
}

/**
 * 通过微信好友的wxid添加客户
 * @param {Number} wxid 微信id
 * @param {String} Ids 微信好友OpenId列表
 * @param {String} hiMsg 招呼语，缺省：你好这是我的企业微信，以后也可以在这里与我联系。
 */
export function addCustomerByIdTask(wxid, Ids, hiMsg) {
  let msg = {
    Id: 1215,
    AccessToken: '',
    MsgType: 'AddCustomerByIdTask',
    Content: {
      WxId: wxid,
      Ids: Ids,
      Msg: hiMsg,
      TaskId: generateTaskId()
    }
  }
  sendSock(msg)
}

/**
 * 通知手机推送聊天记录
 * @param {Number} wxid 微信id
 * @param {Number} convid 会话RemoteId
 * @param {Number} refMsgId 起使消息的MsgRemoteId
 * @param {Number} flag 备用
 * @returns HistoryMsgPushNotice
 */
export function triggerHistoryMsgPushTask(wxid, convId, refMsgId = 0, flag = 0) {
  let msg = {
    Id: 1205,
    AccessToken: '',
    MsgType: 'TriggerHistoryMsgPushTask',
    Content: {
      WxId: wxid,
      ConvId: convId,
      RefMsgId: refMsgId,
      Flag: flag
    }
  }
  sendSock(msg)
}

/**
 * 通过消息Id下载文件（图片，视频） 返回 DownloadFileResultNotice
 * @param {Number} wxid
 * @param {Number} msgId
 * @param {Number} msgRemotedId
 * @param {Number} fileType 下载文件的类型 0 原始文件（原图，视频，音频，文件）
 */
export function downloadFileByMsgIdTask(wxid, msgId, msgRemotedId, fileType) {
  let msg = {
    Id: 1212,
    AccessToken: '',
    MsgType: 'DownloadFileByMsgIdTask',
    Content: {
      WxId: wxid,
      MsgId: msgId,
      MsgRemoteId: msgRemotedId,
      FileType: fileType,
      TaskId: generateTaskId()
    }
  }
  sendSock(msg)
}

/**
 * 发朋友圈
 * @param {Object} circle 朋友圈数据
 */
export function postSnsTask(circle) {
  const content = {
    WxId: circle.WxId, // 设备企业WX号
    Content: circle.Content, //发布的文案
    // Media: circle.Media, //携带的图片、视频、链接等资源
    // Visible: circle.Visible, // 可见范围
    TaskId: generateTaskId() //任务id 在TaskResult中回传
    // Comment : 4, // 评论 TODO: 暂未实现
    //  Poi : 7 // 地理信息 TODO: 暂未实现
  }
  if (circle.Visible) {
    content.Visible = circle.Visible
  }
  if (circle.Media) {
    content.Media = circle.Media
  }
  const msg = {
    Id: 1220,
    AccessToken: '',
    MsgType: 'PostSnsTask',
    Content: content
  }
  sendSock(msg)
}

/**
 * 获取我的朋友圈列表
 * @param {Number} wxid 微信id
 * @param {Number} seq 起始位置上一条朋友圈的序列号，第一次拉取为-1
 */
export function pullMySnsListTask(wxid, seq = -1) {
  const content = {
    WxId: wxid,
    Seq: seq
  }
  const msg = {
    Id: 1218,
    AccessToken: '',
    MsgType: 'PullMySnsListTask',
    Content: content
  }
  sendSock(msg)
}

/**
 * 获取一条朋友圈内容 返回 GetSnsDataTaskResultNotice
 * @param {Number} wxId 设备企业WX号
 * @param {Number} snsId 朋友圈id
 * @param {String} postId 朋友圈postid
 * @param {Number} taskId 任务id 在TaskResult中回传
 */
export function getSnsDataTask(wxId, snsId, postId, taskId) {
  const content = {
    WxId: wxId,
    SnsId: snsId,
    PostId: postId,
    TaskId: taskId
  }
  const msg = {
    Id: 1226,
    AccessToken: '',
    MsgType: 'GetSnsDataTask',
    Content: content
  }
  sendSock(msg)
}

/**
 * 删除朋友圈
 * @param {Number} wxid 设备企业WX号
 * @param {Number} snsId 朋友圈id
 * @param {Number} postId 朋友圈postid
 * @param {Number} taskId 任务id 在TaskResult中回传
 */
export function delSnsTask(wxid, snsId, postId, taskId) {
  let msg = {
    Id: 1224,
    AccessToken: '',
    MsgType: 'DelSnsTask',
    Content: {
      WxId: wxid,
      SnsId: snsId,
      PostId: postId,
      TaskId: taskId
    }
  }
  sendSock(msg)
}

/**
 * 朋友圈点赞
 * @param {Number} wxid 设备企业WX号
 * @param {Number} snsId 朋友圈id
 * @param {Number} postId 朋友圈postid
 * @param {Number} taskId 任务id 在TaskResult中回传
 */
export function snsLikeTask(wxid, snsId, postId, taskId) {
  let msg = {
    Id: 1222,
    AccessToken: '',
    MsgType: 'SnsLikeTask',
    Content: {
      WxId: wxid,
      SnsId: snsId,
      PostId: postId,
      TaskId: taskId
    }
  }
  sendSock(msg)
}

/**
 * 群管理
 * @param {String} wxid 商家所属微信号
 * @param {String} convId 会话id。注意：此处使用id更方便，不是remoteId
 * @param {Number} action 指令
 * @param {Object} message 指令对应的数据
 * @returns ConversationChangedNotice
 */
export function chatRoomActionTask(wxid, convId, action, message) {
  let content = {
    WxId: wxid, // 商家所属微信号
    ConvId: convId, // 会话id。注意：此处使用id更方便，不是remoteId
    Action: action, // 指令
    taskId: generateTaskId()
  }
  if (message.Members) {
    content.Members = message.Members
  }
  if (message.IntValue) {
    content.IntValue = message.IntValue
  }
  if (message.Content) {
    content.Content = message.Content
  }
  let msg = {
    MsgType: 'ChatRoomActionTask',
    Content: content
  }
  console.log('群管理', msg)
  sendSock(msg)
}

/**
 * 触发手机推送联系人列表任务
 * @param {String} wxid 微信id
 * @returns ContactPushNotice DepartmentPushNotice
 */
export function TriggerContactPushTask(wxid) {
  let msg = {
    MsgType: 'TriggerContactPushTask',
    Content: {
      WxId: wxid
    }
  }
  sendSock(msg)
}

/**
 * 触发手机推送客户列表任务
 * @param {String} wxid 微信id
 * @returns CustomerPushNotice UserLabelPushNotice CorporationPushNotice
 */
export function TriggerCustomerPushTask(wxid) {
  let msg = {
    MsgType: 'TriggerCustomerPushTask',
    Content: {
      WxId: wxid
    }
  }
  sendSock(msg)
}

/**
 * 触发手机推送新客户
 * @param {String} wxid 微信id
 * @returns NewCustomerPushNotice
 */
export function triggerNewCustomerTask(wxid) {
  let msg = {
    MsgType: 'TriggerNewCustomerTask',
    Content: {
      WxId: wxid
    }
  }
  sendSock(msg)
}

/**
 * 通过新客户验证
 * @param {String} wxid 设备企业WX号
 * @param {String} remoteId 联系人id
 * @returns TaskResultNotice
 */
export function acceptCustomerTask(wxid, remoteId) {
  let msg = {
    MsgType: 'AcceptCustomerTask',
    Content: {
      WxId: wxid,
      RemoteId: remoteId,
      TaskId: remoteId
      //   TaskId: generateTaskId()
    }
  }
  sendSock(msg)
}

/**
 * 触发手机推送客户标签
 * @param {String} wxid 微信id
 * @returns UserLabelPushNotice
 */
export function TriggerUserLabelTask(wxid) {
  let msg = {
    MsgType: 'TriggerUserLabelTask',
    Content: {
      WxId: wxid
    }
  }
  sendSock(msg)
}

/**
 * 删除个人标签
 * @param {String} wxid 商家所属企业Wx号
 * @param {Number} labelId 标签id，0则新建标签（如存在同名标签则会失败）
 * @param {String} taskId 任务id
 * @returns TaskResultNotice
 */
export function UserLabelDelTask(wxid, labelId, taskId) {
  let msg = {
    MsgType: 'UserLabelDelTask',
    Content: {
      WxId: wxid,
      LabelId: labelId,
      TaskId: taskId || generateTaskId()
    }
  }
  sendSock(msg)
}

/**
 * 新增或修改个人标签
 * @param {String} wxid 商家所属企业Wx号
 * @param {String} labelName 标签名 id!=0 会修改标签名
 * @param {Number} labelId 标签id，0则新建标签（如存在同名标签则会失败）
 * @param {String} taskId 任务id
 * @returns UserLabelModifyTaskResultNotice
 */
export function UserLabelModifyTask(wxid, labelName, labelId, taskId) {
  let msg = {
    MsgType: 'UserLabelModifyTask',
    Content: {
      WxId: wxid,
      LabelName: labelName,
      LabelId: labelId,
      TaskId: taskId || generateTaskId()
    }
  }
  sendSock(msg)
}

/**
 * 客户）设置标签（基于客户）开发中
 * @param {Number} wxid 商家所属企业Wx号
 * @param {Number} remoteId 联系人id
 * @param {Array} labelId
 * @param {Number} taskId
 * @returns TaskResultNotice
 */
export function UserSetLabelTask(wxid, remoteId, labelId, taskId) {
  let msg = {
    MsgType: 'UserLabelModifyTask',
    Content: {
      WxId: wxid,
      RemoteId: remoteId,
      LabelId: labelId,
      TaskId: taskId || generateTaskId()
    }
  }
  sendSock(msg)
}

/**
 * 客户设置标签
 * @param {Object} message 标签信息
 * @returns TaskResultNotice
 */
export function UserLabelSetTask(message) {
  let content = {
    WxId: message.WxId, // 商家所属企业Wx号
    LabelId: message.LabelId, // 标签id
    IsCorp: message.IsCorp, // 是否为公司标签
    TaskId: message.TaskId
  }
  // 新增的客户id
  if (message.AddUsers) {
    content.AddUsers = message.AddUsers
  }
  // 删除的客户id
  if (message.DelUsers) {
    content.DelUsers = message.DelUsers
  }
  let msg = {
    MsgType: 'UserLabelSetTask',
    Content: content
  }
  sendSock(msg)
}

/**
 * 获取联系人信息
 * @param {Number} wxid 设备企业WX号
 * @param {Number} remoteId 联系人id
 * @returns GetContactInfoTaskResultNotice
 */
export function GetContactInfoTask(wxid, remoteId) {
  let msg = {
    MsgType: 'GetContactInfoTask',
    Content: {
      WxId: wxid,
      RemoteId: remoteId
    }
  }
  sendSock(msg)
}

/**
 * 通知手机端执行特定任务
 * @param {Number} wxid 微信id
 * @param {Number} action 指令
 */
export function PhoneActionTask(wxid, action) {
  let content = {
    WxId: wxid,
    Action: action,
    TaskId: generateTaskId()
  }
  sendSock({ MsgType: 'PhoneActionTask', Content: content })
}

/**
 * 查询手机状态
 * @param {String} wxid 商家个人微信内部全局唯一识别码
 * @returns TaskResultNotice
 */
export function PhoneStateTask(wxid) {
  sendSock({
    MsgType: 'PhoneStateTask',
    Content: { WxId: wxid }
  })
}

/**
 * 消息撤回
 * @param {Number} WxId 设备企业WX号
 * @param {Number} RemoteId 消息remoteId
 * @param {Number} TaskId 任务id
 * @returns TaskResult
 */
export function MsgRevokeTask(WxId, RemoteId, TaskId) {
  sendSock({
    MsgType: 'MsgRevokeTask',
    Content: {
      WxId: WxId,
      RemoteId: RemoteId,
      TaskId: TaskId || generateTaskId()
    }
  })
}

/**
 * 给好友发消息任务
 * @param {Number} WxId 设备企业WX号
 * @param {Number} ConvId 会话 RemoteId
 * @param {String} ContentType 发送消息类型 Text Picture Voice Video Link File NameCard WeApp Quote
 * @param {String} Content 发送消息内容 文本，文件url，链接json，名片wxid
 * @param {Number} RefId 引用消息id
 * @param {Array} AtSomeOne 群聊@某人 0表示@所有人
 * @param {Number} TaskId 发送给手机端的时候需要赋值，
 * @returns TalkToFriendTaskResultNotice
 */
export function TalkToFriendTask(WxId, ConvId, ContentType, Content, RefId = '', AtSomeOne = '', TaskId) {
  let taskContent = {
    WxId: WxId,
    ConvId: ConvId,
    ContentType: ContentType,
    Content: base64.encode(Content.replace(/@\S+\u2005/, '')),
    // RefId: RefId,
    // AtSomeOne: AtSomeOne,
    TaskId: TaskId || generateTaskId()
  }
  if (AtSomeOne) {
    if (typeof AtSomeOne === 'string') {
      taskContent.AtSomeOne = AtSomeOne.split(',')
    } else if (typeof AtSomeOne === 'object') {
      taskContent.AtSomeOne = AtSomeOne
    }
  }
  if (RefId) {
    taskContent.RefId = RefId
  }
  sendSock({
    MsgType: 'TalkToFriendTask',
    Content: taskContent
  })

  // 更新本地数据
  const doc = {
    ...taskContent,
    Content: base64.encode(Content),
    CreateTime: parseInt(new Date().getTime() / 1000, 10),
    SenderId: WxId
    // MsgRemoteId: '',
    // MsgId: taskContent.TaskId
    // MsgId: MsgId,
    // Flag: 131074
    // SenderName: "吉利"
  }
  store.dispatch('conversation/InsertLocalChat', doc)
}
