<script lang="ts">
export default {
  name: 'appreversion'
};
</script>

<script setup lang="ts">
import { onMounted, reactive, ref, toRefs } from 'vue';
import { ElForm, ElMessage } from 'element-plus';
import {
  sysAppRevision,
  updateSysAppRevision
} from '@/api/system/appreversion';
import {
  AppRevisionQueryParam,
  AppRevisionItem,
  AppRevisionFormData,
  AppRevisionLangContent,
} from '@/types/api/system/appreversion';

const LANGS = [
  { key: 'zh_CN', label: '简体' },
  { key: 'zh_HK', label: '繁体' },
  { key: 'en_US', label: 'English' },
  { key: 'ko_KR', label: '韩语' },
  { key: 'ja_JP', label: '日语' },
  { key: 'hi_IN', label: '印地语' },
  { key: 'id_ID', label: '印尼语' },
] as const;

function emptyLangContent(): AppRevisionLangContent {
  return { zh_CN: '', zh_HK: '', en_US: '', ko_KR: '', ja_JP: '', hi_IN: '', id_ID: '' };
}

function parseLangJson(raw: string | null | undefined): AppRevisionLangContent {
  if (!raw) return emptyLangContent();
  try {
    const parsed = JSON.parse(raw);
    return {
      zh_CN: parsed.zh_CN ?? '',
      zh_HK: parsed.zh_HK ?? '',
      en_US: parsed.en_US ?? '',
      ko_KR: parsed.ko_KR ?? '',
      ja_JP: parsed.ja_JP ?? '',
      hi_IN: parsed.hi_IN ?? '',
      id_ID: parsed.id_ID ?? '',
    };
  } catch {
    // 兼容旧数据（纯文本）— 放到中文
    return { zh_CN: raw, zh_HK: '', en_US: '', ko_KR: '', ja_JP: '', hi_IN: '', id_ID: '' };
  }
}

function displayDescription(raw: string): string {
  const d = parseLangJson(raw);
  return d.zh_CN || d.zh_HK || d.en_US || d.ko_KR || d.ja_JP || d.hi_IN || d.id_ID || raw;
}

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const state = reactive({
  id: 0,
  loading: true,
  queryParams: {
    pageNo: 1,
    pageSize: 15,
  } as AppRevisionQueryParam,
  list: [] as AppRevisionItem[],
  total: 0,
  dialog: {
    title: '',
    visible: false,
    loading: false,
  },
  activeLangTab: 'zh_CN',
  formData: {
    platform: 0,
    version: '',
    lowestVersion: '',
    descriptions: emptyLangContent(),
    publishTime: '',
    downloadUrl: '',
    remark: '',
  } as AppRevisionFormData,
  rules: {},
});

const {
  id,
  loading,
  queryParams,
  list,
  total,
  dialog,
  formData,
  rules,
  activeLangTab,
} = toRefs(state);

function handleQuery() {
  state.loading = true;
  sysAppRevision(state.queryParams).then(({ data }) => {
    state.list = data.content;
    state.total = data.totalElements;
    state.loading = false;
  });
}

const handleEdit = (row: any) => {
  state.dialog = {
    title: '编辑版本管理',
    visible: true,
    loading: false,
  };
  state.id = row.id;
  state.activeLangTab = 'zh_CN';
  state.formData.platform = row.platform;
  state.formData.version = row.version;
  state.formData.lowestVersion = row.lowestVersion;
  state.formData.descriptions = parseLangJson(row.updateDescription);
  state.formData.publishTime = row.publishTime;
  state.formData.downloadUrl = row.downloadUrl;
  state.formData.remark = row.remark;
};

function submitFormData() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      dialog.value.loading = true;
      const payload = {
        ...state.formData,
        updateDescription: JSON.stringify(state.formData.descriptions),
      };
      updateSysAppRevision(state.id, payload).then(() => {
        cancel();
        dialog.value.loading = false;
        ElMessage.success('修改成功');
        handleQuery();
      });
    }
  });
}

function cancel() {
  dialog.value.visible = false;
  dialog.value.loading = false;
  state.id = 0;
  state.activeLangTab = 'zh_CN';
  state.formData = {
    platform: 0,
    version: '',
    lowestVersion: '',
    descriptions: emptyLangContent(),
    publishTime: '',
    downloadUrl: '',
    remark: '',
  };
}

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

<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form ref="queryFormRef" :model="queryParams" :inline="true">
    </el-form>

    <!-- 数据表格 -->
    <el-table
      ref="dataTableRef"
      v-loading="loading"
      :data="list"
      highlight-current-row
      border
      >
      <el-table-column label="ID" prop="id" min-width="80" align="center" />
      <el-table-column label="平台" prop="platform" min-width="110" align="center">
        <template #default="scope">
          <span v-if="scope.row.platform==0">安卓</span>
          <span v-else-if="scope.row.platform==1">iOS</span>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column label="当前版本" prop="version" min-width="110" align="center" />
      <el-table-column label="最低版本" prop="lowestVersion" min-width="110" align="center" />
      <el-table-column label="更新描述" min-width="160" align="center">
        <template #default="scope">
          {{ displayDescription(scope.row.updateDescription) }}
        </template>
      </el-table-column>
      <el-table-column label="更新日期" prop="publishTime" min-width="160" align="center" />
      <el-table-column label="下载地址" prop="downloadUrl" min-width="200" align="center" />
      <el-table-column label="备注" prop="remark" min-width="160" align="center" />
      <el-table-column label="操作" align="center" width="110" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click.stop="handleEdit(scope.row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页工具条 -->
    <pagination
      v-if="total > 0"
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="handleQuery"
    />

    <!-- 更新表单弹窗 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="560px"
      destroy-on-close
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="平台" prop="platform">
          <el-radio-group v-model="formData.platform">
            <el-radio :label="0">安卓</el-radio>
            <el-radio :label="1">iOS</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="当前版本" prop="version">
          <el-input type="text" v-model="formData.version" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="最低版本" prop="lowestVersion">
          <el-input type="text" v-model="formData.lowestVersion" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="更新描述">
          <div style="width: 100%">
            <el-tabs v-model="activeLangTab" type="card" size="small">
              <el-tab-pane
                v-for="lang in LANGS"
                :key="lang.key"
                :label="lang.label"
                :name="lang.key"
              >
                <el-input
                  type="textarea"
                  :rows="4"
                  v-model="formData.descriptions[lang.key]"
                  :placeholder="`请输入${lang.label}更新描述`"
                />
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-form-item>
        <el-form-item label="更新日期" prop="publishTime">
          <el-date-picker
            v-model="formData.publishTime"
            style="width: 210px"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetime"
            placeholder="更新日期"
            />
        </el-form-item>
        <el-form-item label="下载地址" prop="downloadUrl">
          <el-input type="text" v-model="formData.downloadUrl" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="formData.remark" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="dialog.loading" @click="submitFormData">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
