<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="步骤记录" prop="stepRecordId">
              <el-input v-model="queryParams.stepRecordId" placeholder="请输入步骤记录ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="媒体类型" prop="mediaType">
              <el-select v-model="queryParams.mediaType" placeholder="请选择媒体类型" clearable>
                <el-option label="图片" value="image" />
                <el-option label="视频" value="video" />
                <el-option label="音频" value="audio" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['inspection:stepMedia:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['inspection:stepMedia:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['inspection:stepMedia:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="stepMediaList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="预览" align="center" width="100">
          <template #default="scope">
            <el-image
              v-if="scope.row.mediaType === 'image'"
              :src="scope.row.fileUrl"
              :preview-src-list="[scope.row.fileUrl]"
              fit="cover"
              style="width: 60px; height: 60px"
            />
            <el-icon v-else-if="scope.row.mediaType === 'video'" :size="40" color="#409eff">
              <VideoPlay />
            </el-icon>
            <el-icon v-else :size="40" color="#67c23a">
              <Microphone />
            </el-icon>
          </template>
        </el-table-column>
        <el-table-column label="文件名称" align="center" prop="fileName" :show-overflow-tooltip="true" />
        <el-table-column label="媒体类型" align="center" prop="mediaType" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.mediaType === 'image'" type="success">图片</el-tag>
            <el-tag v-else-if="scope.row.mediaType === 'video'" type="primary">视频</el-tag>
            <el-tag v-else type="warning">音频</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="文件大小" align="center" prop="fileSize" width="120">
          <template #default="scope">{{ formatFileSize(scope.row.fileSize) }}</template>
        </el-table-column>
        <el-table-column label="上传时间" align="center" prop="uploadTime" width="180" />
        <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="下载" placement="top">
              <el-button link type="primary" icon="Download" @click="handleDownload(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['inspection:stepMedia:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>

    <!-- 添加步骤媒体文件对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="600px" append-to-body>
      <el-form ref="stepMediaFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="步骤记录ID" prop="stepRecordId">
          <el-input v-model="form.stepRecordId" placeholder="请输入步骤记录ID" />
        </el-form-item>
        <el-form-item label="媒体类型" prop="mediaType">
          <el-radio-group v-model="form.mediaType">
            <el-radio value="image">图片</el-radio>
            <el-radio value="video">视频</el-radio>
            <el-radio value="audio">音频</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="文件URL" prop="fileUrl">
          <el-input v-model="form.fileUrl" placeholder="请输入文件URL" />
        </el-form-item>
        <el-form-item label="文件名称" prop="fileName">
          <el-input v-model="form.fileName" placeholder="请输入文件名称" />
        </el-form-item>
        <el-form-item label="文件大小" prop="fileSize">
          <el-input-number v-model="form.fileSize" :min="0" controls-position="right" style="width: 100%" />
          <span class="ml-2 text-gray-500">字节</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ArStepMedia" lang="ts">
import { VideoPlay, Microphone } from '@element-plus/icons-vue';
import { listArStepMedia, getArStepMedia, delArStepMedia, addArStepMedia } from '@/api/inspection/stepMedia';
import { ArStepMediaVO, ArStepMediaQuery, ArStepMediaForm } from '@/api/inspection/stepMedia/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const stepMediaList = ref<ArStepMediaVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const stepMediaFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ArStepMediaForm = {
  id: undefined,
  stepRecordId: undefined,
  mediaType: 'image',
  fileUrl: undefined,
  fileName: undefined,
  fileSize: undefined
};

const data = reactive<PageData<ArStepMediaForm, ArStepMediaQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    stepRecordId: undefined,
    mediaType: undefined,
    uploadTimeBegin: undefined,
    uploadTimeEnd: undefined
  },
  rules: {
    stepRecordId: [{ required: true, message: '步骤记录ID不能为空', trigger: 'blur' }],
    mediaType: [{ required: true, message: '媒体类型不能为空', trigger: 'change' }],
    fileUrl: [{ required: true, message: '文件URL不能为空', trigger: 'blur' }],
    fileName: [{ required: true, message: '文件名称不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 格式化文件大小 */
const formatFileSize = (size: number) => {
  if (!size) return '-';
  if (size < 1024) return size + ' B';
  if (size < 1024 * 1024) return (size / 1024).toFixed(2) + ' KB';
  if (size < 1024 * 1024 * 1024) return (size / (1024 * 1024)).toFixed(2) + ' MB';
  return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
};

/** 查询步骤媒体文件列表 */
const getList = async () => {
  loading.value = true;
  const res = await listArStepMedia(queryParams.value);
  stepMediaList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  stepMediaFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ArStepMediaVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加步骤媒体文件';
};

/** 下载文件 */
const handleDownload = (row: ArStepMediaVO) => {
  window.open(row.fileUrl, '_blank');
};

/** 提交按钮 */
const submitForm = () => {
  stepMediaFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      await addArStepMedia(form.value).finally(() => (buttonLoading.value = false));
      proxy?.$modal.msgSuccess('新增成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ArStepMediaVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除步骤媒体文件编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delArStepMedia(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'inspection/stepMedia/export',
    {
      ...queryParams.value
    },
    `ar_step_media_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
