<script setup lang="tsx">
import { ref, withDirectives } from 'vue';
import { NButton, NPopconfirm, NSwitch } from 'naive-ui';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import {
  addOssConfig,
  changeOssConfigStatus,
  delOssConfig,
  getOssConfig,
  listOssConfig,
  updateOssConfig
} from '@/service/api/system/oss-config';
import { getDicts } from '@/service/api/system/dict';
import type { ModelCallback } from '@/hooks/common/form';
import OssConfigSearch from '@/views/system/oss/modules/oss-config-search.vue';
import OssConfigOperateModal from '@/views/system/oss/modules/oss-config-operate-modal.vue';
import hasPermission from '@/directive/permission/hasPermission';

defineOptions({
  name: 'OssConfig'
});

const isHttpsOptions = ref<Api.SystemManage.DictInfo[]>([]);
const statusOptions = ref<Api.SystemManage.DictInfo[]>([]);

getDicts('sys_yes_no').then(response => {
  if (!response.error) {
    isHttpsOptions.value = response.data as Api.SystemManage.DictInfo[];
  }
});
getDicts('sys_normal_disable').then(response => {
  if (!response.error) {
    statusOptions.value = response.data as Api.SystemManage.DictInfo[];
  }
});

const visible = ref(false);

const {
  columns,
  columnChecks,
  data,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: listOssConfig,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    configKey: null, // 配置Key
    bucketName: null, // 存储桶名称
    status: null // 状态
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'configKey',
      title: '配置Key',
      align: 'center'
    },
    {
      key: 'endpoint',
      title: '访问站点',
      align: 'center'
    },
    {
      key: 'bucketName',
      title: '桶名称',
      align: 'center'
    },
    {
      key: 'prefix',
      title: '前缀',
      align: 'center'
    },
    {
      key: 'region',
      title: '域',
      align: 'center'
    },
    {
      key: 'status',
      title: '状态',
      align: 'center',
      render: row => {
        if (row.status === null) {
          return null;
        }
        return (
          <NSwitch
            v-model:value={row.status}
            checked-value="0"
            unchecked-value="1"
            onUpdate:value={() => handleStatusChange(row)}
          />
        );
      }
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 200,
      render: row => (
        <div class="flex-center gap-8px">
          {withDirectives(
            <NButton type="primary" ghost size="small" onClick={() => edit(row.ossConfigId)}>
              编辑
            </NButton>,
            [[hasPermission, ['system:oss:edit']]]
          )}
          {withDirectives(
            <div>
              <NPopconfirm onPositiveClick={() => handleDelete(row.ossConfigId)}>
                {{
                  default: () => $t('common.confirmDelete'),
                  trigger: () => (
                    <NButton type="error" ghost size="small">
                      {$t('common.delete')}
                    </NButton>
                  )
                }}
              </NPopconfirm>
            </div>,
            [[hasPermission, ['system:oss:remove']]]
          )}
        </div>
      )
    }
  ]
});

const { drawerVisible, operateType, editingData, checkedRowKeys, handleAdd, handleEdit, onDeleted, onBatchDeleted } =
  useTableOperate(data, getData);

// 单个删除
function handleDelete(id: Api.SystemManage.OssConfig['ossConfigId']) {
  delOssConfig([id]).then(res => {
    if (!res.error) {
      onDeleted();
    }
  });
}

// 批量删除
function handleBatchDelete() {
  delOssConfig(checkedRowKeys.value as Api.SystemManage.OssConfig['ossConfigId'][]).then(res => {
    if (!res.error) {
      onBatchDeleted();
    }
  });
}

// 编辑
async function edit(id: Api.SystemManage.OssConfig['ossConfigId']) {
  getOssConfig(id).then(res => {
    if (!res.error) {
      editingData.value = res.data;
      handleEdit();
    }
  });
}

// 提交
function handleSubmit(callback: (params: ModelCallback<Api.SystemManage.OssConfig>) => void) {
  callback({
    add: addOssConfig,
    edit: updateOssConfig,
    getData
  });
}

function handleStatusChange(row: Api.SystemManage.OssConfig) {
  const text = row.status === '0' ? '启用' : '停用';
  window.$dialog?.warning({
    title: '提示',
    content: `确定要${text}"${row.configKey}"配置吗？`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      return changeOssConfigStatus(row.ossConfigId, row.status, row.configKey)
        .then(() => {
          window.$message?.success(`${text}成功`);
        })
        .catch(() => {
          row.status = row.status === '0' ? '1' : '0';
        });
    },
    onNegativeClick: () => {
      row.status = row.status === '0' ? '1' : '0';
    },
    onClose: () => {
      row.status = row.status === '0' ? '1' : '0';
    },
    onEsc: () => {
      row.status = row.status === '0' ? '1' : '0';
    }
  });
}

function handleOpen() {
  visible.value = true;
}
</script>

<template>
  <div>
    <NButton v-hasPermission="['system:oss:list']" type="info" ghost size="small" @click="handleOpen">
      <template #icon>
        <SvgIcon icon="ep:operation"></SvgIcon>
      </template>
      配置管理
    </NButton>

    <NModal v-model:show="visible" title="配置管理" preset="card" class="w-1200px">
      <OssConfigSearch
        v-model:model="searchParams"
        :status-options="statusOptions"
        @reset="resetSearchParams"
        @search="getDataByPage"
      />

      <NCard title="配置管理列表" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
        <template #header-extra>
          <TableHeaderOperation
            v-model:columns="columnChecks"
            :disabled-delete="checkedRowKeys.length === 0"
            :loading="loading"
            :has-perm="['system:oss:add', 'system:oss:remove']"
            @add="handleAdd"
            @delete="handleBatchDelete"
            @refresh="getData"
          />
        </template>
        <NDataTable
          v-model:checked-row-keys="checkedRowKeys"
          :columns="columns"
          :data="data"
          size="small"
          :loading="loading"
          remote
          :row-key="({ ossConfigId }) => ossConfigId"
          :pagination="mobilePagination"
          class="sm:h-full"
        />
        <OssConfigOperateModal
          v-model:visible="drawerVisible"
          :operate-type="operateType"
          :row-data="editingData"
          :status-options="statusOptions"
          :is-https-options="isHttpsOptions"
          @submit="handleSubmit"
        />
      </NCard>
    </NModal>
  </div>
</template>

<style scoped></style>
