<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="searchForm" :inline="true" :model="searchInfo">
        <el-form-item label="任务Id">
          <el-input v-model="searchInfo.task_id_string" placeholder="任务Id" />
        </el-form-item>
        <el-form-item label="负责人">
          <el-select v-model="searchInfo.user" placeholder="负责人">
            <el-option v-for="item in ResponsiblePerson" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button size="small" icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <!-- <div class="gva-btn-list">
        <el-button size="small" type="primary" icon="plus" @click="openDialog('addCard')">新增</el-button>
      </div> -->
      <el-table :data="tableData" border @sort-change="sortChange" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column align="left" label="任务ID" min-width="60" prop="task_id" sortable="custom" />
        <el-table-column align="left" label="任务名称" min-width="60" prop="task_name" sortable="custom" />
        <el-table-column align="left" label="负责人" min-width="60" prop="user" sortable="custom" />
        <el-table-column align="left" label="游戏名称" min-width="80" prop="game_name" sortable="custom" />
        <el-table-column align="left" fixed="right" label="操作" width="140">
          <template #default="scope">
            <el-button icon="edit" size="small" type="primary" link @click="uploadFunc(scope.row)">上传</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination :current-page="page" :page-size="pageSize" :page-sizes="[10, 30, 50, 100]" :total="total"
          layout="total, sizes, prev, pager, next, jumper" @current-change="handleCurrentChange"
          @size-change="handleSizeChange" />
      </div>

    </div>
    <el-dialog v-model="dialogFormVisible" :before-close="closeDialog" :title="dialogTitle">
      <el-form :model="form" :rules="rules" ref="uploadForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="任务id" prop="task_id">
          <el-input type="textarea" v-model="form.task_id" style="width:500px;"></el-input>
        </el-form-item>
        <el-form-item label="负责人">
          <el-select v-model="form.responsible_person" placeholder="负责人">
            <el-option v-for="item in ResponsiblePerson" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="上传文件" prop="file">
          <el-upload ref="upload" class="upload-demo" action="#" :before-remove="beforeRemove" :limit="1"
            :on-exceed="handleExceed" :on-remove="handleRemove" :on-change="handleChange" :file-list="fileList.data"
            :http-request="httpRequest" :data="form" :auto-upload="false" name="annexFile" style="width: 500px;">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">{{ message }}</div>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitUpload" v-loading.fullscreen.lock="fullscreenLoading">立即创建</el-button>
          <el-button @click="resetForm()">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>
  
<script lang="ts">
export default {
  name: 'AddFileUpdate',
}
</script>
  
<script lang="ts" setup>

import {
  addFileUpdate,
  getGameTaskList,
} from '@/api/upload'
import {
  selectResponsiblePerson,
} from '@/api/responsiblePerson'
import { useUserStore } from '@/pinia/modules/user'
import { toSQLLine } from '@/utils/stringFun'
import warningBar from '@/components/warningBar/warningBar.vue'
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { async } from 'q'
import { reactive } from 'vue'
import { genFileId } from 'element-plus'
// import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'

const ResponsiblePerson = ref([{
  id: 0,
  name: "",
}
])
const getResponsiblePerson = async () => {
  const table = await selectResponsiblePerson()
  if (table.code === 0) {
    ResponsiblePerson.value = table.data
  }
}
getResponsiblePerson()

const GamePortOptions = ref([
])

const accountTypeOptions = ref([
])

const loginMethodOptions = ref([
])
const type = ref('')
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({
  task_id_string: "",
  orderKey: "",
  desc: false,
  task_id: 0,
  user: "",
})

const onReset = () => {
  searchInfo.value = {
    task_id_string: "",
    orderKey: "",
    desc: false,
    task_id: 0,
    user: "",
  }
}
// 搜索
const onSubmit = () => {
  page.value = 1
  pageSize.value = 10
  searchInfo.value.task_id = Number(searchInfo.value.task_id_string)
  getTableData()
}
// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 排序
const sortChange = ({ prop, order }) => {
  if (prop) {
    if (prop === 'id') {
      prop = 'id'
    }
    searchInfo.value.orderKey = toSQLLine(prop)
    searchInfo.value.desc = order === 'descending'
  }
  getTableData()
}

// 查询
const getTableData = async () => {
  const table = await getGameTaskList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    GamePortOptions.value = table.data.option.game_port
    loginMethodOptions.value = table.data.option.login_type
    accountTypeOptions.value = table.data.option.account_type
    links.value = table.data.option.game_list
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()

const apis: any = 0
// 批量操作
const handleSelectionChange = (val) => {
  apis.value = val
}

// 弹窗相关
const initForm = () => {

  uploadForm.value.resetFields()
  upload.value!.clearFiles()
  form.value = {
    task_id: '',//游戏id
    responsible_person: '',
  }
}

const uploadFunc = async (row) => {
  // const res = await getGameTaskById({ id: row.task_id })
  form.value.task_id = row.task_id
  form.value.responsible_person = row.user
  openDialog('upload')
}

const dialogTitle = ref('新增')
const dialogFormVisible = ref(false)
const openDialog = (key) => {
  switch (key) {
    case 'upload':
      dialogTitle.value = '上传'
      // form.value.is_add = 1
      break
    // case 'edit':
    //   dialogTitle.value = '编辑'
    //   form.value.is_add = 0
    //   break
    default:
      break
  }
  type.value = key
  dialogFormVisible.value = true
}
const closeDialog = () => {
  initForm()
  dialogFormVisible.value = false
}

const links = ref([])

const createFilter = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    )
  }
}


let fullscreenLoading = false
// const uploadForm = ref([])
const upload = ref<UploadInstance>()
const uploadForm: any = ref(null)
const imageUrl = ref('')
const fileList = reactive({
  data: []
});

//上传
const headers = ref({
  // token: getStore('zxdAdmintoken'),
  "content-type": "multipart/form-data"
})
const message = ref('请上传dll/exe文件')

//校验规则
const rules = ref({
  task_id: [{
    required: true,
    message: '请输入游戏id',
    trigger: 'blur'
  }],
})

const form = ref({
  task_id: '',//游戏id
  responsible_person: '',
})


const handleExceed: UploadProps['onExceed'] = (files) => {
  console.log("数组超标")
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}

const handleChange: UploadProps['onChange'] = (file, fileList) => {

  let extension = file.name.substring(file.name.lastIndexOf('.') + 1);
  console.log(extension)
  if (extension !== 'dll' && extension !== 'exe') {
    // this.$message.warning('只能上传后缀是.zip/.rar/.apk的文件'); //控制文件类型
    ElMessage.error('文件类型不对'); //控制文件类型
    upload.value!.clearFiles()
    return false
  }
  else if (Number(file.size) / 1024 / 1024 > 20) {
    ElMessage.error('Avatar file size can not exceed 20MB!')
    upload.value!.clearFiles()
    return false
  }
  return true
}

const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `Cancel the transfert of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  )
}
let fd = new FormData()
const httpRequest = (param: any) => {



  // let fd = new FormData();
  const fileObj = param.file // 相当于input里取得的files
  fd.append('file', fileObj) // 文件对象
  console.log("文件包" + fd.get('file'));
  const url = '';
}

const handleRemove: UploadProps['onRemove'] = (file, fileList) => {
  console.log(fileList)
}


const submitUpload = async () => {
  uploadForm.value.validate(async valid => {
    if (valid) {
      if (fileList.data.length <= 0) {
        ElMessage.error("至少上传一款脚本！");
        return;
      }
      upload.value!.submit()
      fd.append('task_id', form.value.task_id)
      fd.append('responsible_person', form.value.responsible_person)
      // this.fd.append('log', this.ruleForm.log)
      fullscreenLoading = true;
      //调用后端接口，提交即可
      const res = await addFileUpdate(fd)
      console.log(res)
      if (res.code == 0) {
        fullscreenLoading = false;
        ElMessage({
          message: '上传成功',
          type: 'success'
        });
        fd = new FormData()
        fileList.data = []
        resetForm()
        getTableData()
        closeDialog()
      } else {
        fullscreenLoading = false;
        ElMessage.error("上传失败");
        fileList.data = []
        getTableData()
        closeDialog()
      }
    } else {
      // console.log('error submit!!');
      fileList.data = []
      return false;
    }
  });


}


//重置
const resetForm = async () => {
  uploadForm.value.resetFields()
  // console.log(uploadForm.file)
  upload.value!.clearFiles()
  form.value = {
    task_id: '',//游戏id
    responsible_person: '',
  }
}

</script>
  

<!-- <script lang="ts" setup>
import { ref, reactive } from 'vue'
import { genFileId } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'

const fullscreenLoading = ref(false)
const uploadForm = ref(null)
const upload = ref<UploadInstance>()
const imageUrl = ref('')
const fileList = reactive({
    data: []
});

//上传
const headers = ref({
  // token: getStore('zxdAdmintoken'),
  "content-type": "multipart/form-data"
})
const message = ref('请上传dll文件')

//校验规则
const rules = ref({
  game_id: [{
    required: true,
    message: '请输入游戏id',
    trigger: 'blur'
  }],
})

const uploadForm = ref(null)
const form = ref({
  game_id: '' //游戏id
})



const handleExceed: UploadProps['onExceed'] = (files) => {
    upload.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    upload.value!.handleStart(file)
}

const handleChange: UploadProps['onChange'] = (file, fileList) => {

    let extension = file.name.substring(file.name.lastIndexOf('.') + 1);
    console.log(extension)
    if (extension !== 'dll') {
        // this.$message.warning('只能上传后缀是.zip/.rar/.apk的文件'); //控制文件类型
        ElMessage.error('文件类型不对'); //控制文件类型
        upload.value!.clearFiles()
        return false
    }
    else if (Number(file.size) / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        upload.value!.clearFiles()
        return false
    }
    return true
}

const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
    return ElMessageBox.confirm(
        `Cancel the transfert of ${uploadFile.name} ?`
    ).then(
        () => true,
        () => false
    )
}

const httpRequest = (param) => {


    let fd = new FormData();
    const fileObj = param.file // 相当于input里取得的files
    fd.append('file', fileObj) // 文件对象
    console.log("文件包" + fd.get('file'));
    const url = '';
}

const handleRemove: UploadProps['onRemove'] = (file, fileList) => {
    console.log(file, fileList)
}

const submitUpload = () => {
  uploadForm.value.validate(async valid => {
    if (valid) {
      if (fileList.length <= 0) {
        $message.error("至少上传一款脚本！");
        return;
      }
      upload.submit();
      //换行自动添加为<br/>
      // this.ruleForm.log= this.ruleForm.log.replace(/\n/g,"<br/>");
      // console.log(this.ruleForm.log)
      //将表单内其他内容添加进fd
      fd.append('game_id', form.game_id)
      // this.fd.append('log', this.ruleForm.log)
      fd.append('type', "0")
      fullscreenLoading = true;
      //调用后端接口，提交即可
      const res = await addFileUpdate(fd)
      console.log(res)
      if (res.code == 0) {
        fullscreenLoading = false;
        $message({
          message: '上传成功',
          type: 'success'
        });
        fd = {}
        fileList = []
        resetForm(formName)
      } else {
        $message.error("上传失败");
      }
    } else {
      // console.log('error submit!!');
      return false;
    }
  });

    upload.value!.submit()
}


//重置
const resetForm = async (form) => {
  uploadForm.value.resetFields()
  console.log(uploadForm.file)
  upload.value.clearFiles()
  // form.value = {
  //   game_id: '' //游戏id
  // }
}




</script> -->







<style scoped lang="scss">
.button-box {
  padding: 10px 20px;

  .el-button {
    float: right;
  }
}

:deep(.el-tabs__nav-scroll) {
  width: 35%;
  margin: 0 auto
}

:deep(.el-tabs__nav-scroll) .warning {
  color: #dc143c;
}
</style>
  