<script setup lang="ts">
import type { Label } from '../types'
import { Plus, Delete } from '@element-plus/icons-vue'
import AppList from '@/components/base/AppList.vue'
import LabelType from '../components/LabelType.vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { getLabelList, deleteLabel, deleteLabels } from '../api'
import { useMapStore } from '@/stores/map'
import { getNameByValue, updateStatusRuleList, labelList } from '@/utils/dictionary'
import { useLabelType } from '../composables/useLabelType'
import SelectUser from '@/components/SelectUser.vue'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

const LabelFormDialog = defineAsyncComponent(() => import('../components/LabelFormDialog.vue'))
const LabelViewDialog = defineAsyncComponent(() => import('../components/LabelViewDialog.vue'))
const LabelRuleDialog = defineAsyncComponent(() => import('../components/LabelRuleDialog.vue'))
const AISummaryDialog = defineAsyncComponent(() => import('../components/AISummaryDialog.vue'))
const aiDialogVisible = ref(false)

const statusList = useMapStore().getMapValuesByKey('system_status')
const { typeList } = useLabelType()

const appList = $ref<InstanceType<typeof AppList> | null>(null)
// 列表配置
const listParams = reactive({ name: '', type_id: '', status: '', updated_operator: '' })
const listOptions = computed(() => {
  return {
    remote: {
      httpRequest: getLabelList,
      params: listParams,
      beforeRequest(params: any, isReset: boolean) {
        if (isReset) {
          listParams.updated_operator = ''
          listParams.type_id = ''
        } else {
          params.updated_operator = listParams.updated_operator
        }
        return params
      },
    },
    filters: [
      { type: 'input', prop: 'name', placeholder: '请输入标签名称' },
      {
        type: 'select',
        prop: 'type_id',
        placeholder: '请选择标签目录',
        options: typeList.value,
        labelKey: 'name',
        valueKey: 'id',
      },
      {
        type: 'select',
        prop: 'label',
        placeholder: '请选择标签类型',
        options: labelList,
      },
      { 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: 'label',
        computed({ row }: { row: Label }) {
          return getNameByValue(row.label, labelList) || row.label
        },
      },
      { label: '标签目录', prop: 'tag_type.name' },
      { label: '标签权重', prop: 'weight' },
      {
        label: '更新频率',
        prop: 'update_status',
        computed({ row }: { row: Label }) {
          return getNameByValue(row.update_status, updateStatusRuleList)
        },
      },
      {
        label: '状态',
        prop: 'status',
        computed({ row }: { row: Label }) {
          const color = row.status === '1' ? 'var(--main-success-color)' : 'var(--main-color)'
          return `<span style="color: ${color}">${getNameByValue(row.status, statusList)}</span>`
        },
      },
      {
        label: '更新人',
        prop: 'updated_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: 320 },
    ],
  }
})
// 刷新
function handleRefresh() {
  appList?.refetch()
}

let formVisible = $ref(false)
let currentRow = $ref<Label>()

// 新建
function handleAdd() {
  currentRow = undefined
  formVisible = true
}
// 修改
function handleUpdate(row: Label) {
  currentRow = row
  formVisible = true
}
// 删除
function handleRemove(row: Label) {
  ElMessageBox.confirm('确定要删除该标签吗？', '提示').then(() => {
    deleteLabel({ id: row.id }).then(() => {
      ElMessage({ message: '删除成功', type: 'success' })
      handleRefresh()
    })
  })
}
// 查看
let viewVisible = $ref(false)
function handleView(row: Label) {
  currentRow = row
  viewVisible = true
}
// 规则
let ruleVisible = $ref(false)
function handleRule(row: Label) {
  currentRow = row
  ruleVisible = true
}

function handleSelect(id: string) {
  listParams.type_id = id
  nextTick(() => {
    appList?.refetch()
  })
}

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

const handleRemoves = async function () {
  const ids = multipleSelection.map((item) => item.id)
  await ElMessageBox.confirm('确定要删除选中的标签数据吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
  await deleteLabels({ ids: JSON.stringify(ids) })
  appList?.refetch(true)
  ElMessage({ message: '删除成功', type: 'success' })
}
</script>

<template>
  <AppCard>
    <div class="label-wrap">
      <div class="label-left"><LabelType :active-id="listParams.type_id" @select="handleSelect"></LabelType></div>
      <AppList v-bind="listOptions" ref="appList" class="label-right" @selection-change="handleSelectionChange">
        <template #header-buttons>
          <div style="display: flex; justify-content: space-between">
            <div>
              <el-button type="primary" :icon="Plus" @click="handleAdd" v-if="!userStore.status.tag_status"
                >新建</el-button
              >
              <el-button
                type="primary"
                plain
                :icon="Delete"
                :disabled="!multipleSelection.length"
                @click="handleRemoves"
                v-permission="'experiment_tag_delete'"
                >删除</el-button
              >
            </div>
            <el-button type="primary" @click="aiDialogVisible = true">AI建议</el-button>
          </div>
        </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="handleRule(row)">规则</el-button>
          <el-button type="primary" plain @click="handleView(row)">查看</el-button>
          <el-button type="primary" plain @click="handleUpdate(row)" v-permission="'experiment_tag_update'"
            >编辑</el-button
          >
          <el-button type="primary" plain @click="handleRemove(row)" v-permission="'experiment_tag_delete'"
            >删除</el-button
          >
        </template>
      </AppList>
    </div>
  </AppCard>
  <!-- 新建/修改标签 -->
  <LabelFormDialog
    v-model="formVisible"
    :data="currentRow"
    @update="handleRefresh"
    v-if="formVisible"></LabelFormDialog>
  <!-- 查看标签 -->
  <LabelViewDialog v-model="viewVisible" :data="currentRow" v-if="viewVisible && currentRow"></LabelViewDialog>
  <!-- 规则 -->
  <LabelRuleDialog v-model="ruleVisible" :data="currentRow" v-if="ruleVisible && currentRow"></LabelRuleDialog>
  <AISummaryDialog v-model="aiDialogVisible" v-if="aiDialogVisible"></AISummaryDialog>
</template>

<style lang="scss">
.label-wrap {
  height: calc(100vh - 130px);
  display: flex;
}
.label-left {
  padding-right: 20px;
  margin-right: 20px;
  flex: 0 0 200px;
  border-right: 1px solid rgb(187, 187, 187);
  overflow-x: hidden;
  overflow-y: auto;
}
.label-right {
  flex: 1;
  overflow-x: hidden;
  overflow-y: auto;
}
</style>
