<!--
 * @Descripttion: (/pda_auto_update)
 * @version: (1.0)
 * @Author: (admin)
 * @Date: (2024-03-18)
 * @LastEditors: (admin)
 * @LastEditTime: (2024-03-18)
-->
<template>
  <div>
    <el-form :model="queryParams" label-position="right" inline ref="queryRef" v-show="showSearch" @submit.prevent
      size="large">
      <el-form-item label="安装包名称" prop="packageName">
        <el-input v-model="queryParams.packageName" placeholder="请输入" class="z-el-input" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="版本号" prop="versionNo">
        <el-input v-model="queryParams.versionNo" placeholder="请输入" class="z-el-input" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="版本名称" prop="versionName">
        <el-input v-model="queryParams.versionName" placeholder="请输入" class="z-el-input" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="更新内容" prop="updateDetails">
        <el-input v-model="queryParams.updateDetails" placeholder="请输入" class="z-el-input" clearable
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="发布时间">
        <el-date-picker v-model="queryTime" style="width: 400px" type="datetimerange" range-separator="-"
          @change="handleQuery" start-placeholder="开始时间" end-placeholder="结束时间"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button icon="search" type="primary" @click="handleQuery">{{ $t('btn.search') }}</el-button>
        <el-button icon="refresh" @click="resetQuery">{{ $t('btn.reset') }}</el-button>
      </el-form-item>
    </el-form>
    <!-- 工具区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" v-hasPermi="['business:pdaautoupdate:add']" plain icon="plus" @click="handleAdd">
          <!-- {{ $t('btn.add') }} -->
          新版发布
        </el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" :disabled="single" v-hasPermi="['business:pdaautoupdate:edit']" plain icon="edit"
          @click="handleUpdate">
          {{ $t('btn.edit') }}
        </el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" :disabled="multiple" v-hasPermi="['business:pdaautoupdate:delete']" plain icon="delete"
          @click="handleDelete">
          {{ $t('btn.delete') }}
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <!-- 数据区域 -->
    <el-table :data="dataList" v-loading="loading" ref="table" highlight-current-row @sort-change="sortChange"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column prop="id" label="id" align="center" v-if="columns.showColumn('id')" />
      <el-table-column prop="packageName" label="安装包名称" align="center" :show-overflow-tooltip="true"
        v-if="columns.showColumn('packageName')" width="240" />
      <el-table-column prop="versionNo" label="版本号" align="center" v-if="columns.showColumn('versionNo')" width="120" />
      <el-table-column prop="versionName" label="版本名称" align="center" :show-overflow-tooltip="true"
        v-if="columns.showColumn('versionName')" width="120" />
      <el-table-column prop="publishTime" label="发布时间" align="center" :show-overflow-tooltip="true"
        v-if="columns.showColumn('publishTime')" width="160" />
      <el-table-column prop="updateDetails" label="更新内容" align="center" :show-overflow-tooltip="true"
        v-if="columns.showColumn('updateDetails')" />
      <el-table-column prop="remark" label="备注" align="center" :show-overflow-tooltip="true"
        v-if="columns.showColumn('remark')" />
      <el-table-column label="操作" align="center" width="100">
        <template #default="scope">
          <!-- <el-button v-hasPermi="['business:pdaautoupdate:edit']" type="success" icon="edit" title="编辑" plain
            @click="handleUpdate(scope.row)"></el-button> -->
          <el-button v-hasPermi="['business:pdaautoupdate:delete']" type="danger" icon="delete" title="删除" plain
            @click="handleDelete(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination class="mt10" background :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :lock-scroll="false" v-model="open" width="600">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" size="large" style="max-width: 500px;">
        <!-- <el-form-item label="id" prop="id">
          <el-input-number v-model.number="form.id" controls-position="right" placeholder="请输入id" :disabled="true" />
        </el-form-item> -->
        <el-form-item label="安装包" prop="packageName">
          <el-input v-model="form.packageName" placeholder="请选择安装包">
            <template #append>
              <el-upload name="file" ref="uploadRef" :limit="1" accept=".apk" :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :on-error="handleFileError"
                :on-exceed="handleExceed" :auto-upload="false" :on-change="uploadPackageChange" :show-file-list="false">
                <template #trigger>
                  <el-button>选择</el-button>
                </template>
              </el-upload>
            </template>
          </el-input>
          <!-- <el-upload ref="uploadRef" :auto-upload="false" :on-change="uploadPackageChange"
            :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :on-error="handleFileError"
            :on-exceed="handleExceed" :limit="1">
            <template #trigger>
              <el-button>选择安装包</el-button>
            </template>
          </el-upload> -->
        </el-form-item>
        <el-form-item label="版本号" prop="versionNo">
          <el-input-number v-model="form.versionNo" placeholder="请输入版本号" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="版本名称" prop="versionName">
          <el-input v-model="form.versionName" placeholder="请输入版本名称" />
        </el-form-item>
        <el-form-item label="更新内容" prop="updateDetails">
          <el-input v-model="form.updateDetails" placeholder="请输入更新内容" type="textarea" autosize />
        </el-form-item>
        <!-- <el-form-item label="发布时间" prop="publishTime">
          <el-date-picker v-model="form.publishTime" type="datetime" :teleported="false"
            placeholder="选择日期时间"></el-date-picker>
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入remark" />
        </el-form-item>
      </el-form>
      <template #footer v-if="opertype != 3">
        <el-button text @click="cancel" size="large">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="submitForm" size="large">{{ $t('btn.submit') }}</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="pdaautoupdate">
import {
  listPdaAutoUpdate, addPdaAutoUpdate, delPdaAutoUpdate, updatePdaAutoUpdate, getPdaAutoUpdate,

}
  from '@/api/business/pdaautoupdate.js'

import { getToken } from "@/utils/auth";
const { proxy } = getCurrentInstance()
// 选中id数组数组
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const loading = ref(false)
const showSearch = ref(true)
const queryTime = ref()
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  sort: '',
  sortType: 'asc',
})
const columns = ref([
  { visible: false, prop: 'id', label: 'Id' },
  { visible: true, prop: 'packageName', label: '安装包名称' },
  { visible: true, prop: 'versionNo', label: '版本号' },
  { visible: true, prop: 'versionName', label: '版本名称' },
  { visible: true, prop: 'publishTime', label: '发布时间' },
  { visible: true, prop: 'updateDetails', label: '更新内容' },
  { visible: false, prop: 'remark', label: '备注' },
])
const total = ref(0)
const dataList = ref([])
const queryRef = ref()
const defaultTime = ref([new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)])


var dictParams = [
]


function getList() {
  loading.value = true
  listPdaAutoUpdate(queryParams).then(res => {
    const { code, data } = res
    if (code == 200) {
      dataList.value = data.result
      total.value = data.totalNum
      loading.value = false
    }
  })
}

// 查询
function handleQuery() {
  queryParams.pageNum = 1

  if (queryTime.value != null) {
    queryParams.beginTime = queryTime.value[0]
    queryParams.endTime = queryTime.value[1]
    // console.log(queryParams)
  }
  else {
    queryParams.beginTime = undefined
    queryParams.endTime = undefined
  }
  console.log(queryParams)
  getList()
}

// 重置查询操作
function resetQuery() {
  queryTime.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

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

// 自定义排序
function sortChange(column) {
  var sort = undefined
  var sortType = undefined

  if (column.prop != null && column.order != null) {
    sort = column.prop
    sortType = column.order

  }
  queryParams.sort = sort
  queryParams.sortType = sortType
  handleQuery()
}

/*************** form操作 ***************/
const formRef = ref()
const title = ref("")
// 操作类型 1、add 2、edit 3、view
const opertype = ref(0)
const open = ref(false)
const state = reactive({
  form: {},
  rules: {
    packageName: [{ required: true, message: "安装包名称不能为空", trigger: "change" }],
    versionNo: [{ required: true, message: "版本号不能为空", trigger: "change" }],
    publishTime: [{ required: true, message: "发布时间不能为空", trigger: "change" }],
    versionName: [{ required: true, message: "版本名称不能为空", trigger: "change" }],
    updateDetails: [{ required: true, message: "更新内容不能为空", trigger: "change" }],
  },
  options: {
  }
})

const { form, rules, options } = toRefs(state)

// 关闭dialog
function cancel() {
  open.value = false
  reset()
}

// 重置表单
function reset() {
  form.value = {
    id: undefined,
    packageName: undefined,
    versionNo: undefined,
    versionName: undefined,
    // publishTime: undefined,
    updateDetails: undefined,
    remark: undefined,
  };
  proxy.resetForm("formRef")
}

// 添加按钮操作
function handleAdd() {
  reset();
  form.value.publishTime = new Date()
  open.value = true
  title.value = '添加'
  opertype.value = 1
}

// 修改按钮操作
function handleUpdate(row) {
  reset()
  const id = row.id || ids.value
  getPdaAutoUpdate(id).then((res) => {
    const { code, data } = res
    if (code == 200) {
      open.value = true
      title.value = "修改数据"
      opertype.value = 2

      form.value = {
        ...data,
      }
    }
  })
}

// 添加&修改 表单提交
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined && opertype.value === 2) {
        updatePdaAutoUpdate(form.value).then((res) => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
          .catch(() => { })
      } else {
        submitFileForm()
      }
    }
  })
}

// 删除按钮操作
function handleDelete(row) {
  const Ids = row.id || ids.value

  proxy
    .$confirm('是否确认删除？')
    .then(function () {
      return delPdaAutoUpdate(Ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    })
    .catch(() => { })
}

/*** 导入参数 */
const upload = reactive({
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: 'Bearer ' + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/business/PdaAutoUpdate/upload'
})
/**提交上传文件 */
function submitFileForm() {
  console.log(upload.url)
  proxy.$refs['uploadRef'].submit()
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.isUploading = false

  //PDA安装包上传成功，开始提交整个表单
  addPdaAutoUpdate(form.value).then((res) => {
    proxy.$modal.msgSuccess("新增成功")
    proxy.$refs['uploadRef'].clearFiles()
    open.value = false
    getList()
  })
    .catch(() => { })
  // proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.data + '</div>', '导入结果', {
  //   dangerouslyUseHTMLString: true
  // })
}
/** 文件上传服务器错误处理 */
const handleFileError = (Error, file, fileList) => {
  upload.isUploading = false
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>【" + file.name + "】导入错误。" + '</div>', '导入错误', {
    dangerouslyUseHTMLString: true
  })
}
/** 上传文件数量超限，替换文件 */
const handleExceed = (files, uploadFiles) => {
  proxy.$refs['uploadRef'].clearFiles()
  proxy.$refs['uploadRef'].handleStart(files[0])
}
function uploadPackageChange(file) {
  if (file != null) {
    form.value.packageName = file.name
  }
}


handleQuery()
</script>