<template>
  <div class="address-book-page">
    <zPaging ref="zPaging" :show-scrollbar="false" @scrolltolower="doLoadMore">
      <template #top>
        <div :class="'top_bg'">
          <customNavbar
            :class="'index_top_navbar'"
            :title="$t('index.mine.addressBook')"
            :hideHome="navshow"
            :hideBack="navshow"
          >
            <template #left>
              <tm-icon
                @click="goWebHome"
                v-if="navshow"
                name="tmicon-angle-left"
                style="padding-left: 30rpx;"
              ></tm-icon>
            </template>
          </customNavbar>
          <div class="pl-[32rpx] pr-[32rpx] pt-[32rpx] pb-[32rpx]">
            <customInput
              :searchText="searchVal"
              @inputSearchText="inputSearchText"
            ></customInput>
          </div>
        </div>
        <tm-tabs
          :list="state.addressBookTabs"
          align="center"
          :width="750"
          :height="300"
          :itemWidth="250"
          default-name="company"
          activeColor="#46299d"
          activeFontColor="#46299d"
          tabs-line-ani-color="#46299d"
          :showTabsLineAni="true"
          :showTabsLine="false"
          :activeFontSize="32"
          :itemFontSize="30"
          @update:activeName="updateAddressBookTab"
        ></tm-tabs>
      </template>
      <div class="address-book">
        <div class="address-book-tabs-panes-list">
          <div
            class="tabs-panes-each address-book-company"
            v-if="
              state.addressBookActiveTab === 'company' &&
              state.myContractList.length > 0
            "
          >
            <div class="address-book-company-name">
              <span>{{ state.myCompany }}</span>
            </div>
            <div
              class="members-list-each"
              v-for="(item, index) in state.myContractList"
              :key="index"
            >
              <div class="members-info" @click="toUserDetail(item)">
                <avatarModule
                  :mode="1"
                  :avatar="item.avatar"
                  :groupType="0"
                  :userName="item.nickname"
                  :customStyle="{ width: '72rpx', height: '72rpx' }"
                  :customTextStyle="{
                    fontSize: '32rpx',
                    fontWeight: 'bold',
                    color: '#fff',
                    lineHeight: '44rpx',
                  }"
                ></avatarModule>
                <div class="members-info-area">
                  <div class="members-info-basic" style="padding: 0 0 24rpx;">
                    <span class="members-name">
                      {{ item.nickname }}
                    </span>
                    <span class="members-jobNum">
                      {{ item.job_num }}
                    </span>
                  </div>
                  <div class="members-positions-area">
                    <tm-popover position="bc">
                      <tm-scrolly :refresher="false" :height="84">
                        <div class="members-positions">
                          <div
                            class="members-positions-each"
                            v-for="(postionItem,
                            positionIndex) in item.user_position"
                            :key="positionIndex"
                          >
                            {{ postionItem.position_name }}
                          </div>
                        </div>
                      </tm-scrolly>
                      <template v-slot:label>
                        <tm-scrolly
                          :refresher="false"
                          :height="
                            item.user_position.length >= 4
                              ? 180
                              : item.user_position.length === 3
                              ? 140
                              : item.user_position.length === 2
                              ? 100
                              : item.user_position.length === 1
                              ? 60
                              : 0
                          "
                        >
                          <div class="members-positions-popover-box">
                            <div
                              class="members-positions-popover"
                              v-for="(postionItem,
                              positionIndex) in item.user_position"
                              :key="positionIndex"
                            >
                              {{ postionItem.position_name }}
                            </div>
                          </div>
                        </tm-scrolly>
                      </template>
                    </tm-popover>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div
            class="tabs-panes-each address-book-friends"
            v-if="
              state.addressBookActiveTab === 'friends' &&
              state.myFriendsList.length > 0
            "
          >
            <div
              class="members-list-each"
              v-for="(item, index) in state.myFriendsList"
              :key="index"
            >
              <wd-swipe-action
                class="swipe-action"
                @click="showDeleteModal(item, index)"
                v-if="
                  !item.company_name ||
                  (item.company_name && item.company_name !== state.myCompany)
                "
              >
                <div class="members-info" @click="toUserDetail(item)">
                  <avatarModule
                    :mode="1"
                    :avatar="item.avatar"
                    :groupType="0"
                    :userName="item.nickname"
                    :customStyle="{ width: '72rpx', height: '72rpx' }"
                    :customTextStyle="{
                      fontSize: '32rpx',
                      fontWeight: 'bold',
                      color: '#fff',
                      lineHeight: '44rpx',
                    }"
                  ></avatarModule>
                  <div class="members-info-area">
                    <div
                      class="members-info-basic"
                      :style="{ padding: item.company_name ? 0 : '0 0 24rpx' }"
                    >
                      <span class="members-name">
                        {{ item.nickname }}
                      </span>
                      <span class="members-jobNum">
                        {{ item.job_num }}
                      </span>
                      <!-- <span class="members-company">{{ item.company_name }}</span> -->
                    </div>
                    <div class="members-positions-area">
                      <tm-popover position="bc">
                        <tm-scrolly :refresher="false" :height="84">
                          <div class="members-positions">
                            <div
                              class="members-positions-each"
                              v-for="(postionItem,
                              positionIndex) in item.user_position"
                              :key="positionIndex"
                            >
                              {{ postionItem.position_name }}
                            </div>
                          </div>
                        </tm-scrolly>
                        <template v-slot:label>
                          <tm-scrolly
                            :refresher="false"
                            :height="
                              item.user_position.length >= 4
                                ? 180
                                : item.user_position.length === 3
                                ? 140
                                : item.user_position.length === 2
                                ? 100
                                : item.user_position.length === 1
                                ? 60
                                : 0
                            "
                          >
                            <div class="members-positions-popover-box">
                              <div
                                class="members-positions-popover"
                                v-for="(postionItem,
                                positionIndex) in item.user_position"
                                :key="positionIndex"
                              >
                                {{ postionItem.position_name }}
                              </div>
                            </div>
                          </tm-scrolly>
                        </template>
                      </tm-popover>
                    </div>
                  </div>
                </div>
                <div class="company-infos" v-if="item.company_name">
                  <div class="company-each">
                    <span>{{ item.company_name }}</span>
                  </div>
                </div>
                <template #right>
                  <div
                    v-for="(swipeActionItem,
                    swipeActionIndex) in state.swipeAction"
                    :key="swipeActionIndex"
                  >
                    <span>{{ swipeActionItem.text }}</span>
                  </div>
                </template>
              </wd-swipe-action>
            </div>
          </div>
          <div
            class="tabs-panes-each address-book-groups"
            v-if="
              state.addressBookActiveTab === 'groups' &&
              state.myGroupsList.length > 0
            "
          >
            <div
              class="groups-list-each"
              v-for="(item, index) in state.myGroupsList"
              :key="index"
            >
              <div class="groups-info">
                <avatarModule
                  :mode="2"
                  :avatar="item?.avatar"
                  :groupType="Number(item?.group_type)"
                  :customStyle="{ width: '72rpx', height: '72rpx' }"
                ></avatarModule>
                <span class="groups-name">
                  {{ item?.group_name }}
                </span>
                <span
                  class="groups-type"
                  :style="{
                    color:
                      groupTypeMapping[item?.group_type]?.result_type_color,
                    border:
                      '1px solid' +
                      groupTypeMapping[item?.group_type]?.result_type_color,
                  }"
                >
                  {{ groupTypeMapping[item?.group_type]?.result_type }}
                </span>
              </div>
              <div class="groups-btns">
                <div class="groups-btns-each" @click="toGroupChat(item)">
                  <span>{{ $t('addressBook.btns.enterGroup') }}</span>
                </div>
              </div>
            </div>
          </div>
          <div
            class="addressBook-noData"
            v-if="
              !state.isLoadingData &&
              ((state.addressBookActiveTab === 'company' &&
                state.myContractList.length === 0) ||
                (state.addressBookActiveTab === 'friends' &&
                  state.myFriendsList.length === 0) ||
                (state.addressBookActiveTab === 'groups' &&
                  state.myGroupsList.length === 0))
            "
          >
            <img src="@/static/image/search/search-no-data.png" />
            <span>
              {{
                searchVal
                  ? $t('addFriend.message.notFindData')
                  : $t('search.hint')
              }}
            </span>
          </div>
        </div>
      </div>
      <tm-modal
        class="friendDeleteModal"
        ref="friendDeleteModalRef"
        :mask="true"
        :okText="$t('ok')"
        okColor="#46299d"
        cancelColor="#999"
        @ok="doDeleteFriend"
        @cancel="hideDeleteModal"
        :teleport="false"
        titleStyle="font-size: 40rpx;font-weight: 600;line-height: 1;"
        :height="300"
        :round="4"
      >
        <div class="friendDeleteModal-content">
          <span>{{ $t('addressBook.message.doOrNotDeleteFriend') }}</span>
        </div>
      </tm-modal>
    </zPaging>
  </div>
</template>
<script setup>
import customInput from '@/components/custom-input/custom-input.vue'
import zPaging from '@/uni_modules/z-paging/components/z-paging/z-paging.vue'
import avatarModule from '@/components/avatar-module/index.vue'

import { ref, onMounted, reactive, watch } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { handleSetWebviewStyle, handleFindWebview } from '@/utils/common'
import { ServeUserGroupChatList, ServeCreateTalkList } from '@/api/chat/index'
import { ServeGetSessionId } from '@/api/search/index'
import { formatTalkItem } from '@/utils/talk'
import { useDialogueStore, useTalkStore } from '@/store'
import {
  ServeQueryFriendsList,
  ServeDeleteFriend,
} from '@/api/addressBook/index'

import { useI18n } from 'vue-i18n'
const { t } = useI18n()

const navshow = ref(false)
const searchVal = ref('')
const friendDeleteModalRef = ref(null)

const state = reactive({
  addressBookTabs: [], //tab页
  addressBookActiveTab: 'company', //当前选中的通讯录tab
  myContractListPage: 1, //当前查询的我的组织架构通讯录列表分页
  myContractListPageSize: 10, //我的组织架构通讯录列表单页数量
  myContractList: [], //我的组织架构通讯录列表
  hasMoreContracts: true, //是否还有更多我的组织架构通讯录数据
  myFriendsListPage: 1, //当前查询的我的好友列表分页
  myFriendsListPageSize: 10, //我的好友列表单页数量
  myFriendsList: [], //我的好友列表
  hasMoreFriends: true, //是否还有更多我的好友数据
  myGroupsListPage: 1, //当前查询的群组列表分页
  myGroupsListPageSize: 10, //群组列表单页数量
  myGroupsList: [], //我的群组列表
  hasMoreGroups: true, //是否还有更多我的群组数据
  myCompany: '', //当前登录人公司别
  swipeAction: [], //左滑操作栏按钮组
  isLoadingData: true, //是否正在加载数据
})

onLoad((options) => {
  if (options.type) {
    navshow.value = true
  }
})

const goWebHome = () => {
  uni.navigateBack()
  handleFindWebview(`handleBackHost()`)
}

onMounted(() => {
  state.swipeAction = [
    {
      text: t('addressBook.btns.delete'), //操作按钮的文本,
    },
  ]
  state.addressBookTabs = [
    {
      key: 'company',
      title: t('addressBook.tabs.company'),
    },
    {
      key: 'friends',
      title: t('addressBook.tabs.friends'),
    },
    {
      key: 'groups',
      title: t('addressBook.tabs.groups'),
    },
  ]
  handleSetWebviewStyle()
  getMyContractList()
})

//输入搜索内容
const inputSearchText = (e) => {
  searchVal.value = e
}

//切换通讯录tab
const updateAddressBookTab = (e) => {
  state.addressBookActiveTab = e
}

//获取“组织架构”通讯录列表
const getMyContractList = () => {
  let params = {
    type: 'addressBook', //查我的通讯录的时候写死addressBook
    page: state.myContractListPage,
    page_size: state.myContractListPageSize,
    name: searchVal.value,
  }
  // console.log(params)
  state.isLoadingData = true
  ServeQueryFriendsList(params)
    .then((res) => {
      // console.log(res)
      state.isLoadingData = false
      if (res?.code === 200) {
        state.myCompany = res.data?.company_name
        if (state.myContractListPage === 1) {
          state.myContractList = res.data?.user_list || []
        } else {
          state.myContractList = state.myContractList.concat(
            res.data?.user_list || [],
          )
        }
        if (state.myContractList.length < res.data?.count) {
          state.hasMoreContracts = true
        } else {
          state.hasMoreContracts = false
        }
      }
    })
    .catch((err) => {
      state.isLoadingData = false
    })
}

//获取“我的好友”列表
const getMyFriendsList = () => {
  let params = {
    type: 'myFriends', //查我得好友的时候写死myFriends
    page: state.myFriendsListPage,
    page_size: state.myFriendsListPageSize,
    name: searchVal.value,
  }
  console.error(params)
  state.isLoadingData = true
  ServeQueryFriendsList(params)
    .then((res) => {
      console.log(res)
      state.isLoadingData = false
      if (res?.code === 200) {
        if (state.myFriendsListPage === 1) {
          state.myFriendsList = res.data?.user_list || []
        } else {
          state.myFriendsList = state.myFriendsList.concat(
            res.data?.user_list || [],
          )
        }
        if (state.myFriendsList.length < res.data?.count) {
          state.hasMoreFriends = true
        } else {
          state.hasMoreFriends = false
        }
      }
    })
    .catch((err) => {
      state.isLoadingData = false
    })
}

//点击进入用户详情页面
const toUserDetail = (userInfo) => {
  uni.navigateTo({
    url:
      '/pages/dialog/dialogDetail/userDetail??erpUserId=' +
      userInfo.erp_user_id,
  })
}

//获取“我的群组”列表
const getMyGroupsList = () => {
  let params = {
    page: state.myGroupsListPage,
    page_size: state.myGroupsListPageSize,
    group_name: searchVal.value,
  }
  state.isLoadingData = true
  ServeUserGroupChatList(params)
    .then((res) => {
      console.log(res)
      state.isLoadingData = false
      if (res?.code === 200) {
        if (state.myGroupsListPage === 1) {
          state.myGroupsList = res.data?.items || []
        } else {
          state.myGroupsList = state.myGroupsList.concat(res.data?.items || [])
        }
        if (state.myGroupsList.length < res.data?.total) {
          state.hasMoreGroups = true
        } else {
          state.hasMoreGroups = false
        }
      }
    })
    .catch((err) => {
      state.isLoadingData = false
    })
}

//加载更多数据
const doLoadMore = (e) => {
  if (state.addressBookActiveTab === 'company' && state.hasMoreContracts) {
    state.myContractListPage += 1
    getMyContractList()
  } else if (state.addressBookActiveTab === 'friends' && state.hasMoreFriends) {
    state.myFriendsListPage += 1
    getMyFriendsList()
  } else if (state.addressBookActiveTab === 'groups' && state.hasMoreGroups) {
    state.myGroupsListPage += 1
    getMyGroupsList()
  }
}

//获取会话Id
const getSessionId = (talk_type, receiver_id) => {
  return new Promise((resolve, reject) => {
    let params = {
      talkType: talk_type,
      receiverId: receiver_id,
    }
    const resp = ServeGetSessionId(params)
    console.log(resp)
    resp.then(({ code, data }) => {
      console.log(data)
      if (code == 200) {
        resolve(data?.sessionId)
      } else {
      }
    })
    resp.catch(() => {})
  })
}

//点击跳转进入我的指定群聊
const toGroupChat = async (groupInfo) => {
  let talk_type = 2
  let receiver_id = groupInfo.id
  const sessionId = await getSessionId(talk_type, receiver_id)
  if (useTalkStore().findTalkIndex(`${talk_type}_${receiver_id}`) === -1) {
    ServeCreateTalkList({
      talk_type,
      receiver_id,
    }).then(async ({ code, data }) => {
      if (code == 200) {
        let item = formatTalkItem(data)
        useTalkStore().addItem(item)
      }
    })
  }
  useDialogueStore().setDialogue({
    name: groupInfo.group_name,
    talk_type: 2,
    receiver_id: receiver_id,
  })
  uni.navigateTo({
    url: '/pages/dialog/index?sessionId=' + sessionId,
  })
}

//显示删除好友确认框
const showDeleteModal = (userInfo, friendIndex) => {
  friendDeleteModalRef.value.open({
    userInfo,
    friendIndex,
  })
}

//关闭删除好友确认框
const hideDeleteModal = () => {
  friendDeleteModalRef.value.close()
}

//删除好友
const doDeleteFriend = (args) => {
  console.log(args.userInfo, args.friendIndex)
  let params = {
    receiver_id: args.userInfo.id, //聊天的用户id
    talk_type: 1,
  }
  ServeDeleteFriend(params).then((res) => {
    console.log(res)
    if (res?.code === 200) {
      message.success(t('addressBook.message.deleteSuccess') + ' !')
      state.myFriendsList.splice(args.friendIndex, 1)
    }
  })
}

// 映射表-根据groupType设置对应值
const groupTypeMapping = {
  0: {},
  1: {},
  2: {
    result_type: t('index.mine.department'),
    result_type_color: '#377EC6',
  },
  3: {
    result_type: t('index.mine.project'),
    result_type_color: '#C1681C',
  },
  4: {
    result_type: t('index.type.company'),
    result_type_color: '#7A58DE',
  },
}

watch(
  () => state.addressBookActiveTab,
  (newVal) => {
    if (newVal === 'company') {
      state.myContractListPage = 1
      getMyContractList()
    } else if (newVal === 'friends') {
      state.myFriendsListPage = 1
      getMyFriendsList()
    } else if (newVal === 'groups') {
      state.myGroupsListPage = 1
      getMyGroupsList()
    }
  },
)

watch(
  () => searchVal.value,
  (newVal) => {
    if (state.addressBookActiveTab === 'company') {
      state.myContractListPage = 1
      getMyContractList()
    } else if (state.addressBookActiveTab === 'friends') {
      state.myFriendsListPage = 1
      getMyFriendsList()
    } else if (state.addressBookActiveTab === 'groups') {
      state.myGroupsListPage = 1
      getMyGroupsList()
    }
  },
)
</script>
<style scoped lang="scss">
::v-deep .zp-paging-container-content {
  height: 100%;
  display: flex;
}

::v-deep .index_top_navbar .tmicon-angle-left {
  color: #fff !important;
}

::v-deep .index_top_navbar .text-weight-b {
  color: #fff !important;
}

::v-deep .index_top_navbar .statusHeightTop > .noNvueBorder:first-child {
  background: transparent !important;
  border: none !important;
}

.top_bg {
  background: url('@/static/image/mine/page_top.png') no-repeat;
  background-size: cover;
  background-position: bottom center;
}

:deep(.animateAll_tabs_tmui) {
  width: 120rpx !important;
  height: 10rpx !important;
}

.address-book-page {
  .address-book {
    flex: 1;
    display: flex;
    flex-direction: column;
    background-image: url('@/static/image/clockIn/z3280@3x.png');
    background-size: cover;
    background-position: bottom center;
    background-attachment: fixed;
    width: 100%;

    .address-book-tabs-panes-list {
      margin: 30rpx 24rpx;
      overflow: hidden;
      flex: 1;
      display: flex;
      flex-direction: column;

      .tabs-panes-each {
        gap: 30rpx 0;
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        justify-content: center;
      }
      .address-book-company,
      .address-book-friends {
        .address-book-company-name {
          margin: 0 0 -16rpx;
          span {
            font-size: 26rpx;
            font-weight: 400;
            line-height: 1;
            color: #999;
          }
        }
        .members-list-each {
          display: flex;
          flex-direction: column;
          align-items: flex-start;
          justify-content: center;
          background-color: #fff;
          width: 100%;
          border-radius: 8rpx;

          .swipe-action {
            width: 100%;
            overflow: visible !important;

            :deep(.wd-swipe-action__right) {
              display: flex;
              flex-direction: row;
              align-items: center;
              justify-content: center;
              background-color: #cf3050;
              padding: 0 48rpx;
              border-radius: 0 8rpx 8rpx 0;
              span {
                color: #fff;
                line-height: 1;
                font-size: 30rpx;
                font-weight: 400;
              }
            }
          }

          .members-info {
            display: flex;
            flex-direction: row;
            align-items: flex-start;
            justify-content: flex-start;
            gap: 16rpx;
            padding: 24rpx 24rpx 0;
            width: 100%;

            .members-info-area {
              display: flex;
              flex-direction: row;
              align-items: flex-start;
              justify-content: flex-start;
              gap: 16rpx;

              .members-info-basic {
                display: flex;
                flex-direction: column;
                align-items: flex-start;
                justify-content: center;

                .members-name {
                  font-size: 30rpx;
                  font-weight: 500;
                  width: 150rpx;
                  word-break: break-all;
                }

                .members-jobNum {
                  font-size: 26rpx;
                  font-weight: 400;
                  color: #999;
                  word-break: break-all;
                  margin: 10rpx 0 0;
                }

                .members-company {
                  font-size: 24rpx;
                  font-weight: 400;
                  line-height: 1;
                  color: #999;
                }
              }
              .members-positions-area {
                .members-positions {
                  display: flex;
                  flex-direction: row;
                  align-items: center;
                  justify-content: flex-start;
                  flex-wrap: wrap;
                  gap: 10rpx;
                  padding: 4rpx 0 0;
                  max-height: 84rpx;
                  overflow: hidden;
                  -webkit-box-orient: vertical;
                  -webkit-line-clamp: 2;
                  line-clamp: 2;

                  .members-positions-each {
                    background-color: #eee9f8;
                    line-height: 1;
                    font-size: 24rpx;
                    padding: 4rpx 16rpx;
                    color: #46299d;
                  }
                }
                .members-positions-popover-box {
                  display: flex;
                  flex-direction: column;
                  align-items: center;
                  justify-content: center;
                  gap: 10rpx 0;

                  .members-positions-popover {
                    background-color: #eee9f8;
                    line-height: 1;
                    font-size: 24rpx;
                    padding: 8rpx 16rpx;
                    color: #46299d;
                    width: 100%;
                  }
                }
              }
            }
          }
          .company-infos {
            margin: 0 0 0 88rpx;
            padding: 0 0 24rpx 24rpx;
            .company-each {
              span {
                font-size: 24rpx;
                font-weight: 400;
                line-height: 1;
                color: #999;
              }
            }
          }
        }
      }
      .address-book-groups {
        .groups-list-each {
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: space-between;
          background-color: #fff;
          width: 100%;
          padding: 24rpx;
          border-radius: 8rpx;

          .groups-info {
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: flex-start;
            gap: 16rpx;
            .groups-name {
              font-size: 30rpx;
              font-weight: 500;
            }
            .groups-type {
              font-size: 24rpx;
              border-radius: 6rpx;
              font-weight: bold;
              padding: 6rpx 12rpx;
              flex-shrink: 0;
            }
          }
          .groups-btns {
            flex-shrink: 0;
            margin: 0 0 0 16rpx;
            .groups-btns-each {
              display: flex;
              flex-direction: row;
              align-items: center;
              justify-content: center;
              background-color: #46299d;
              padding: 16rpx;
              border-radius: 8rpx;

              span {
                color: #fff;
                font-size: 24rpx;
                font-weight: 400;
                line-height: 1;
              }
            }
          }
        }
      }
      .addressBook-noData {
        margin: 30rpx 24rpx;
        overflow: hidden;
        flex: 1;
        gap: 30rpx 0;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        img {
          width: 500rpx;
        }
        span {
          font-size: 30rpx;
          font-weight: 400;
          line-height: 1;
          color: #999;
        }
      }
    }
  }

  .friendDeleteModal {
    :deep(.overlay) {
      height: 100vh !important;
    }
    .friendDeleteModal-content {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
    }
  }
}
</style>
