<script lang="js" setup>
import { ref, computed, onMounted, watch, reactive, nextTick, getCurrentInstance, h } from 'vue'
import { ServeGetTalkList } from '@/api/chat.js'
import { ServeGetGroups } from '@/api/group'
import XNModal from '@/components/x-naive-ui/x-n-modal/index.vue'
import { Plus } from '@vicons/tabler'
import { CloseCircle } from '@vicons/ionicons5'
import customModal from '@/components/common/customModal.vue'
import xSearchForm from '@/components/x-naive-ui/x-search-form/index.vue'
import xNDataTable from '@/components/x-naive-ui/x-n-data-table/index.vue'
import flTree from '@/components/flnlayout/tree/flnindex.vue'
import { processError, processSuccess } from '@/utils/helper/message.js'
import { ServeUserGroupChatList } from '@/api/search'
import { GetContactFriendList } from '@/api/chat'
import { getUserInfoByERPUserId } from '@/api/user'
import { useRouter } from 'vue-router'
import { useUtil } from '@/hooks/useUtil'
import { NButton } from 'naive-ui'

const emit = defineEmits(['close', 'on-submit'])

const { useMessage } = useUtil()
const router = useRouter()

const currentInstance = getCurrentInstance()
const $request = currentInstance?.appContext.config.globalProperties?.$request

const isShowBox = defineModel('show')
const loading = ref(true)
const items = ref([])
const keywords = ref('')
const loadGroupStatus = ref(false)
const props = defineProps({
  'forwardMode': {
    type: Number,
    default: 0
  }
})

// 通讯录弹窗相关状态
const state = reactive({
  selectedGroupRowKeys: [],
  isShowAddressBookModal: false,
  customModalStyle: {
    width: '1288px',
    height: '846px',
    backgroundColor: '#F9F9FD'
  },
  addressBookSearchConfig: [
    {
      label: '姓名',
      key: 'nickName',
      type: 'input',
      valueType: 'string'
    }
  ],
  groupChatListSearchConfig: [
    {
      label: '群聊名称',
      key: 'groupName',
      type: 'input',
      valueType: 'string'
    }
  ],
  treeData: [],
  expandedKeys: [],
  clickKey: 3,
  treeRefreshCount: 0,
  treeSelectData: {},
  addressBookColumns: [
    {
      type: 'selection'
    },
    {
      title: '姓名 【工号】',
      field: 'nickname',
      width: 200,
      ellipsis: {
        tooltip: true
      },
      render(row, index) {
        return row.nickName + '【' + row.jobNum + '】'
      }
    },
    {
      title: '岗位名称',
      field: 'user_position',
      width: 400,
      ellipsis: {
        tooltip: true
      },
      render(row, index) {
        let positionNames = Array.isArray(row.depPositions)
          ? row.depPositions.flatMap((dep) =>
              Array.isArray(dep.positions) ? dep.positions.map((pos) => pos.name) : []
            )
          : []
        return positionNames.join(' , ')
      }
    }
  ],
  groupChatListColumns: [
        {
      type: 'selection'
    },
    {
      title: '群聊名称',
      field: 'groupName',
      width: 400,
      ellipsis: {
        tooltip: true
      },
      render(row, index) {
        return row.group_name
      }
    },
    {
      title: '群类型',
      field: 'groupType',
      width: 200,
      ellipsis: true,
      render(row, index) {
        let groupType = row.group_type
        if (groupType == 1) {
          return '普通群'
        } else if (groupType == 2) {
          return '部门群'
        } else if (groupType == 3) {
          return '项目群'
        } else if (groupType == 4) {
          return '公司群'
        }
      }
    }
  ],
  addressBookData: [],
  company_name: '',
  groupChatListData: [],
  addressBookTableHeight: 500,
  addressBookTableWidth: 800,
  addressBookPage: 1,
  addressBookPageSize: 10,
  addressBookTotal: 0,
  addressBookSearchNickName: '',
  addressBookCurrentTab: 'employeeAddressBook',
  groupChatListPage: 1,
  groupChatListPageSize: 10,
  groupChatListTotal: 0,
  groupChatListSearchGroupName: '',
  selectedRowKeys: []
})

// 原有转发功能的过滤器
const searchFilter = computed(() => {
  return items.value.filter((item) => {
    return item.name.toLowerCase().includes(keywords.value.toLowerCase())
  })
})

const checkedFilter = computed(() => {
  return items.value.filter((item) => item.checked)
})

const isCanSubmit = computed(() => {
  return !checkedFilter.value.length
})

// 原有加载数据函数
const onLoad = () => {
  onLoadContact()
}

const onLoadContact = () => {
  loading.value = true
  ServeGetTalkList()
    .then((res) => {
      if (res.code == 200) {
        let list = res.data.items || []

        items.value = list.filter((item) => ((item.talk_type === 1 && item.receiver_id !== 2) || item.talk_type !== 1)).map((item) => {
          return {
            ...item,
            checked: false
          }
        })
      }
    })
    .finally(() => {
      loading.value = false
    })
}

// 原有转发功能函数
const onMaskClick = () => {
  emit('close')
}

const selectType = ref(2)

const onTriggerContact = (item) => {
  const clicked = items.value.find((val) => val.id === item.id)
  if (!clicked) return

  

  // 多选：限制同一类型选择
  if (!clicked.checked) {

    clicked.checked = true
  } else {
    clicked.checked = false
  }
}

const onRemoveContact = (item) => {
  let data = items.value.find((val) => val.id === item.id)
  
  if (data) {
    data.checked = false
  }
}

const onCancel = () => {
  isShowBox.value = false
}

const onSubmit = () => {
  let data = checkedFilter.value.map((item) => {
    return {
      receiver_id: item.receiver_id,
      talk_type: item.talk_type
    }
  })
  emit('on-submit', data)
}

// 通讯录弹窗功能函数
const onCreateContact = () => {
  state.isShowAddressBookModal = true
  getTreeData()
  getDepPoisUser()
  getUserGroupChatList()
}

const closeAddressBookModal = () => {
  state.isShowAddressBookModal = false
  resetAddressBookModal()
}

const calcTreeData = (data) => {
  for (let item of data) {
    item.key = item.ID
    item.label = item.name
    item.title = item.name
    if (item.sons) {
      item.children = item.sons
      calcTreeData(item.children)
    }
    delete item.ID
    delete item.name
    delete item.sons
  }
}

const getTreeData = () => {
  let url = '/department/v2/tree/filter'
  let params = {}
  $request.HTTP.components.postDataByParams(url, params).then(
    (res) => {
      if (res.status === 0 && Array.isArray(res.data.nodes)) {
        let data = res.data.nodes
        calcTreeData(data)
        state.treeData = data
        state.treeRefreshCount++
        getDepPoisUser()
      } else {
        processError(res.msg || '获取失败！')
      }
    },
    () => {
      processError('获取失败！')
    },
    () => {
      processError('获取失败！')
    }
  )
}

const getDepPoisUser = () => {
  let url = '/user/v2/list'
  let params = {
    departmentId: state.addressBookSearchNickName ? undefined : state.clickKey,
    page: state.addressBookPage,
    pageSize: state.addressBookPageSize,
    status: 'notactive',
    nickName: state.addressBookSearchNickName
  }
  $request.HTTP.components.postDataByParams(url, params).then((res) => {
    if (res.code === 200) {
      state.addressBookData = res?.data?.data || []
      state.addressBookTotal = res?.data?.count || 0
    }
  })
}

const getUserGroupChatList = () => {
  let params = {
    page: state.groupChatListPage,
    page_size: state.groupChatListPageSize,
    group_name: state.groupChatListSearchGroupName
  }
  ServeUserGroupChatList(params).then((res) => {
    if (res.code === 200) {
      state.groupChatListData = res?.data?.items || []
      state.groupChatListTotal = res?.data?.total || 0
    }
  })
}

const handleTreeClick = ({ selectedKey, tree }) => {
  state.clickKey = tree.key
  state.treeSelectData = tree
  state.addressBookPage = 1
  getDepPoisUser()
}

const resetAddressBookModal = () => {
  nextTick(() => {
    state.addressBookCurrentTab = 'employeeAddressBook'
    state.addressBookSearchNickName = ''
    state.groupChatListSearchGroupName = ''
    state.addressBookTableWidth = 800
    state.clickKey = 3
    state.treeRefreshCount++
    state.addressBookPage = 1
    state.addressBookPageSize = 10
    state.groupChatListPage = 1
    state.groupChatListPageSize = 10
    state.selectedRowKeys = []
    getDepPoisUser()
    getUserGroupChatList()
  })
}

const handleAddressBookPagination = (page) => {
  state.addressBookPage = page
  getDepPoisUser()
}

const handleAddressBookPaginationSize = (pageSize) => {
  state.addressBookPageSize = pageSize
  state.addressBookPage = 1
  getDepPoisUser()
}

const changeAddressBookSearch = (value) => {
  if (!value.nickName?.trim()) {
    state.addressBookSearchNickName = ''
  } else {
    state.addressBookSearchNickName = value.nickName
  }
}

const handleAddressBookTabChange = (value) => {
  state.addressBookCurrentTab = value
  // 切换时清空另一类选项
  if (value === 'employeeAddressBook') {
    state.selectedGroupRowKeys = []
  } else if (value === 'groupChatList') {
    state.selectedRowKeys = []
  }
}

const changeGroupChatListSearch = (value) => {
  if (!value.groupName?.trim()) {
    state.groupChatListSearchGroupName = ''
  } else {
    state.groupChatListSearchGroupName = value.groupName
  }
}

const handleGroupChatListPagination = (page) => {
  state.groupChatListPage = page
  getUserGroupChatList()
}

const handleGroupChatListPaginationSize = (pageSize) => {
  state.groupChatListPageSize = pageSize
  state.groupChatListPage = 1
  getUserGroupChatList()
}

const onAddressBookCancel = () => {
  state.isShowAddressBookModal = false
}

const onAddressBookSubmit = async () => {
  if (state.addressBookCurrentTab === 'employeeAddressBook') {
    if (!Array.isArray(state.selectedRowKeys) || state.selectedRowKeys.length === 0) {
      processError('请选择联系人')
      return
    }

    try {
      const results = await Promise.all(
        state.selectedRowKeys.map((erpId) => getUserInfoByERPUserId({ erp_user_id: erpId }))
      )

      const data = results
        .filter((res) => res && res.code === 200 && res.data && res.data.sys_id)
        .map((res) => ({ receiver_id: res.data.sys_id, talk_type: 1 }))

      if (data.length === 0) {
        processError('未获取到有效联系人')
        return
      }

      emit('on-submit', data)
      state.isShowAddressBookModal = false
    } catch (e) {
      processError('发送失败，请稍后重试')
    }
  } else if (state.addressBookCurrentTab === 'groupChatList') {
    if (!Array.isArray(state.selectedGroupRowKeys) || state.selectedGroupRowKeys.length === 0) {
      processError('请选择群聊')
      return
    }

    const data = state.selectedGroupRowKeys.map((gid) => ({ receiver_id: gid, talk_type: 2 }))
    emit('on-submit', data)
    state.isShowAddressBookModal = false
  }
}

watch(() => {
  return isShowBox.value
}, (newVal) => {
  if (newVal) {
    onLoad()
  }
})

watch(() => state.addressBookSearchNickName, (newValue, oldValue) => {
  if (newValue) {
    state.addressBookTableWidth = 1142
    state.addressBookPage = 1
  } else {
    state.addressBookTableWidth = 800
    state.clickKey = 3
    state.treeRefreshCount++
    state.addressBookPage = 1
  }
  getDepPoisUser()
})

watch(() => state.groupChatListSearchGroupName, (newValue, oldValue) => {
  if (newValue) {
    state.groupChatListPage = 1
  } else {
    state.groupChatListPage = 1
  }
  getUserGroupChatList()
})
</script>

<template>
  <x-n-modal v-model:show="isShowBox" :title="forwardMode === 2 ? '合并转发' : '逐条转发'" style="width: 997px; height: 740px;background-color: #F9F9FD"
    :on-after-leave="onMaskClick" content-style="display: flex; justify-content: center; align-items: center;">
    <div class="w-927px h-627px bg-#fff rounded-3px px-35px pb-20px pt-10px">
  <div class="w-100% flex justify-end mb-5px">
          <n-button text type="primary" @click="onCreateContact">
    <template #icon>
      <Plus />
    </template>
    创建新聊天
  </n-button>
  </div>
      <div class="flex items-center justify-between mb-28px">
        <div class="text-#333639">搜索</div>
        <div class="w-779px h-34px">
          <n-input v-model:value="keywords" type="text" clearable placeholder="请输入">
         
          </n-input>
        </div>
      </div>
      <div class="flex justify-between">
        <div class="w-260px h-517px rounded-4px border-1px border-solid border-#E5E5E5 px-12px">
          <!-- <div class="border-b-2px border-b-solid border-b-#FBFBFB h-35px flex items-center justify-end">
            <n-button text color="#46299D" class="text-14px" @click="changeSelectType">
              {{ selectType === 1 ? '多选' : '取消多选' }}
            </n-button>
          </div> -->
          <div>
            <n-virtual-list v-if="!loading" style="max-height: 470px" :item-size="65" :items="searchFilter">
              <template #default="{ item }">
                <div class="flex items-center border-b-2px border-b-solid h-65px border-b-#FBFBFB"
                 >
                  <div class="mr-22px">
             
                    <n-checkbox  v-model:checked="item.checked" />
                  </div>
                  <div class="mr-10px">
                    
                    <avatarModule class="mr-10px" showGroupType   :mode="item.talk_type"
              :avatar="item.avatar"
              :groupType="item.group_type"
              :customStyle="{width:'42px',height:'42px'}"></avatarModule>
                    <!-- <n-image class="w-42px h-42px rounded-full" :src="item.avatar" /> -->
                  </div>
                  <div class="flex items-center overflow-hidden flex">
                    <span class="text-ellipsis">{{ item.name }}</span>
                    <!-- <span v-if="item.type == 2" class="badge group ml-2">群</span> -->
                    <span v-if="item.talk_type === 2" class="flex-shrink-0">{{ `(${item.group_member_num})` }}</span>
                  </div>
                </div>
              </template>
            </n-virtual-list>
            <div v-else class="flex-center h-470px">
              <span>加载中...</span>
            </div>
          </div>
        </div>
        <div class="w-578px h-517px rounded-4px border-1px border-solid border-#E5E5E5 px-12px">
          <div class="border-b-2px border-b-solid border-b-#FBFBFB h-35px flex items-center text-14px text-#000">
            发送给
          </div>
          <div class="h-350px border-b-2px border-b-solid border-b-#FBFBFB">
            <div v-if="checkedFilter.length > 0">
              <n-virtual-list style="max-height: 350px" :item-size="65" :items="checkedFilter">
                <template #default="{ item }">
                  <div class="flex items-center border-b-2px border-b-solid h-65px border-b-#FBFBFB pr-20px">
                    <div class="mr-10px">
                      <avatarModule class="mr-10px" showGroupType   :mode="item.talk_type"
              :avatar="item.avatar"
              :groupType="item.group_type"
              :customStyle="{width:'42px',height:'42px'}"></avatarModule>
                    </div>
                    <div class="flex items-center overflow-hidden flex">
                      <span class="text-ellipsis">{{ item.name }}</span>
                      <!-- <span v-if="item.type == 2" class="badge group ml-2">群</span> -->
                      <span v-if="item.talk_type === 2" class="flex-shrink-0">{{ `(${item.group_member_num})` }}</span>
                    </div>
                    <n-button class="ml-auto" text color="#C7C7C9" @click="onRemoveContact(item)">
                      <n-icon :component="CloseCircle" size="18" />
                    </n-button>
                  </div>
                </template>
              </n-virtual-list>
            </div>
            <div v-else class="flex-center h-350px">
              <n-empty size="medium" description="暂无选择联系人">
                <template #icon>
                  <img src="@/assets/image/no-data.svg" alt="" />
                </template>
              </n-empty>
            </div>
          </div>
          <div class="flex flex-col items-center justify-center h-120px">
            <div class="text-14px text-#999999 mb-23px">
              <span>[{{ forwardMode === 2 ? '合并转发' : '逐条转发' }}]</span> 
              <span v-if="checkedFilter.length > 0">
  {{
    checkedFilter.length > 2
      ? checkedFilter.slice(0, 2).map(item => item.name).join('、') + ' 等'
      : checkedFilter.map(item => item.name).join('、')
  }}会话记录
</span>
              <span v-else>请选择联系人</span>
            </div>
            <div class="flex justify-center items-center ">
              <n-button color="#C7C7C9" class="w-250px h-34px text-14px text-#fff mr-10px" @click="onCancel">取消</n-button>
              <n-button color="#46299D" class="w-250px h-34px text-14px text-#fff" 
                @click="onSubmit" :disabled="isCanSubmit">发送</n-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
  </x-n-modal>

  <!-- 通讯录弹窗 -->
  <customModal
    v-model:show="state.isShowAddressBookModal"
    title="通讯录"
    :style="state.customModalStyle"
    :customCloseBtn="true"
    :closable="false"
    :customCloseEvent="true"
    @customCloseModal="closeAddressBookModal"
  >
    <template #content>
      <div class="custom-modal-content">
        <n-card style="padding: 0 12px">
          <n-tabs
            type="line"
            @update:value="handleAddressBookTabChange"
            tab-style="font-size: 16px; font-weight: 600;color: #8B8B8B;"
          >
            <n-tab name="employeeAddressBook">员工通讯录</n-tab>
            <n-tab name="groupChatList">群聊列表</n-tab>
          </n-tabs>
          <xSearchForm
            v-if="state.addressBookCurrentTab == 'employeeAddressBook'"
            :search-config="state.addressBookSearchConfig"
            customInputPlaceholder="请输入姓名"
            @change="changeAddressBookSearch"
            :cols="3"
          ></xSearchForm>
          <xSearchForm
            v-if="state.addressBookCurrentTab == 'groupChatList'"
            :search-config="state.groupChatListSearchConfig"
            customInputPlaceholder="请输入群聊名称"
            @change="changeGroupChatListSearch"
            :cols="3"
          ></xSearchForm>

          <div class="addressBook-content" v-if="state.addressBookCurrentTab == 'employeeAddressBook'">
            <div class="addressBook-tree" v-if="!state.addressBookSearchNickName">
              <fl-tree
                :data="state.treeData"
                :expandedKeys="state.expandedKeys"
                :refreshCount="state.treeRefreshCount"
                :clickKey="state.clickKey"
                @triggerTreeClick="handleTreeClick"
              ></fl-tree>
            </div>
            <div class="addressBook-table">
              <xNDataTable
                :columns="state.addressBookColumns"
                :data="state.addressBookData"
                :style="{
                  height: `${state.addressBookTableHeight}px`,
                  width: `${state.addressBookTableWidth}px`
                }"
                :row-key="row => row.ID"
                v-model:checked-row-keys="state.selectedRowKeys"
                flex-height
              ></xNDataTable>
              <div class="addressBook-pagination">
                <n-pagination
                  v-model:page="state.addressBookPage"
                  v-model:page-size="state.addressBookPageSize"
                  :item-count="state.addressBookTotal"
                  show-quick-jumper
                  show-size-picker
                  :page-sizes="[10, 20, 50]"
                  :on-update:page="handleAddressBookPagination"
                  :on-update:page-size="handleAddressBookPaginationSize"
                >
                  <template #prefix="{ itemCount }"> 共 {{ itemCount }} 条记录 </template>
                </n-pagination>
              </div>
            </div>
          </div>

          <div class="groupChatList-content" v-if="state.addressBookCurrentTab == 'groupChatList'">
            <div class="groupChatList-table">
              <xNDataTable
                :columns="state.groupChatListColumns"
                :data="state.groupChatListData"
                :style="{
                  height: '500px',
                  width: '1148px'
                }"
                   :row-key="row => row.id"
                v-model:checked-row-keys="state.selectedGroupRowKeys"
                flex-height
              ></xNDataTable>
              <div class="groupChatList-pagination">
                <n-pagination
                  v-model:page="state.groupChatListPage"
                  v-model:page-size="state.groupChatListPageSize"
                  :item-count="state.groupChatListTotal"
                  show-quick-jumper
                  show-size-picker
                  :page-sizes="[10, 20, 50]"
                  :on-update:page="handleGroupChatListPagination"
                  :on-update:page-size="handleGroupChatListPaginationSize"
                >
                  <template #prefix="{ itemCount }"> 共 {{ itemCount }} 条记录 </template>
                </n-pagination>
              </div>
            </div>
          </div>

          <!-- 底部操作按钮，仅保留展示 -->
          <div  style="display: flex; justify-content: center; align-items: center; padding: 10px 0;">
            <n-button color="#C7C7C9" class="w-200px h-34px text-14px text-#fff mr-10px" @click="onAddressBookCancel">取消</n-button>
            <n-button color="#46299D" class="w-200px h-34px text-14px text-#fff" @click="onAddressBookSubmit">发送</n-button>
          </div>
        </n-card>
      </div>
    </template>
  </customModal>
</template>

<style scoped lang="scss">
.custom-modal-content {
  .addressBook-content {
    display: flex;
    flex-direction: row;
    gap: 20px;

    .addressBook-tree {
      width: 328px;
      height: 500px;
      overflow: auto;
      border: 1px solid #efeff5;
      border-radius: 4px;
      padding: 12px 20px;
      box-sizing: border-box;
    }

    .addressBook-table {
      :deep(.n-data-table-th) {
        background-color: #46299d;
        color: #fff;
      }
      .addressBook-pagination {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        padding: 22px 0 0;
        box-sizing: border-box;
      }
    }
  }

  .groupChatList-content {
    display: flex;
    flex-direction: row;
    gap: 20px;

    .groupChatList-table {
      :deep(.n-data-table-th) {
        background-color: #46299d;
        color: #fff;
      }
      .groupChatList-pagination {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        padding: 22px 0 0;
        box-sizing: border-box;
      }
    }
  }
}
</style>
