<script setup lang="ts">
import type { Group, GroupMember } from '../types'
import { UserFilled, Plus, Delete } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import AppList from '@/components/base/AppList.vue'
import { getNameByValue, groupTypeList, updateStatusRuleList, updateStatusList } from '@/utils/dictionary'
import { useMapStore } from '@/stores/map'
import { getGroupStatistics, getGroupMembers, clearGroupMembers, updateGroupStatistics } from '../api'
import BindMembers from './BindMembers.vue'

const props = defineProps<{
  data: Group
}>()

defineEmits<{
  (e: 'update'): void
  (e: 'update:modelValue', visible: boolean): void
}>()

const statusList = useMapStore().getMapValuesByKey('system_status')
const genderList = useMapStore().getMapValuesByKey('system_gender')
const connectionTypeList = useMapStore().getMapValuesByKey('experiment_connection_type')

const detail = reactive({ count: 0, status: '1', updated_time: '-' })
function fetchInfo() {
  getGroupStatistics({ group_id: props.data.id }).then(res => {
    Object.assign(detail, res.data.detail)
  })
}
watchEffect(() => fetchInfo())

// 立即更新
function handleUpdate() {
  updateGroupStatistics({ id: props.data.id }).then(() => {
    ElMessage({ type: 'success', message: '更新成功' })
    fetchInfo()
  })
}

// 清空群组成员
function handleClearMembers() {
  ElMessageBox.confirm('确定要删清空该群组成员吗？', '提示').then(() => {
    clearGroupMembers({ group_id: props.data.id }).then(() => {
      ElMessage({ message: '清空成功', type: 'success' })
      handleRefresh()
    })
  })
}
// 添加群组成员
const selectMembersVisible = ref(false)
function handleAdd() {
  selectMembersVisible.value = true
}

const appList = ref<InstanceType<typeof AppList> | null>(null)
// 列表配置
const listOptions = computed(() => {
  return {
    remote: {
      httpRequest: getGroupMembers,
      params: { group_id: props.data.id }
    },
    columns: [
      { label: '序号', type: 'index', width: 60 },
      { label: '用户ID', prop: 'id' },
      { label: '姓名', prop: 'name' },
      {
        label: '性别',
        prop: 'gender',
        computed({ row }: { row: GroupMember }) {
          return getNameByValue(row.gender, genderList)
        }
      },
      { label: '手机号码', prop: 'mobile' },
      {
        label: '来源连接',
        prop: 'experiment_connection_id',
        computed({ row }: { row: GroupMember }) {
          return getNameByValue(row.connection.type.toString(), connectionTypeList)
        }
      },
      {
        label: '状态',
        prop: 'status',
        computed({ row }: { row: GroupMember }) {
          return getNameByValue(row.status, statusList)
        }
      },
      { label: '更新人', prop: 'updated_operator.real_name' },
      { label: '更新时间', prop: 'updated_time' },
      { label: '操作', slots: 'table-x' }
    ]
  }
})
// 刷新
function handleRefresh() {
  fetchInfo()
  appList.value?.refetch()
}
</script>

<template>
  <el-dialog title="查看群组信息" width="1000px" @closed="$emit('update:modelValue', false)">
    <el-form label-suffix="：" label-width="82px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="群组名称">{{ data.name }}</el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="群组类型">{{ getNameByValue(data.type, groupTypeList) }}</el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="更新频率">{{ getNameByValue(data.update_status, updateStatusRuleList) }}</el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态">
            <span :style="`color:${data.status === '1' ? 'var(--main-success-color)' : 'var(--main-color)'}`">
              {{ getNameByValue(data.status, statusList) }}
            </span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-card>
      <div class="group-box">
        <dl>
          <dt>群组人数</dt>
          <dd class="label-box__count">
            <el-icon><UserFilled></UserFilled></el-icon>
            <span>{{ detail.count }}人</span>
          </dd>
        </dl>
        <template v-if="data.type === '1'">
          <dl>
            <dt></dt>
            <dd>
              <el-button type="danger" :icon="Delete" @click="handleClearMembers">清空用户群组</el-button>
              <el-button type="primary" :icon="Plus" @click="handleAdd">添加用户</el-button>
            </dd>
          </dl>
        </template>
        <template v-else>
          <dl>
            <dt>最后更新时间</dt>
            <dd>{{ detail.updated_time }}</dd>
          </dl>
          <dl>
            <dt>更新状态</dt>
            <dd>
              <span style="margin-right: 10px">{{ getNameByValue(detail.status.toString(), updateStatusList) }}</span>
              <el-button
                type="primary"
                plain
                @click="handleUpdate"
                size="small"
                :disabled="['2', '4'].includes(detail.status.toString())"
                >立即更新</el-button
              >
            </dd>
          </dl>
        </template>
      </div>
    </el-card>
    <el-card style="margin-top: 20px">
      <template #header>群组用户</template>
      <AppList v-bind="listOptions" ref="appList">
        <template #table-x="{ row }">
          <el-button type="primary" plain>
            <router-link
              target="_blank"
              :to="{ path: '/user/image', query: { user_id: row.id, experiment_id: row.experiment_id } }"
              >查看</router-link
            >
          </el-button>
        </template>
      </AppList>
    </el-card>

    <template #footer>
      <el-row justify="center">
        <el-button plain auto-insert-space @click="$emit('update:modelValue', false)">关闭</el-button>
      </el-row>
    </template>
    <BindMembers
      :data="data"
      v-model="selectMembersVisible"
      @update="handleRefresh"
      v-if="selectMembersVisible"></BindMembers>
  </el-dialog>
</template>

<style lang="scss">
.group-box {
  display: flex;
  justify-content: space-between;
  dt {
    margin-bottom: 10px;
    text-align: center;
  }
  dd {
    display: flex;
    align-items: center;
    justify-content: center;
    span {
      padding: 0 5px;
    }
  }
}
.group-box__count {
  font-weight: bold;
  color: var(--main-color);
}
</style>
