<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="platform">
              <el-select v-model="queryParams.platform" placeholder="请选择平台" clearable style="width: 120px">
                <el-option label="Android" value="android">
                  <span class="flex items-center gap-1">
                    <el-icon><Monitor /></el-icon> Android
                  </span>
                </el-option>
                <el-option label="iOS" value="ios">
                  <span class="flex items-center gap-1">
                    <el-icon><Cellphone /></el-icon> iOS
                  </span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="版本号" prop="latestVersion">
              <el-input v-model="queryParams.latestVersion" placeholder="请输入版本号" clearable style="width: 150px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 100px">
                <el-option label="启用" value="1" />
                <el-option label="停用" value="0" />
              </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="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="['app:version:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['app:version:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['app:version:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['app:version: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="versionList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />

        <!-- 平台 -->
        <el-table-column label="平台" align="center" prop="platform" width="100">
          <template #default="{ row }">
            <el-tag
              :type="row.platform === 'android' ? 'success' : 'primary'"
              :icon="row.platform === 'android' ? Monitor : Cellphone"
              size="small"
            >
              {{ row.platform === 'android' ? 'Android' : 'iOS' }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 版本号 -->
        <el-table-column label="版本号" align="center" prop="latestVersion" width="120">
          <template #default="{ row }">
            <span class="version-badge">v{{ row.latestVersion }}</span>
          </template>
        </el-table-column>

        <!-- 版本序号 -->
        <el-table-column label="版本序号" align="center" prop="versionCode" width="100" />

        <!-- 强制更新 -->
        <el-table-column label="强制更新" align="center" prop="forceUpdate" width="100">
          <template #default="{ row }">
            <el-tag :type="row.forceUpdate === '1' ? 'danger' : 'info'" size="small">
              {{ row.forceUpdate === '1' ? '强制更新' : '可选更新' }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 状态 -->
        <el-table-column label="状态" align="center" prop="status" width="90">
          <template #default="{ row }">
            <el-tag :type="row.status === '1' ? 'success' : 'danger'" size="small">
              {{ row.status === '1' ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 更新说明 -->
        <el-table-column label="更新说明" align="center" prop="releaseNotes" min-width="180" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.releaseNotes || '-' }}</span>
          </template>
        </el-table-column>

        <!-- 下载地址 -->
        <el-table-column label="下载地址" align="center" prop="downloadUrl" min-width="160" show-overflow-tooltip>
          <template #default="{ row }">
            <el-link v-if="row.downloadUrl" type="primary" :href="row.downloadUrl" target="_blank" :underline="false">
              <el-icon class="mr-1"><Download /></el-icon>下载
            </el-link>
            <span v-else class="text-gray-400">-</span>
          </template>
        </el-table-column>

        <!-- 备注 -->
        <el-table-column label="备注" align="center" prop="remark" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.remark || '-' }}</span>
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column label="操作" align="center" fixed="right" width="100" 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="['app:version:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['app:version:remove']"></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="580px" append-to-body>
      <el-form ref="versionFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="平台" prop="platform">
          <el-radio-group v-model="form.platform">
            <el-radio value="android">
              <el-tag type="success" size="small" style="cursor:pointer">Android</el-tag>
            </el-radio>
            <el-radio value="ios">
              <el-tag type="primary" size="small" style="cursor:pointer">iOS</el-tag>
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="版本号" prop="latestVersion">
          <el-input v-model="form.latestVersion" placeholder="例：1.2.3" />
        </el-form-item>
        <el-form-item label="版本序号" prop="versionCode">
          <el-input-number v-model="form.versionCode" :min="1" :precision="0" controls-position="right" placeholder="用于排序，数值越大越新" class="w-full" />
        </el-form-item>
        <el-form-item label="强制更新" prop="forceUpdate">
          <el-radio-group v-model="form.forceUpdate">
            <el-radio value="0">可选更新</el-radio>
            <el-radio value="1">强制更新</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio value="1">启用</el-radio>
            <el-radio value="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="下载地址" prop="downloadUrl">
          <file-upload v-model="form.downloadUrl" :limit="0" :file-size="0" :file-type="[]" :is-show-tip="false" />
        </el-form-item>
        <el-form-item label="更新说明" prop="releaseNotes">
          <el-input v-model="form.releaseNotes" type="textarea" :rows="4" placeholder="请输入本版本的更新内容..." />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="2" 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="Version" lang="ts">
import { Monitor, Cellphone, Download } from '@element-plus/icons-vue';
import { listVersion, getVersion, delVersion, addVersion, updateVersion } from '@/api/app/version';
import { VersionVO, VersionQuery, VersionForm } from '@/api/app/version/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const versionList = ref<VersionVO[]>([]);
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 versionFormRef = ref<ElFormInstance>();

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

const initFormData: VersionForm = {
  id: undefined,
  platform: 'android',
  latestVersion: undefined,
  versionCode: undefined,
  forceUpdate: '0',
  downloadUrl: undefined,
  releaseNotes: undefined,
  status: '1',
  remark: undefined
}
const data = reactive<PageData<VersionForm, VersionQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    platform: undefined,
    latestVersion: undefined,
    versionCode: undefined,
    forceUpdate: undefined,
    downloadUrl: undefined,
    releaseNotes: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    platform: [
      { required: true, message: "请选择平台", trigger: "change" }
    ],
    latestVersion: [
      { required: true, message: "版本号不能为空", trigger: "blur" }
    ],
    versionCode: [
      { required: true, message: "版本序号不能为空", trigger: "blur" }
    ],
    forceUpdate: [
      { required: true, message: "请选择是否强制更新", trigger: "change" }
    ],
    status: [
      { required: true, message: "请选择状态", trigger: "change" }
    ],
  }
});

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

/** 查询APP版本列表 */
const getList = async () => {
  loading.value = true;
  const res = await listVersion(queryParams.value);
  versionList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

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

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

const normalizeBinaryValue = (value: unknown, defaultValue: string) => {
  if (value === undefined || value === null || value === '') return defaultValue;
  if (value === true) return '1';
  if (value === false) return '0';
  const normalizedValue = String(value).toLowerCase();
  if (['1', 'true', 'yes', 'y', '是'].includes(normalizedValue)) return '1';
  if (['0', 'false', 'no', 'n', '否'].includes(normalizedValue)) return '0';
  return defaultValue;
}

const normalizeFormData = (data?: VersionForm): VersionForm => {
  return {
    ...initFormData,
    ...data,
    id: data?.id ?? (data as any)?.versionId,
    platform: data?.platform ?? initFormData.platform,
    forceUpdate: normalizeBinaryValue(data?.forceUpdate, initFormData.forceUpdate as string),
    status: normalizeBinaryValue(data?.status, initFormData.status as string)
  };
}

const getVersionId = (row?: VersionVO) => {
  return row?.id ?? (row as any)?.versionId;
}

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: VersionVO[]) => {
  ids.value = selection.map(item => getVersionId(item)).filter((id): id is string | number => id !== undefined && id !== null);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "新增 APP 版本";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: VersionVO) => {
  reset();
  const _id = getVersionId(row) || ids.value[0];
  if (!_id) {
    proxy?.$modal.msgError("未获取到APP版本主键，无法修改");
    return;
  }
  const res = await getVersion(_id);
  form.value = normalizeFormData(res.data);
  dialog.visible = true;
  dialog.title = "修改 APP 版本";
}

/** 提交按钮 */
const submitForm = () => {
  versionFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      const submitData = normalizeFormData(form.value);
      if (submitData.id) {
        await updateVersion(submitData).finally(() => buttonLoading.value = false);
      } else {
        await addVersion(submitData).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: VersionVO) => {
  const _ids = getVersionId(row) || ids.value;
  if (!_ids || (Array.isArray(_ids) && !_ids.length)) {
    proxy?.$modal.msgError("未获取到APP版本主键，无法删除");
    return;
  }
  await proxy?.$modal.confirm('是否确认删除APP版本编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delVersion(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

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

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

<style lang="scss" scoped>
.version-badge {
  display: inline-block;
  padding: 2px 8px;
  background: #f0f4ff;
  color: #4a6cf7;
  border-radius: 12px;
  font-size: 13px;
  font-weight: 600;
  font-family: 'Courier New', monospace;
  border: 1px solid #d0dbff;
}
</style>
