<template>
  <div class="PageContent">
    <div class="WebToolbar">
      <div class="FormComponent">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="企业名称">
            <el-input
              v-model="formInline.EnterpriseName"
              placeholder="请输入企业编码"
              clearable
            />
          </el-form-item>
          <el-form-item label="企业编码">
            <el-input
              v-model="formInline.EnterpriseCode"
              placeholder="请输入企业编码"
              clearable
            />
          </el-form-item>
          <el-form-item label="模型名称">
            <el-input
              v-model="formInline.ModelName"
              placeholder="请输入模型名称"
              clearable
            />
          </el-form-item>
        </el-form>
      </div>
      <div class="ButtonAssembly">
        <el-button style="color: #fff" @click="queryData()">
          <img src="../../assets/menu/search.png" alt="" />
          <span>查询</span>
        </el-button>
        <el-button style="color: #1d2129" @click="resetFormInline">
          <img src="../../assets/menu/reset.png" alt="" />
          <span>重置</span>
        </el-button>
      </div>
    </div>
    <div class="Tabulation">
      <div class="actionBar">
        <h1>考试列表</h1>
        <div class="Worktop">
          <el-button @click="goToAboutPage">编辑器</el-button>
          <el-button @click="handleReleaseExam">发布</el-button>
          <el-button @click="handleRevokeReleaseExam">撤销发布</el-button>
          <el-button @click="handleFinishedExam">考试结束</el-button>
            <el-button @click="handleExamination">考试名单</el-button>

          <el-button class="BlueBack" @click="handleCreate">
            <img src="../../assets/menu/Increased.png" alt="" />
            <span>新增</span>
          </el-button>
            <el-button class="BlueBack" @click="dialogToLead = true">
                <img src="../../assets/menu/toLead.png" alt="" />
                <span>导入</span>
            </el-button>
          <el-button class="Delete">
            <img src="../../assets/menu/delete.png" alt="" />
            <span>删除</span>
          </el-button>
        </div>
      </div>
      <div class="ExaminationForm">
        <el-table
          ref="multipleTableRef"
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" />
          <el-table-column label="序号" type="index" :index="indexMethod" width="60px"/>
          <el-table-column property="EnterpriseName" label="企业名称" />
          <el-table-column property="EnterpriseCode" label="企业编码" />
          <el-table-column property="DistrictCode" label="关区代码" />
          <el-table-column property="ModelName" label="模型名称" />
          <el-table-column property="VersionNumber" label="版本号" />
          <el-table-column property="MapLongitude" label="地图经度" />
			<el-table-column property="MapLatitude" label="地图纬度" />
			<el-table-column property="TrainingSize" label="模型包大小" />
          <el-table-column property="ModelResources" label="模型包资源地址" />
          <el-table-column property="UpdateTime" label="最新更新时间" />
          <el-table-column property="" label="操作">
            <template #default="{row}">
            <span class="user-name" @click="handleEdit(row)" >编辑</span>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-model:current-page="InlineForm.PageIndex"
          :page-size="InlineForm.PageSize"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="total, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
<!--新增弹框-->
  <el-dialog
    v-model="dialogFormVisible"
    title="编辑模型"
    width="1050"
    center
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="form" :rules="state.rules" :inline="true" :label-width="formLabelWidth">
      <el-form-item label="企业编号：" prop="ExamName">
        <el-input v-model="form.ExamName" />
      </el-form-item>
      <el-form-item
        label="企业名称："
        class="demo-form-scene"
      >
      <el-input v-model="form.ExamName" />
      </el-form-item>
      <el-form-item label="模型名称："  >
        <el-input v-model="form.ExamName" />
      </el-form-item>
      <el-form-item label="版本号："  >
        <el-input v-model="form.ExamName" />
      </el-form-item>
      <el-form-item label="地图经度："  >
        <el-input v-model="form.ExaminationDuration" autocomplete="off" />
      </el-form-item>
      <el-form-item label="地图纬度：">
        <el-input v-model="form.IncomingLineModelLength" autocomplete="off" />
        <span class="example">示例：YJV22-4*95/12米</span>
      </el-form-item>
      <el-form-item label="模型包大小：">
        <el-input v-model="form.OutgoingLineModelLength" autocomplete="off" />
        <span class="example">示例：YJV22-4*95/12米</span>
      </el-form-item>
      <el-form-item label="模型包资源：">
        <el-input v-model="form.OutgoingLineModelLength" autocomplete="off" />
        <span class="example">示例：YJV22-4*95/12米</span>
      </el-form-item>
      <el-form-item label="更新时间：">
        <el-input v-model="form.OutgoingLineModelLength" autocomplete="off" />
        <span class="example">示例：YJV22-4*95/12米</span>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
		  <el-button  @click="closeDialog">
		    取消
		  </el-button>
        <el-button @click="submit" type="primary">保存</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElTable, ElMessageBox, ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import {
  GetModelList,
  AddExam,
  EditExam,
  GetModelDetails,
  EditExamList,
  DeleteExam,
  GetScene,
  GetPlatformArea,
  GetLine,
  ApiReleaseExam,
  ApiRevokeReleaseExam,
  ApiFinishedExam,
  ApiCopyExam,
  ApiDownloadExamm,
  ApiGetExamRosterList,
  DeleteExamRoster,
  ApiGetAddExamRosterListt,
  ApiAddExamRoster,
  apiUpload

} from '@/api/index.js'

const formInline = reactive({
  EnterpriseName: '',
  EnterpriseCode: '',
  ModelName: '',
  PageIndex: 1,
  PageSize: 10
})
const resetFormInline = () => {
  formInline.EnterpriseName = ''
  formInline.EnterpriseCode = ''
  formInline.ModelName = ''
  getTable()
  //   for (const key in formInline) {
  //     if ( key !== 'PageIndex' || key !== 'PageIndex' ) formInline[key] = ''
  //   }
}
// 多选框
const indexMethod = (index) => {
  return index + 1
}

// 新增数据，弹框显示
const formRef = ref(null)
const dialogFormVisible = ref(false)
function handleCreate () {
  dialogFormVisible.value = true
}
const formLabelWidth = '150px'
const value1 = ref('')
const value2 = ref('')
const state = reactive({
  rules: {},
  scenemList: [],
  platformAreaList: [],
  lineList: []
})
const form = reactive({
  EnterpriseName: '',
  DistrictCode: '',
  ModelName: '',
  VersionNumber: '',
  MapLongitude: '',
  MapLatitude: '',
  Trainingsize: '',
  ModelResources: '',
  UpdateTime: ''
//   WorkOrderContent: '',
//   BackgroundInformation: '',
//   StartExamTime: '',
//   EndExamTime: '',
//   Type: '考试'
})

// 查询列表
onMounted(() => {
  getTable()
  // addTable()
  GetScene().then(res => {
    state.scenemList = res.data
    console.log(res.data, 'res.data--')
  })
  GetPlatformArea({
    SceneId: 'eab5920509b011ed844e7cd30a92bb1c'
  }).then(res => state.platformAreaList = res.data)
  GetLine({
    PlatformAreaId: '28f0723409b111ed844e7cd30a92bb1c'
  }).then(res => state.lineList = res.data)
})

// 考试列表
const total = ref(0)
const tableData = ref([])
const queryData = () => {
  formInline.PageIndex = 1
  getTable()
}
const getTable = async () => {
  try {
    const { code, data } = await GetModelList({
      ...formInline
    })

    if (code === 0) {
      console.log('data', data)
      total.value = data.total
      tableData.value = data.list
    } else {
      total.value = 0
      tableData.value = []
    }
  } catch (error) {}
}

const multipleTableRef = ref()
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  if (val.length > 1) {
    multipleTableRef.value.clearSelection()
    multipleTableRef.value.toggleRowSelection(val.pop())
  } else {
    // this.currentRow = val.pop();
    multipleSelection.value = val
  }
}
const textarea = ref('')
const small = ref(false)
const background = ref(false)
const disabled = ref(false)

// 分页
const InlineForm = reactive({
  PageIndex: 1,
  PageSize: 10
})
const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  formInline.PageSize = val
  getTable()
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  formInline.PageIndex = val
  getTable()
}
const ExamId = ref('')
const handleEdit = async (row) => {
  const res = await GetModelDetails({ EnterpriseCode: row.EnterpriseCode })
  console.log(res.data, 'res--')
  for (const key in form) {
    form[key] = res.data[key]
  }
  //   ExamId.value = res.data.ExamId
  dialogFormVisible.value = true
}
const handleCopy = (row) => {
  ApiCopyExam({ ExamId: row.ExamId }).then(res => {
    console.log(res, 'res--')
    if (res.code === 0) {
      ElMessage({
        message: '操作成功',
        type: 'success'
      })
      queryData()
    } else {
      ElMessage.error(res?.data || '操作失敗')
    }
  })
}
// 删除
const handleDelete = (row) => {
  console.log(row.ExamId, 'row--')
  ElMessageBox.confirm('确定要删除吗?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    DeleteExam({ ExamId: row.ExamId }).then(res => {
      console.log(res, 'res--')
      if (res.code === 0) {
        ElMessage({
          message: '操作成功',
          type: 'success'
        })
        queryData()
      } else {
        ElMessage.error(res?.data || '操作失敗')
      }
    })
  })
}
// 复制

// 保存
const submit = () => {
  formRef.value.validate(async (valid) => {
    console.log(form, 'from--')
    if (valid) {
      const obj = state.platformAreaList.find(v => v.PlatformAreaId == form.PlatformAreaId)
      console.log(obj, 'obj--')

      if (ExamId.value) {
        EditExam({
          ...form,
          PlatformArea: obj?.PlatformAreaName || '',
          ExamId: ExamId.value
        }).then(res => {
          console.log(res, 'res--')
          if (res.code == 0) {
            ElMessage({
              message: '操作成功.',
              type: 'success'
            })
            closeDialog()
            queryData()
          } else {
            ElMessage.error(res?.data || '操作失敗')
          }
        })
      } else {
		   form.Type = '考试'
        AddExam({
          ...form,
          PlatformArea: obj?.PlatformAreaName || ''
        }).then(res => {
          console.log(res, 'res--')
          if (res.code == 0) {
            ElMessage({
              message: '操作成功.',
              type: 'success'
            })
            closeDialog()
            queryData()
          } else {
            ElMessage.error(res?.data || '操作失敗')
          }
        })
      }
    }
  })
}
// 取消
const closeDialog = () => {
  for (const key in form) {
    form[key] = ''
  }
  ExamId.value = ''
  dialogFormVisible.value = false
}

// 跳转编辑器
const router = useRouter()
const goToAboutPage = () => {
	 if (multipleSelection.value?.length === 0) return ElMessage.error('请先选择')
  router.push(`/EditorMacros?ExamId=${multipleSelection.value[0].ExamId}`) // 跳转到指定路由
}
// 编辑弹框
const EditFormVisible = ref(false)
const EditExamtableData = ref()
const handleUpdate = async () => {
  EditFormVisible.value = true
  const data = await EditExamList()
  console.log(data.data, 'data')
}

// 发布
const handleReleaseExam = () => {
  if (multipleSelection.value?.length === 0) return ElMessage.error('请先选择')
  ElMessageBox.confirm('确定要发布吗?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ApiReleaseExam({ ExamId: multipleSelection.value[0].ExamId }).then(res => {
      console.log(res, 'res--')
      if (res.code == 0) {
        ElMessage({
          message: '操作成功',
          type: 'success'
        })
        queryData()
      } else {
        ElMessage.error(res?.data || '操作失敗')
      }
    })
  })
}

// 撤销发布
const handleRevokeReleaseExam = () => {
  if (multipleSelection.value?.length === 0) return ElMessage.error('请先选择')
  ElMessageBox.confirm('确定要撤销发布吗?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ApiRevokeReleaseExam({ ExamId: multipleSelection.value[0].ExamId }).then(res => {
      console.log(res, 'res--')
      if (res.code === 0) {
        ElMessage({
          message: '操作成功',
          type: 'success'
        })
        queryData()
      } else {
        ElMessage.error(res?.data || '操作失敗')
      }
    })
  })
}

// 撤销发布
const handleFinishedExam = () => {
  if (multipleSelection.value?.length === 0) return ElMessage.error('请先选择')
  ElMessageBox.confirm('确定要考试结束吗?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ApiFinishedExam({ ExamId: multipleSelection.value[0].ExamId }).then(res => {
      console.log(res, 'res--')
      if (res.code === 0) {
        ElMessage({
          message: '操作成功',
          type: 'success'
        })
        queryData()
      } else {
        ElMessage.error(res?.data || '操作失敗')
      }
    })
  })
}

// 考试名单
const dialogTabular = ref(false)
const stateA = reactive({
  total: 0,
  examRosterList: [],
  queryForm: {
    Name: '',
    Account: '',
    PageIndex: 1,
    PageSize: 10
  }
})
const handleExamination = async () => {
  if (multipleSelection.value?.length === 0) return ElMessage.error('请先选择')
  getExamination()
  getAddExamRosterListt()
  dialogTabular.value = true
}

const getExamination = async () => {
  console.log(stateA.queryForm, ' stateA.queryForm--')
  const res = await ApiGetExamRosterList({
    ExamId: multipleSelection.value[0].ExamId,
    // ExamId: '048dd77b0a734856a86153e2feaa1d1d',
    ...stateA.queryForm
  })
  dialogTabular.value = true
  stateA.examRosterList = res.data?.list || []
  stateA.total = res.data?.total
  console.log(res, 'res--ApiGetExamRosterList')
}
// 考试名单删除
const handleCancel = (row) => {
  console.log(row.ExamUsersId, 'row--')
  ElMessageBox.confirm('确定要删除吗?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    DeleteExamRoster({ ExamUsersId: row.ExamUsersId }).then(res => {
      console.log(res, 'res--')
      if (res.code === 0) {
        ElMessage({
          message: '操作成功',
          type: 'success'
        })
        getExamination()
        getAddExamRosterListt()
      } else {
        ElMessage.error(res?.data || '操作失敗')
      }
    })
  })
}

// 考试新增名单
const dialogExamination = ref(false)

const rosterSelection = ref([])
const handleSelChange = (val) => {
  console.log(val, 'val--')
  rosterSelection.value = val
}

const stateB = reactive({
  total: 0,
  examRosterList: [],
  queryForm: {
    Name: '',
    Account: '',
    PageIndex: 1,
    PageSize: 10
  }
})
const handleCurrentChangeB = (val) => {
  stateB.queryForm.PageIndex = val
  getAddExamRosterListt()
}
const getAddExamRosterListt = async () => {
  console.log(stateA.queryForm, ' stateA.queryForm--')
  if (multipleSelection.value?.length === 0) return ElMessage.error('请先选择')
  const res = await ApiGetAddExamRosterListt({
    ExamId: multipleSelection.value[0].ExamId,
    // ExamId: '048dd77b0a734856a86153e2feaa1d1d',
    ...stateB.queryForm
  })
  dialogTabular.value = true
  stateB.examRosterList = res.data?.list || []
  stateB.total = res.data?.total
  console.log(res, 'res--ApiGetExamRosterList')
}

const addExamRoster = () => {
  if (multipleSelection.value?.length === 0) return ElMessage.error('请先选择')
  ApiAddExamRoster({
    ExamId: multipleSelection.value[0].ExamId,
    UserIdList: rosterSelection.value.map(item => item.UserId)
  }).then(res => {
    console.log(res, 'res--')
    if (res.code === 0) {
      ElMessage({
        message: '操作成功',
        type: 'success'
      })
      getExamination()
      getAddExamRosterListt()
	  dialogExamination.value = false
    } else {
      ElMessage.error(res?.data || '操作失敗')
    }
  })
}
// 导入
const dialogToLead = ref(false)

const uploadRef = ref()
const handleExceed = (files) => {
  // submitUpload(files[0])
  uploadRef.value.clearFiles()
  nextTick(() => {
    uploadRef.value.handleStart(files[0])
  })
}
const handleChange = (uploadFile) => {
  console.log(uploadFile, 'uploadFile')
  // submitUpload(uploadFile.raw)
}
const submitUpload = () => {
  uploadRef.value.submit()
}
const toUpload = (param) => {
  if (!uploadRef.value) return ElMessage.error('请先上传文件')
  const formData = new FormData()
  formData.append('Files', param.file)
  apiUpload('', formData).then((res) => {
    console.log(res, 'res--')
    if (res.code === 0) {
      ElMessage({
        message: '上传成功',
        type: 'success'
      })
      queryData()
    } else {
      ElMessage.error(res?.data || '操作失敗')
    }
  })
}

</script>

<style scoped lang="scss">
.PageContent {
  width: 100%;
  height: 100%;
}
.WebToolbar {
  width: 100%;
  height: 72px;
  background-color: #fff;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  :deep(.el-form-item__content) {
    width: 256px !important;
    height: 32px !important;
  }
  :deep(.el-input) {
    width: 256px !important;
  }
  :deep(.el-select) {
    width: 256px !important;
  }
  :deep(.el-form-item__label) {
    color: #666 !important;
  }
}

.ButtonAssembly {
  .el-button {
    width: 84px;
    height: 32px;
    border: none;
    font-weight: 400;
    font-size: 14px;
    border-radius: 2px 2px 2px 2px;
    img {
      width: 16px;
      height: 16px;
      margin-right: 8px;
    }
  }
  .el-button:nth-child(1) {
    background-color: #0d867f;
  }
  .el-button:nth-child(2) {
    background-color: #f2f3f5;
  }
}

.Tabulation {
  width: 100%;
  height: calc(100% - 72px);
  background-color: #fff;
  margin-top: 14px;
  padding: 20px;
  .actionBar {
    display: flex;
    justify-content: space-between;
    h1 {
      font-weight: 500;
      font-size: 20px;
      color: #1d2129;
      line-height: 28px;
      font-family: Microsoft YaHei, Microsoft YaHei;
    }
  }
  .Worktop {
    .el-button {
      border: 1px solid #0d867f;
      font-weight: 400;
      font-size: 14px;
      color: #0d867f;
    }
    .el-button:hover {
      background-color: transparent;
    }
    .BlueBack {
      background: #0d867f;
      border-radius: 2px 2px 2px 2px;
      font-weight: 400;
      font-size: 14px;
      color: #ffffff;
      line-height: 22px;
      img {
        width: 16px;
        height: 16px;
        margin-right: 8px;
      }
    }
    .BlueBack:hover {
      background-color: #0d867f;
    }
    .Delete {
      background: #f2f3f5;
      border-radius: 2px 2px 2px 2px;
      font-weight: 400;
      font-size: 14px;
      color: #1d2129;
      line-height: 22px;
      border: none;
      img {
        width: 16px;
        height: 16px;
        margin-right: 8px;
      }
    }
    .Delete:hover {
      background-color: #f2f3f5;
    }
  }
  .ExaminationForm {
    margin-top: 16px;
    background-color: #0077aa;
  }
  .el-table tr {
    height: 41px;
  }
  .el-table td {
    height: 41px;
  }
  :deep(th) {
    background-color: #e5e6eb;
  }
}
.el-pagination {
  float: right;
  background-color: #fff !important;
  margin-top: 18px;
}
:deep(.el-pager li.is-active) {
  background-color: #e7f9f8 !important;
  font-weight: 400;
  color: #0d867f !important;
}
:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
  background-color: #e7f9f8 !important;
}

:deep(.el-select) {
  width: 280px !important;
}
:deep(.el-input) {
  width: 280px !important;
}
.example {
  margin-left: 20px;
  color: red;
}
.backInformation {
  :deep(.el-input) {
    width: 280px !important;
    height: 120px !important;
  }
}
.dialog-footer {
  width: 100%;
  text-align: center;
}
:deep(.el-textarea__inner) {
  width: 280px !important;
}
.user-name,.register{
  cursor: pointer;
}
.functionalUnit{
  margin-left: 20px;
  display: flex;
  .el-button {
    width: 84px;
    height: 32px;
    border: none;
    font-weight: 400;
    font-size: 14px;
    border-radius: 2px 2px 2px 2px;
    color: #fff;
    img {
      width: 16px;
      height: 16px;
      margin-right: 8px;
    }
  }
  .el-button:nth-child(1) {
    background-color: #2192ba;
  }
  .el-button:nth-child(2) {
    background-color: #17c85f;
  }
}
.TabularTitle{
  font-size: 14px;
  color: #747272;
  font-weight: bold;
  margin-bottom: 10px;
}
.pagination{
  width: 100%;
  height:30px;
  :deep(.el-pagination){
    margin-top: 9px!important;
  }
}
.addSlip{
  .el-button{
    border: none;
    background-color: #0077aa;
    margin-top: 8px;
    color: #fff;
  }
  :deep(.el-pagination){
    margin-top: 8px!important;
  }
}
.ml-3{
  margin-left: 20px;
}
</style>
