<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="versionName">
              <el-input v-model="queryParams.versionName" placeholder="请输入版本名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="发布日期" prop="releaseDate">
              <el-date-picker clearable v-model="queryParams.releaseDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择发布日期" />
            </el-form-item>
            <el-form-item label="下载链接" prop="downloadLink">
              <el-input v-model="queryParams.downloadLink" placeholder="请输入下载链接" clearable @keyup.enter="handleQuery" />
            </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="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['business:versionManagement:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['business:versionManagement:edit']"
            >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPermi="['business:versionManagement:remove']"
            >删除</el-button
            >
          </el-col>
          <!--          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['business:versionManagement:export']">导出</el-button>
          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="versionManagementList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" align="center" prop="id" v-if="true" />
        <el-table-column label="版本号" align="center" prop="versionCode" />
        <el-table-column label="版本名称" align="center" prop="versionName" />
        <el-table-column label="下载链接" align="center" prop="downloadLink" />
        <el-table-column label="主要更新内容" align="center" width="180">
          <template #default="scope">
            <el-tooltip :content="scope.row.updateContent" placement="top">
              <span class="truncate">{{ scope.row.updateContent }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <!--        <el-table-column label="已知问题" align="center" width="180">
          <template #default="scope">
            <el-tooltip :content="scope.row.knownIssues" placement="top">
              <span class="truncate">{{ scope.row.knownIssues }}</span>
            </el-tooltip>
          </template>
        </el-table-column>-->
        <el-table-column label="操作系统类型" align="center" prop="osType" />
        <!--        <el-table-column label="系统版本" align="center" prop="osSupport" />-->
        <el-table-column label="是否强制更新" align="center">
          <template #default="scope">
            {{ formatForceUpdate(scope.row.forceUpdate) }}
          </template>
        </el-table-column>
        <!--        <el-table-column label="更新包大小" align="center" prop="updatePackageSize" />-->
        <el-table-column label="状态" align="center">
          <template #default="scope">
            {{ formatStatus(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column label="发布日期" align="center" prop="releaseDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.releaseDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:versionManagement:edit']"
              >修改</el-button
              >
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:versionManagement:remove']"
              >删除</el-button
              >
            </el-tooltip>
            <el-tooltip content="生成下载链接" placement="top">
              <el-button link type="primary" icon="Edit" @click="generateAppDownLoadFile2(scope.row)" v-hasPermi="['business:versionManagement:edit']"
              >生成下载链接</el-button
              >
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改App版本管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="700px" append-to-body>
      <el-form ref="versionManagementFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="版本号" prop="versionCode">
          <el-input v-model="form.versionCode" placeholder="请输入版本号" />
        </el-form-item>
        <el-form-item label="版本名称" prop="versionName">
          <el-input v-model="form.versionName" placeholder="请输入版本名称" />
        </el-form-item>

        <el-form-item label="文件" prop="icon">
          <div class="upload-container">
            <el-upload
              class="upload-icon"
              action="#"
              :on-change="handleIconChange"
              :on-remove="handleIconRemove"
              :file-list="fileList"
              :auto-upload="false"
              :limit="1"
              accept=".apk,.ipa"
            >
              <template #trigger>
                <el-button type="primary">点击选择</el-button>
              </template>
              <template #tip>
                <div class="el-upload__tip">
                  <span v-if="fileList.length > 0">当前已选文件：{{ fileList[0].name }}</span>
                </div>
              </template>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="下载链接" prop="downloadLink">
          <el-input v-model="form.downloadLink" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="发布日期" prop="releaseDate">
          <el-date-picker clearable v-model="form.releaseDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择发布日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="系统类型" prop="osType">
          <el-radio-group v-model="form.osType" size="small">
            <el-radio v-for="dict in mobile_sys_type" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否强制更新" prop="forceUpdate">
          <el-radio-group v-model="form.forceUpdate" size="small">
            <el-radio v-for="dict in is_force_update" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="更新内容" prop="updateContent">
          <editor v-model="form.updateContent" :min-height="192" />
        </el-form-item>
        <!--        <el-form-item label="已知问题" prop="knownIssues">
          <el-input v-model="form.knownIssues" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="最低系统版本" prop="osSupport">
          <el-input v-model="form.osSupport" placeholder="请输入支持的最低系统版本，如 Android 5.0, iOS 11.0" />
        </el-form-item>-->

        <!--        <el-form-item label="更新包大小" prop="updatePackageSize">
          <el-input v-model="form.updatePackageSize" placeholder="请输入更新包大小" />
        </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="VersionManagement" lang="ts">
import {
  listVersionManagement,
  getVersionManagement,
  delVersionManagement,
  addVersionManagement,
  updateVersionManagement,
  generateAppDownLoadFile,
  uploadAppFileAsync
} from '@/api/system/business/versionManagement';
import { VersionManagementVO, VersionManagementQuery, VersionManagementForm } from '@/api/system/business/versionManagement/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { is_force_update, mobile_sys_type } = toRefs<any>(proxy?.useDict('is_force_update', 'mobile_sys_type'));
const versionManagementList = ref<VersionManagementVO[]>([]);
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 versionManagementFormRef = ref<ElFormInstance>();

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

const initFormData: VersionManagementForm = {
  id: undefined,
  versionCode: undefined,
  versionName: undefined,
  releaseDate: undefined,
  updateContent: undefined,
  knownIssues: undefined,
  osType: undefined,
  osSupport: undefined,
  forceUpdate: '0', // ✅ 默认选中“否”
  downloadLink: undefined,
  updatePackageSize: undefined,
  status: undefined,
  createdAt: undefined,
  updatedAt: undefined
};
const data = reactive<PageData<VersionManagementForm, VersionManagementQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    versionCode: undefined,
    versionName: undefined,
    releaseDate: undefined,
    updateContent: undefined,
    knownIssues: undefined,
    osType: undefined,
    osSupport: undefined,
    forceUpdate: undefined,
    downloadLink: undefined,
    updatePackageSize: undefined,
    status: undefined,
    createdAt: undefined,
    updatedAt: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键ID不能为空', trigger: 'blur' }],
    versionCode: [{ required: true, message: '版本号不能为空', trigger: 'blur' }],
    versionName: [{ required: true, message: '版本名称不能为空', trigger: 'blur' }],
    releaseDate: [{ required: true, message: '发布日期不能为空', trigger: 'blur' }],
    updateContent: [{ required: true, message: '更新内容不能为空', trigger: 'change' }],
    downloadLink: [{ required: false, message: '下载链接不能为空', trigger: 'blur' }],
    osType: [{ required: true, message: '系统类型不能为空', trigger: 'change' }]
  }
});

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

/** 查询App版本管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listVersionManagement(queryParams.value);
  versionManagementList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  fileList.value = [];
  dialog.visible = true;
  dialog.title = '添加';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: VersionManagementVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getVersionManagement(_id);
  Object.assign(form.value, res.data);
  form.value.forceUpdate = String(res.data.forceUpdate);
  dialog.visible = true;
  dialog.title = '修改';
};
/** 提交按钮 */
const submitForm = () => {
  versionManagementFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        // 判断如果没有下载链接，则必须上传文件
        if (!form.value.downloadLink || form.value.downloadLink.trim() === '') {
          if (fileList.value.length === 0) {
            proxy?.$modal.msgError('请先选择并上传文件或填写下载链接');
            return;
          }
        }
        await updateVersionManagement(form.value).finally(() => (buttonLoading.value = false));
      } else {
        if (form.value.osType == 'Android') {
          if (fileList.value.length === 0) {
            proxy?.$modal.msgError('请先选择并上传文件');
            return;
          }
        }
        await addVersionManagement(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: VersionManagementVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delVersionManagement(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};
const generateAppDownLoadFile2 = async (row?: VersionManagementVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否生成下载链接？').finally(() => (loading.value = false));
  await generateAppDownLoadFile(_ids.toString());
  proxy?.$modal.msgSuccess('生成成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'business/versionManagement/export',
    {
      ...queryParams.value
    },
    `versionManagement_${new Date().getTime()}.xlsx`
  );
};
const formatStatus = (status: number): string => {
  switch (status) {
    case 1:
      return '已发布';
    case 0:
      return '草稿';
    case -1:
      return '已下架';
    default:
      return '未知状态';
  }
};
const formatForceUpdate = (value: number): string => {
  return value === 1 ? '是' : '否';
};
onMounted(() => {
  getList();
});

//预览图标需要
const iconPreviewUrl = ref('');
const competitionIcon = ref('');
const fileList = ref([]);
const handleIconChange = async (file) => {
  const index = fileList.value.findIndex((f) => f.uid === file.uid);
  fileList.value = [];

  if (file.raw) {
    iconPreviewUrl.value = URL.createObjectURL(file.raw);
  }

  if (index === -1) {
    // 如果文件不在列表中，则添加进去
    fileList.value.push(file);
  }

  try {
    const rawFile = file.raw;
    const res = await uploadAppFileAsync(rawFile);
    if (res.code === 200) {
      // 更新文件状态为成功
      const uploadedFile = {
        ...file,
        status: 'success',
        response: res.data.url,
        fileName: res.data.fileName // 假设返回了 fileName 字段
      };

      // 找到刚添加的文件并更新
      const updatedIndex = fileList.value.findIndex((f) => f.uid === file.uid);
      if (updatedIndex !== -1) {
        fileList.value[updatedIndex] = uploadedFile;
      }

      // 设置下载链接
      form.value.downloadLink = 'https://oss.hunanpt.cn/' + uploadedFile.fileName;
      ElMessage.success('上传成功');
    } else {
      throw new Error(res.msg);
    }
  } catch (error) {
    // 更新文件状态为失败
    fileList.value[index] = {
      ...file,
      status: 'fail',
      error: '上传失败'
    };
    ElMessage.error('上传失败，请重试');
  }
};
// 删除文件处理函数
const handleIconRemove = (file, updatedFileList) => {
  fileList.value = updatedFileList;
  // 清除预览图和临时链接
  iconPreviewUrl.value = '';
  competitionIcon.value = ''; // 如果需要清除后台加载的图标，可以在这里设置为空字符串
};
</script>
<style scoped>
.truncate {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  word-wrap: normal;
}
</style>
