<script setup lang="ts">
import type { Strategy } from '../types'
import { Plus, Delete } from '@element-plus/icons-vue'
import AppList from '@/components/base/AppList.vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { getStrategyList, deleteStrategy } from '../api'
import { useMapStore } from '@/stores/map'
import { getNameByValue, updateStatusRuleList } from '@/utils/dictionary'
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 typeList = useMapStore().getMapValuesByKey('strategy_type')
const industryList = useMapStore().getMapValuesByKey('strategy_industry')
const statusList = useMapStore().getMapValuesByKey('system_status')

const appList = $ref<InstanceType<typeof AppList> | null>(null)
// 列表配置
const listParams = reactive({ name: '', type_id: '', status: '', updated_operator: '' })
const listOptions = computed(() => {
  return {
    remote: {
      httpRequest: getStrategyList,
      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: 'industry',
        placeholder: '请选择策略行业',
        options: industryList,
      },
      {
        type: 'select',
        prop: 'type',
        placeholder: '请选择策略类型',
        options: typeList,
      },
      { 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: Strategy }) {
          return getNameByValue(row.type, typeList)
        },
      },
      {
        label: '策略行业',
        prop: 'industry',
        computed({ row }: { row: Strategy }) {
          return getNameByValue(row.industry, industryList)
        },
      },
      {
        label: '更新频率',
        prop: 'update_status',
        computed({ row }: { row: Strategy }) {
          return getNameByValue(row.update_status, updateStatusRuleList)
        },
      },
      {
        label: '状态',
        prop: 'status',
        computed({ row }: { row: Strategy }) {
          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_name',
      },
      { label: '更新时间', prop: 'updated_time' },
      { label: '操作', slots: 'table-x', width: 320 },
    ],
  }
})
// 刷新
function handleRefresh() {
  appList?.refetch()
}

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

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

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

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

<template>
  <AppCard>
    <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>
        </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="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>
  </AppCard>
  <!-- 新建/修改策略 -->
  <FormDialog v-model="formVisible" :data="currentRow" @update="handleRefresh" v-if="formVisible"></FormDialog>
  <!-- 查看策略 -->
  <ViewDialog v-model="viewVisible" :data="currentRow" v-if="viewVisible && currentRow"></ViewDialog>
</template>
