<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="appId" prop="appId">
        <el-input v-model="queryParams.appId" placeholder="请输入appId" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="应用名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入应用名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="平台类型" prop="name">
        <el-select v-model="queryParams.type" placeholder="请选择平台类型" clearable @change="handleQuery">
          <el-option v-for="dict in platform_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </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-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['business:app:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['business:app:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['business:app:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['business:app:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="appList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="appId" align="center" prop="appId" />
      <el-table-column label="应用名称" align="center" prop="name" />
      <el-table-column label="下载" align="center" prop="url">
        <template #default="scope">
          <el-button link type="primary" plain icon="Download" @click="handleDownload(scope.row.url)">下载</el-button>
        </template>
      </el-table-column>
      <el-table-column label="上传者" align="center" prop="author" width="100" />
      <el-table-column label="更新类型" align="center" width="100">
        <template #default="scope">
          <span v-if="scope.row.isForceUpdate" style="color:#f56c6c">{{ '强制更新' }}</span>
          <span v-else style="color:#67c23a">{{ '非强制更新' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="平台类型" align="center" prop="type" width="100">
        <template #default="scope">
          <dict-tag :options="platform_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="应用版本名" align="center" prop="versionName" width="100" />
      <el-table-column label="应用版本号" align="center" prop="versionCode" width="100" />
      <el-table-column label="更新内容" align="center" prop="remark" width="100">
        <template #default="scope">
          <el-tooltip effect="dark" :content="scope.row.remark" placement="top">
            {{ scope.row.remark.length > 4 ? scope.row.remark.substring(0, 3) + '...' : scope.row.remark }}
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:app:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['business:app:remove']">删除</el-button>
        </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" />

    <!-- 添加或修改app版本管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="appRef" :model="form" :rules="rules" label-width="120px" v-loading="formLoading">
        <el-form-item label="appId" prop="appId">
          <el-input v-model="form.appId" placeholder="请输入appId" />
        </el-form-item>
        <el-form-item label="应用名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入应用名称" />
        </el-form-item>
        <el-form-item label="下载地址" prop="url">
          <el-input v-model="form.url" placeholder="请输入下载地址">
            <template #append>
              <el-upload :action="webHost + '/common/upload'" :headers="headers" :limit="1" :on-success="handleSuccess"
                :on-exceed="handleExceed" :before-upload="beforeUpload" :show-file-list="false"
                :on-change="handleChange" :file-list="fileList">
                <el-button icon="Upload"></el-button>
              </el-upload>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="平台类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择平台类型" clearable>
            <el-option v-for="dict in platform_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="更新类型" prop="type">
          <el-radio v-model="form.isForceUpdate" :label="true">强制更新</el-radio>
          <el-radio v-model="form.isForceUpdate" :label="false">非强制更新</el-radio>
        </el-form-item>
        <el-form-item label="应用版本名" prop="versionName">
          <el-input v-model="form.versionName" placeholder="请输入应用版本名 如 1.0.0" />
        </el-form-item>
        <el-form-item label="应用版本号" prop="versionCode">
          <el-input v-model="form.versionCode" placeholder="请输入应用版本号" />
        </el-form-item>
        <el-form-item label="更新内容" prop="remark">
          <el-input v-model="form.remark" type="textarea" rows="5" placeholder="请输入跟新内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="App">
import { listApp, getApp, delApp, addApp, updateApp } from '@/api/business/app'
import { getToken } from '@/utils/auth'
import { stubString } from 'lodash'
const { proxy } = getCurrentInstance()
const { platform_type } = proxy.useDict('platform_type')
const webHost = import.meta.env.VITE_APP_PRODUCTION_API
const headers = { Authorization: getToken() }
const appList = ref([])
const open = ref(false)
const loading = ref(false)
const formLoading = ref(false)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const fileList = ref([])
const versionNameReg = /^([1-9]\d|[1-9])(\.([1-9]\d|\d)){2}$/
const versionCodeReg = /^[1-9][0-9]*$/
const isVersionName = async (rule, value, callback) => {
  if (!versionNameReg.test(value)) {
    callback(new Error('请输入正确版本名!例如：1.0.1'))
  } else {
    callback()
  }
}
const isVersionCode = async (rule, value, callback) => {
  if (!versionCodeReg.test(value)) {
    callback(new Error('应用版本号只能由数字构成!'))
  } else {
    callback()
  }
}
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10
  },
  rules: {
    appId: [{ required: true, message: 'appId不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '应用名称不能为空', trigger: 'blur' }],
    url: [{ required: true, message: '下载地址不能为空', trigger: 'blur' }],
    versionName: [
      { required: true, message: '应用版本名不能为空', trigger: 'blur' },
      { required: true, validator: isVersionName, trigger: 'blur' }
    ],
    versionCode: [
      { required: true, message: '应用版本号不能为空', trigger: 'blur' },
      { required: true, validator: isVersionCode, trigger: 'blur' }
    ]
  }
})

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

/** 文件上传前的 回调事件 */
function beforeUpload(file) {
  // console.log(file)
  formLoading.value = true
}
/** 文件下载 */
function handleDownload(url) {
  // console.log(webHost + url)
  window.open(webHost + url)
}

/** 查询app版本管理列表 */
function getList() {
  loading.value = true
  listApp(queryParams.value).then((response) => {
    appList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/**缩略图上传成功回调 */
function handleSuccess(res) {
  form.value.url = res.fileName
  formLoading.value = false
  fileList.value = []
}

function handleChange(files) {
  // console.log("change", files)
}
/**文件数量超出的回调 */
function handleExceed(files) {
  // console.log("exceed", files)
  form.value.url = files[0].url
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {}
  proxy.resetForm('appRef')
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef')
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加app版本管理'
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getApp(_id).then((response) => {
    form.value = response.data
    open.value = true
    title.value = '修改app版本管理'
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['appRef'].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateApp(form.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addApp(form.value).then((response) => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm('是否确认删除app版本管理编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delApp(_ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'business/app/export',
    {
      ...queryParams.value
    },
    `app_${new Date().getTime()}.xlsx`
  )
}

getList()
</script>
