<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" row-key="id" :request-api="listMatchApi">
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" @click="openCreateDialog" v-show="true || scope">创建任务</el-button>

        <!--                <el-button type="primary" v-auth="['demo:match:add']" icon="CirclePlus" @click="openDialog(1, '异源图像匹配新增')">-->
        <!--                    新增-->
        <!--                </el-button>-->
        <!--                <el-button type="primary" v-auth="['demo:match:import']" icon="Upload" plain @click="batchAdd">-->
        <!--                    导入-->
        <!--                </el-button>-->
        <!--                <el-button type="primary" v-auth="['demo:match:export']" icon="Download" plain @click="downloadFile">-->
        <!--                    导出-->
        <!--                </el-button>-->
        <!--                <el-button-->
        <!--                    type="danger"-->
        <!--                    v-auth="['demo:match:remove']"-->
        <!--                    icon="Delete"-->
        <!--                    plain-->
        <!--                    :disabled="!scope.isSelected"-->
        <!--                    @click="batchDelete(scope.selectedListIds)"-->
        <!--                >-->
        <!--                    批量删除-->
        <!--                </el-button>-->
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" icon="View" link @click="doExecute(scope.row)">开始任务</el-button>

        <el-button type="primary" icon="View" link @click="showData(scope.row)">执行结果</el-button>

        <el-button type="primary" icon="View" link @click="showLog(scope.row)">查看日志</el-button>

        <el-button type="primary" icon="View" link @click="showResult(scope.row)">查看指标</el-button>
        <!--                <el-button-->
        <!--                    type="primary"-->
        <!--                    link-->
        <!--                    icon="View"-->
        <!--                    v-auth="['demo:match:query']"-->
        <!--                    @click="openDialog(3, '异源图像匹配查看', scope.row)"-->
        <!--                >-->
        <!--                    查看-->
        <!--                </el-button>-->
        <!--                <el-button-->
        <!--                    type="primary"-->
        <!--                    link-->
        <!--                    icon="EditPen"-->
        <!--                    v-auth="['demo:match:edit']"-->
        <!--                    @click="openDialog(2, '异源图像匹配编辑', scope.row)"-->
        <!--                >-->
        <!--                    编辑-->
        <!--                </el-button>-->
        <el-button type="primary" link icon="Delete" v-auth="['demo:match:remove']" @click="deleteMatch(scope.row)"> 删除 </el-button>
      </template>
    </ProTable>
    <FormDialog ref="formDialogRef" />
    <ImportExcel ref="dialogRef" />

    <el-dialog v-if="dialogVisible" v-model="dialogVisible" title="创建任务">
      <el-container>
        <span class="span_class">任务名称</span>
        <el-input v-model="formData.name" placeholder="请输入任务名称"></el-input>
      </el-container>
      <el-container style="margin-top: 20px">
        <span class="span_class">任务文件</span>
        <file @update:model-value="updateFile" :file-size="2048" :file-type="['zip']"></file>
      </el-container>
      <el-button type="primary" @click="doCreateTask">创建</el-button>
    </el-dialog>

    <el-dialog v-model="dataDialogVisible" title="执行结果">
      <el-container direction="vertical">
        <el-container direction="horizontal">
          <el-container direction="vertical">
            <span>hw</span>
            <el-image :src="resultData.url1Prefix + resultData.url1 + results[pageination]" />
          </el-container>
          <el-container direction="vertical">
            <span>kjg</span>
            <el-image :src="resultData.url1Prefix + resultData.url2 + results[pageination]" />
          </el-container>
        </el-container>

        <el-container direction="horizontal" style="margin-top: 20px">
          <el-container direction="vertical">
            <span>overlay_before_registration</span>
            <el-image :src="resultData.url2Prefix + resultData.url3 + results[pageination]" />
          </el-container>
          <el-container direction="vertical">
            <span>overlay_after_registration</span>
            <el-image :src="resultData.url2Prefix + resultData.url4 + results[pageination]" />
          </el-container>
        </el-container>

        <el-container direction="horizontal" style="margin-top: 20px">
          <el-container direction="vertical">
            <span>IR_VIS_obj_in_IR</span>
            <el-image :src="resultData.url2Prefix + resultData.url5 + results[pageination]" />
          </el-container>
          <el-container direction="vertical">
            <span>VIS_obj_in_VIS</span>
            <el-image :src="resultData.url2Prefix + resultData.url6 + results[pageination]" />
          </el-container>
        </el-container>

        <el-container direction="vertical" style="margin-top: 20px">
          <span>coordinates_in_IR.txt</span>
          <el-container v-for="(item, index) in txtData" :key="index">
            {{ item }}
          </el-container>
        </el-container>
      </el-container>
      <el-pagination layout="prev, pager, next" :page-count="results.length" @change="changePage"></el-pagination>
    </el-dialog>

    <el-dialog v-model="logVisible" title="查看日志">
      <el-container direction="vertical">
        <el-container v-for="(item, index) in logData" :key="index">
          {{ item }}
        </el-container>
      </el-container>
    </el-dialog>
    <ResultDialog ref="ResultDialogRef" />
  </div>
</template>

<script setup lang="tsx" name="Match">
import { ref, reactive } from 'vue'
import { useHandleData } from '@/hooks/useHandleData'
import { useDownload } from '@/hooks/useDownload'
import { ElMessage, ElMessageBox } from 'element-plus'
import ProTable from '@/components/ProTable/index.vue'
import ImportExcel from '@/components/ImportExcel/index.vue'
import FormDialog from '@/components/FormDialog/index.vue'
import { ProTableInstance, ColumnProps } from '@/components/ProTable/interface'
import {
  listMatchApi,
  delMatchApi,
  addMatchApi,
  updateMatchApi,
  importTemplateApi,
  importMatchDataApi,
  exportMatchApi,
  getMatchApi,
  createTask,
  execute,
  getResult
} from '@/api/modules/demo/match'
import File from '@/components/Upload/File.vue'
import { getDictsApi } from '@/api/modules/system/dictData'
import ResultDialog from '@/components/ResultDialog/ResultDialog.vue'
import http from '@/api'

const logVisible = ref(false)
const logData = ref([])
const showLog = async function (row) {
  let arr = row.resultPath.split('ObjectDetection_Web')
  let res = await http.get('/profile' + arr[arr.length - 1] + '/log.log')
  logData.value = res.split('\n')
  logVisible.value = true
}

const resultData = ref({
  url1Prefix: '',
  url2Prefix: '',
  url1: 'hw/',
  url2: 'kjg/',
  url3: '/overlay_before_registration/',
  url4: '/overlay_after_registration/',
  url5: '/IR_VIS_obj_in_IR/',
  url6: '/VIS_obj_in_VIS/'
})
const changePage = function (data) {
  pageination.value = data - 1
}
const pageination = ref(0)
const results = ref([])
const dataDialogVisible = ref(false)
const txtData = ref([])

const showData = function (row) {
  getResult({ taskId: row.id }).then(res => {
    if (res.code === 200) {
      let arr = row.resultPath.split('/ObjectDetection_Web')
      resultData.value.url2Prefix = '/api/profile' + arr[arr.length - 1]
      arr = row.preprocessPath.split('/ObjectDetection_Web')
      resultData.value.url1Prefix = '/api/profile' + arr[arr.length - 1] + '/input/'
      results.value = res.data
      pageination.value = 0
      http
        .get(resultData.value.url2Prefix.replace('/api', '') + '/coordinates_in_IR.txt')
        .then(res => {
          txtData.value = res.split('\n')
          dataDialogVisible.value = true
        })
        .catch(err => {
          ElMessage.error('获取coordinates_in_IR.txt失败')
        })
      console.log(resultData.value)
    } else {
      ElMessage.error('获取结果失败!')
    }
  })
}

const ResultDialogRef = ref<InstanceType<typeof ResultDialog> | null>(null)
const showResult = async function (row) {
  let path = row.resultPath.split('ObjectDetection_Web')
  path = path[path.length - 1]
  let result = await http.get('/profile' + path + '/result.json')
  ResultDialogRef.value.openDialog(result)
}

const doExecute = function (row) {
  execute({ taskId: row.id }).then(res => {
    console.log(res)
  })
}

const dialogVisible = ref(false)
const openCreateDialog = function () {
  formData.value = {
    name: '',
    file: null
  }
  dialogVisible.value = true
}
const formData = ref({
  name: '',
  file: null
})
const doCreateTask = function () {
  createTask(formData.value).then(res => {
    if (res.code === 200) {
      dialogVisible.value = false
      ElMessage.success('创建成功')
      proTable.value.getTableList()
    } else {
      ElMessage.error('创建失败,' + res.msg)
    }
  })
}
const updateFile = function (fileId) {
  // console.log('catch')
  formData.value.file = fileId
}

// ProTable 实例
const proTable = ref<ProTableInstance>()

// 删除异源图像匹配信息
const deleteMatch = async (params: any) => {
  await useHandleData(delMatchApi, params.id, '删除【' + params.id + '】异源图像匹配')
  proTable.value?.getTableList()
}

// 批量删除异源图像匹配信息
const batchDelete = async (ids: string[]) => {
  await useHandleData(delMatchApi, ids, '删除所选异源图像匹配信息')
  proTable.value?.clearSelection()
  proTable.value?.getTableList()
}

// 导出异源图像匹配列表
const downloadFile = async () => {
  ElMessageBox.confirm('确认导出异源图像匹配数据?', '温馨提示', { type: 'warning' }).then(() =>
    useDownload(exportMatchApi, '异源图像匹配列表', proTable.value?.searchParam)
  )
}

// 批量添加异源图像匹配
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null)
const batchAdd = () => {
  const params = {
    title: '异源图像匹配',
    tempApi: importTemplateApi,
    importApi: importMatchDataApi,
    getTableList: proTable.value?.getTableList
  }
  dialogRef.value?.acceptParams(params)
}

const formDialogRef = ref<InstanceType<typeof FormDialog> | null>(null)
// 打开弹框的功能
const openDialog = async (type: number, title: string, row?: any) => {
  let res = { data: {} }
  if (row?.id) {
    res = await getMatchApi(row?.id || null)
  }
  // 重置表单
  setItemsOptions()
  const params = {
    title,
    width: 580,
    isEdit: type !== 3,
    itemsOptions: itemsOptions,
    model: type == 1 ? {} : res.data,
    api: type == 1 ? addMatchApi : updateMatchApi,
    getTableList: proTable.value?.getTableList
  }
  formDialogRef.value?.openDialog(params)
}

// 表格配置项
const columns = reactive<ColumnProps<any>[]>([
  { type: 'selection', fixed: 'left', width: 70 },
  { prop: 'id', label: '主键ID' },
  {
    prop: 'name',
    label: '任务名称',
    search: {
      el: 'input'
    },
    width: 120
  },
  {
    prop: 'status',
    label: '任务状态',
    search: {
      el: 'input'
    },
    width: 120,
    tag: true,
    enum: () => getDictsApi('biz_task_status'),
    fieldNames: { label: 'dictLabel', value: 'dictValue' }
  },
  {
    prop: 'parameters',
    label: '调用算法时所用的参数',
    search: {
      el: 'input'
    },
    width: 120
  },
  {
    prop: 'preprocessPath',
    label: '预处理数据路径',
    search: {
      el: 'input'
    },
    width: 120
  },
  {
    prop: 'resultPath',
    label: '结果数据路径',
    search: {
      el: 'input'
    },
    width: 120
  },
  {
    prop: 'startTime',
    label: '开始时间',
    search: {
      el: 'date-picker',
      props: { type: 'datetimerange', valueFormat: 'YYYY-MM-DD HH:mm:ss' }
    },
    width: 120
  },
  {
    prop: 'endTime',
    label: '结束时间',
    search: {
      el: 'date-picker',
      props: { type: 'datetimerange', valueFormat: 'YYYY-MM-DD HH:mm:ss' }
    },
    width: 120
  },
  {
    prop: 'costSecond',
    label: '耗时',
    search: {
      el: 'input'
    },
    width: 120
  },
  {
    prop: 'remarks',
    label: '备注',
    search: {
      el: 'input'
    },
    width: 120
  },
  { prop: 'operation', label: '操作', width: 230, fixed: 'right' }
])
// 表单配置项
let itemsOptions: ProForm.ItemsOptions[] = []
const setItemsOptions = () => {
  itemsOptions = [
    {
      label: '任务名称',
      prop: 'name',
      rules: [{ required: true, message: '任务名称不能为空', trigger: 'blur' }],
      compOptions: {
        placeholder: '请输入任务名称'
      }
    },
    {
      label: '任务状态',
      prop: 'status',
      rules: [{ required: true, message: '任务状态不能为空', trigger: 'blur' }],
      compOptions: {
        placeholder: '请输入任务状态'
      }
    },
    {
      label: '调用算法时所用的参数',
      prop: 'parameters',
      rules: [{ required: true, message: '调用算法时所用的参数不能为空', trigger: 'blur' }],
      compOptions: {
        type: 'textarea',
        clearable: true,
        placeholder: '请输入内容'
      }
    },
    {
      label: '预处理数据路径',
      prop: 'preprocessPath',
      rules: [{ required: true, message: '预处理数据路径不能为空', trigger: 'blur' }],
      compOptions: {
        placeholder: '请输入预处理数据路径'
      }
    },
    {
      label: '结果数据路径',
      prop: 'resultPath',
      rules: [{ required: true, message: '结果数据路径不能为空', trigger: 'blur' }],
      compOptions: {
        placeholder: '请输入结果数据路径'
      }
    },
    {
      label: '开始时间',
      prop: 'startTime',
      rules: [{ required: true, message: '开始时间不能为空', trigger: 'change' }],
      compOptions: {
        elTagName: 'date-picker',
        type: 'date',
        placeholder: '请选择开始时间'
      }
    },
    {
      label: '结束时间',
      prop: 'endTime',
      rules: [{ required: true, message: '结束时间不能为空', trigger: 'change' }],
      compOptions: {
        elTagName: 'date-picker',
        type: 'date',
        placeholder: '请选择结束时间'
      }
    },
    {
      label: '耗时',
      prop: 'costSecond',
      rules: [{ required: true, message: '耗时不能为空', trigger: 'blur' }],
      compOptions: {
        placeholder: '请输入耗时'
      }
    },
    {
      label: '备注',
      prop: 'remarks',
      rules: [{ required: true, message: '备注不能为空', trigger: 'blur' }],
      compOptions: {
        placeholder: '请输入备注'
      }
    }
  ]
}
</script>

<style scoped>
.span_class {
  display: flex;
  align-self: center;
  justify-content: center;
  width: 120px;
  font-size: 13px;
}
</style>
