<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <el-row class="ml10 mb8">
        <el-form :inline="true" :model="queryForm" @keyup.enter="getDataList" ref="queryRef">
          <el-form-item :label="$t('institutionalCenter.attachmentName')">
            <el-input v-model="queryForm.attachmentName" :placeholder="$t('institutionalCenter.inputPlaceholder')" style="max-width:240px" />
          </el-form-item>
          <el-form-item>
            <el-button icon="search" type="primary" @click="getDataList">{{ $t('common.queryBtn') }}</el-button>
            <el-button icon="Refresh" @click="resetQuery">{{ $t('common.resetBtn') }}</el-button>
          </el-form-item>
        </el-form>
      </el-row>

      <el-row>
        <div class="mb8" style="width:100%">
          <el-button v-if="!isReadonly" class="ml10" type="primary" icon="folder-add" @click="openAddDialog">{{ $t('common.addBtn') }}</el-button>
          <right-toolbar style="float: right; margin-right:20px" @queryTable="getDataList" />
        </div>
      </el-row>

      <el-table :data="state.dataList" style="width:100%" v-loading="state.loading" border row-key="id">
        <el-table-column type="index" label="#" width="60" />
        <el-table-column prop="attachmentName" :label="$t('institutionalCenter.table.attachmentName')" />
        <el-table-column prop="downloadNum" :label="$t('institutionalCenter.table.downloadNum')" />
        <el-table-column prop="createBy" :label="$t('institutionalCenter.table.uploader')" />
        <el-table-column prop="createTime" :label="$t('institutionalCenter.table.uploadTime')" width="180" />
        <el-table-column :label="$t('common.action')" width="200">
          <template #default="{ row }">
            <el-button text size="small" type="primary" icon="download" @click="handleDownload(row)">{{ $t('common.download') }}</el-button>
            <el-button v-if="!isReadonly" text size="small" type="primary" icon="delete" @click="handleDelete(row.id)">{{ $t('common.delBtn') }}</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-bind="state.pagination" @current-change="currentChangeHandle" @size-change="sizeChangeHandle" />

      <!-- Add Dialog -->
      <el-dialog :title="$t('institutionalCenter.add.title')" v-model="addDialogVisible" width="540px">
        <div>
          <el-form ref="addFormRef" :model="addForm">
            <el-form-item>
              <UploadFile :fileSize="5" :fileType="['pdf']" :limit="1" @change="handleFileChange" />
              <!-- <div class="mt8 text-gray-500 text-sm">{{ $t('institutionalCenter.add.hint') }}</div> -->
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <el-button @click="addDialogVisible = false">{{ $t('institutionalCenter.add.cancel') }}</el-button>
          <el-button type="primary" @click="submitAdd" :loading="addLoading">{{ $t('institutionalCenter.add.confirm') }}</el-button>
        </template>
      </el-dialog>

    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { useI18n } from 'vue-i18n';
import { BasicTableProps, useTable } from '/@/hooks/table';
import UploadFile from '/@/components/Upload/index.vue';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { fetchCompanyPoliciesPage, addCompanyPolicy, downloadCompanyPolicyCount, deleteCompanyPolicies } from '/@/api/config/institutionalCenter';
import type { CompanyPolicyItem } from '/@/api/config/institutionalCenter/types';
import { useRoute } from 'vue-router'

const { t } = useI18n();
const route = useRoute()
const message = useMessage();

// query form
const queryForm = reactive({ attachmentName: '' });

const state: BasicTableProps = reactive({
  queryForm,
  pageList: fetchCompanyPoliciesPage,
});

const { getDataList, currentChangeHandle, sizeChangeHandle, downBlobFile } = useTable(state);

// dialog / add
const addDialogVisible = ref(false);
const addFormRef = ref();
const addLoading = ref(false);
const addForm = reactive({ attachmentName: '', attachmentUrl: '' });

const openAddDialog = () => {
  addForm.attachmentName = '';
  addForm.attachmentUrl = '';
  addDialogVisible.value = true;
};

const handleFileChange = (url: string, files: File[]) => {
  if (files && files.length) {
    addForm.attachmentName = files[0].name;
    addForm.attachmentUrl = url;
  } else {
    addForm.attachmentName = '';
    addForm.attachmentUrl = '';
  }
}

const submitAdd = async () => {
  if (!addForm.attachmentUrl) {
    message.warning(t('institutionalCenter.add.uploadRequired'));
    return;
  }

  addLoading.value = true;
  try {
    await addCompanyPolicy(addForm);
    message.success(t('common.addSuccess') || '添加成功');
    addDialogVisible.value = false;
    getDataList();
  } catch (err: any) {
    message.error(err?.msg || err?.message || t('common.operateFail') || '提交失败');
  } finally {
    addLoading.value = false;
  }
};

const extractFileName = (url: string) => {
  if (!url) return '';
  if (url.includes('fileName=')) return decodeURIComponent(url.split('fileName=')[1]);
  return url.split('/').pop() || url;
};

const handleDelete = async (ids: string) => {
  try {
    await useMessageBox().confirm(t('common.delConfirmText'));
  } catch {
    return;
  }

  try {
    await deleteCompanyPolicies(ids);
    message.success(t('common.delSuccessText'));
    getDataList();
  } catch (err: any) {
    message.error(err?.msg || err?.message || t('common.operateFail'));
  }
};

const handleDownload = async (row: CompanyPolicyItem) => {
  if (!row?.id || !row.attachmentUrl) return;
  try {
    await downloadCompanyPolicyCount(row.id);
  } catch (e) {
    // ignore counting errors
  }
  // 下载文件
  downBlobFile(row.attachmentUrl!, {}, row.attachmentName || extractFileName(row.attachmentUrl!));
  getDataList()
};

const resetQuery = () => {
  queryForm.attachmentName = '';
  getDataList();
};

const isReadonly = ref(false)
onMounted(() => {
  isReadonly.value = route.query.from === 'workbench'
})

// initial fetch
getDataList();
</script>

<style scoped>
.layout-container .layout-padding-view {
  overflow: auto;
}
</style>
