<script setup lang="ts">
import type { Group } from '../types'
import { Plus, Delete } from '@element-plus/icons-vue'
import AppList from '@/components/base/AppList.vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { getNameByValue, groupTypeList, updateStatusRuleList } from '@/utils/dictionary'
import { getGroupList, deleteGroup } from '../api'
import { useMapStore } from '@/stores/map'
import SelectUser from '@/components/SelectUser.vue'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

const FormDialog = defineAsyncComponent(() => import('../components/FormDialog.vue'))
const ViewDialog = defineAsyncComponent(() => import('../components/ViewDialog.vue'))

const statusList = useMapStore().getMapValuesByKey('system_status')

const appList = $ref<InstanceType<typeof AppList> | null>(null)
// 列表配置
const listParams = reactive({ name: '', id: '', status: '', updated_operator: '' })
const listOptions = computed(() => {
  return {
    remote: {
      httpRequest: getGroupList,
      params: listParams,
      beforeRequest(params: any, isReset: boolean) {
        if (isReset) listParams.updated_operator = ''
        params.updated_operator = listParams.updated_operator
        return params
      }
    },
    filters: [
      { type: 'input', prop: 'name', placeholder: '请输入群组名称' },
      { type: 'input', prop: 'id', placeholder: '请输入群组ID' },
      { type: 'select', prop: 'status', placeholder: '请选择群组状态', options: statusList },
      { type: 'input', prop: 'updated_operator', placeholder: '更新人', slots: 'filter-user' }
    ],
    columns: [
      { type: 'selection' },
      { label: '序号', type: 'index', width: 60 },
      { label: '群组ID', prop: 'id' },
      { label: '群组名称', prop: 'name' },
      {
        label: '群组类型',
        prop: 'type',
        computed({ row }: { row: Group }) {
          return getNameByValue(row.type, groupTypeList)
        }
      },
      {
        label: '更新方式',
        prop: 'update_status',
        computed({ row }: { row: Group }) {
          return getNameByValue(row.update_status, updateStatusRuleList)
        }
      },
      { label: '最近计算完成时间', prop: 'record.updated_time' },
      {
        label: '状态',
        prop: 'status',
        computed({ row }: { row: Group }) {
          const color = row.status === '1' ? 'var(--main-success-color)' : 'var(--main-color)'
          return `<span style="color: ${color}">${getNameByValue(row.status, statusList)}</span>`
        }
      },
      {
        label: '更新人',
        prop: 'created_operator.real_name',
        computed({ row }: any) {
          return row.updated_operator?.real_name || row.updated_operator?.nickname
        }
      },
      { label: '更新时间', prop: 'updated_time' },
      { label: '操作', slots: 'table-x', width: 240 }
    ]
  }
})

// 刷新
function handleRefresh() {
  appList?.refetch()
}

let multipleSelection = $ref<Group[]>([])
function handleSelectionChange(selection: Group[]) {
  multipleSelection = selection
}

let formVisible = $ref(false)
let currentRow = $ref<Partial<Group>>()

// 新建
function handleAdd(type: '1' | '2' | '3') {
  currentRow = { type }
  formVisible = true
}
// 修改
function handleUpdate(row: Group) {
  currentRow = row
  formVisible = true
}
// 删除
function handleRemove(rows: Group[]) {
  ElMessageBox.confirm(rows.length > 1 ? '确定要删除勾选群组吗？' : '确定要删除该群组吗？', '提示').then(() => {
    const ids = rows.map(item => item.id)
    deleteGroup({ ids }).then(() => {
      ElMessage({ message: '删除成功', type: 'success' })
      handleRefresh()
    })
  })
}
let viewVisible = $ref(false)
// 查看
function handleView(row: Group) {
  currentRow = row
  viewVisible = true
}
</script>

<template>
  <AppCard>
    <AppList v-bind="listOptions" ref="appList" @selection-change="handleSelectionChange">
      <template #header-buttons>
        <el-space>
          <!-- v-permission="['experiment_group_create_dynamic_group', 'experiment_group_create_static_group']" -->
          <el-dropdown>
            <el-button type="primary" :icon="Plus" v-if="!userStore.status.group_status">新建</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleAdd('2')">新建动态群组</el-dropdown-item>
                <el-dropdown-item @click="handleAdd('1')">新建静态群组</el-dropdown-item>
                <!--<el-dropdown-item @click="handleAdd('3')">新建RFM群组</el-dropdown-item>-->
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button
            type="danger"
            plain
            :icon="Delete"
            :disabled="!multipleSelection.length"
            @click="handleRemove(multipleSelection)"
            v-permission="'experiment_group_delete'"
            >删除</el-button
          >
        </el-space>
      </template>
      <template #filter-user>
        <SelectUser v-model="listParams.updated_operator" placeholder="更新人" @change="handleRefresh"></SelectUser>
      </template>

      <template #table-x="{ row }">
        <el-button type="primary" plain @click="handleView(row)">查看</el-button>
        <el-button
          type="primary"
          plain
          @click="handleUpdate(row)"
          v-permission="['experiment_group_create_dynamic_group', 'experiment_group_update_static_group']"
          >编辑</el-button
        >
        <el-button type="primary" plain @click="handleRemove([row])" v-permission="'experiment_group_delete'"
          >删除</el-button
        >
      </template>
    </AppList>
  </AppCard>

  <!-- 新建/修改群组 -->
  <FormDialog
    v-model="formVisible"
    :data="currentRow"
    @update="handleRefresh"
    v-if="formVisible && currentRow"
  ></FormDialog>
  <!-- 查看 -->
  <ViewDialog v-model="viewVisible" :data="(currentRow as Group)" v-if="viewVisible && currentRow"></ViewDialog>
</template>
