<template>
  <div>
    <el-form :model="queryParams" inline class="query-form" ref="queryForm">
      <el-form-item label="名称" prop="uqName">
        <el-input v-model="queryParams.uqName" placeholder="请输入名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="是否发布" prop="publish">
        <el-select v-model="queryParams.publish" placeholder="请选择发布类型" clearable filterable>
          <el-option label="已发布" value="1"/>
          <el-option label="未发布" value="0"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getList" :icon="Search">搜索</el-button>
        <el-button @click="handleReset" :icon="Refresh">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="query-btn">
      <el-button type="primary" @click="handleAdd" :icon="Plus" plain>新增</el-button>
      <popover-delete :name="uqNameList" btn-type="danger" :type="'拓扑图查询'"
                      :is-disabled="disabled" :is-plain="true" :btn-icon="Delete"
                      @delete="handleDelete(uqIds)"/>
    </div>
    <div class="table">
      <el-table
          :data="list"
          row-key="id"
          :lazy="true"
          ref="singleTable"
          v-loading="loading"
          @selection-change="handleSelect"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column label="序号" type="index" width="60" align="center"/>
        <el-table-column prop="uqName" label="名称" align="center"/>
        <el-table-column prop="dataSourceId" label="数据源" align="center">
          <template  #default="scope">
            <el-tag >{{getDataSourceOptionItem(scope.row.dataSourceId)}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="publish" label="发布类型" align="center">
          <template #default="scope">
            <tag dict-type="publish_type" :value="scope.row.publish"/>
          </template>
        </el-table-column>
        <el-table-column prop="uqDescribe" label="描述" align="center"/>
        <el-table-column prop="createTime" label="创建时间" align="center"/>
        <el-table-column prop="updateTime" label="更新时间" align="center"/>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <div v-if="scope.row.publish == false">
              <el-button type="text" size="mini"
                         @click="handleEdit(scope.row.id)" >编辑
              </el-button>
              <el-button type="text" size="mini"
                         @click="handleDesign(scope.row)" >设计
              </el-button>
              <popover-delete :name="scope.row.uqName"  :type="'拓扑图查询'"
                              @delete="handleDelete(scope.row.id)"/>
            </div>
            <div v-else>
              <el-button type="text" size="mini" @click="handleDownLine(scope.row)"
                         :icon="Bottom" style="color: red">下线
              </el-button>
              <el-button type="text" size="mini"
                         @click="handleView(scope.row.id)" :icon="View">查看
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <paging :current-page="pageInfo.pageNum" :page-size="pageInfo.pageSize" :page-sizes="[10, 20, 30, 40,50]"
            :total="total" @changeSize="handleSizeChange" @goPage="handleCurrentChange"/>
    <el-dialog v-model="isVisited" :title="title" width="600px">
      <el-form :model="form" ref="formInstance" :rules="formRules" class="dialog-form">
        <el-row>
          <el-col :span="24">
            <el-form-item label="数据源" prop="dataSourceId" v-if="title=='新增拓扑'">
              <el-select v-model="form.dataSourceId" placeholder="数据源" clearable filterable>
                <el-option
                    v-for="item in dataSourceOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="数据源" prop="dataSourceId" v-else>
              <el-text>{{ getDataSourceOptionItem(form.dataSourceId) }}</el-text>
            </el-form-item>
            <el-form-item label="名称" prop="uqName">
              <el-input v-model="form.uqName" placeholder="请输入topo名称"></el-input>
            </el-form-item>
            <el-form-item label="描述" prop="uqDescribe">
              <el-input v-model="form.uqDescribe" placeholder="请输入描述"></el-input>
            </el-form-item>
          </el-col>
          <!--        <el-col :span="11" >-->
          <!--          <el-form-item label="发布类型" prop="publish">-->
          <!--            <el-radio-group v-model="form.publish">-->
          <!--              <el-radio border :label="1">已发布</el-radio>-->
          <!--              <el-radio border :label="0">未发布</el-radio>-->
          <!--            </el-radio-group>-->
          <!--          </el-form-item>-->
          <!--        </el-col>-->
        </el-row>
      </el-form>
      <template #footer>
      <span>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit(formInstance)">确定</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {Search, Refresh, Plus, Delete, Edit,Bottom,View} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from "element-plus";
import {useRouter} from "vue-router";
import {getTopoList, delTopo, addTopo, editTopo, getTopoDetails} from "@/api/custom-query/topo";
import {getDataSourceOption} from "@/api/custom-query/datamodel";
import {topoDownLine} from "@/api/custom-query/topo-search";
import Paging from "@/components/pagination/index.vue";

const router = useRouter()
const queryParams = reactive({
  preview: '',
  publish: '',
  type: '',
  uqName: '',
})
const dataSourceOption = ref()
const queryForm = ref([])
const list = ref([])
const uqIds = ref([])
const uqNameList = ref([])
const total = ref()
const loading = ref(true)
const disabled = ref(true)
const title = ref('')
const isVisited = ref(false)
const pageInfo = reactive({
  pageNum: 1,
  pageSize: 10,
})
const form = ref()
const formInstance = ref()
const formRules = ref({
  dataSourceId: [{required: true, message: '请选择数据源', trigger: "blur"}],
  uqName: [{required: true, message: '请输入topo名称', trigger: 'blur'}],
  uqDescribe: [{required: true, message: '请输入描述', trigger: 'blur'}],
})
//获取数据源select的option
const getOption = () => {
  console.log('getOpeion')
  getDataSourceOption().then(res => {
    if (res.code === 1000) {
      dataSourceOption.value = res.data
      // getList();
    }
  })
}
const getDataSourceOptionItem = (dataSourceId) => {
  if(dataSourceOption.value===undefined)return;
  for (let item of dataSourceOption.value) {
    if (item.value === dataSourceId) {
      return item.label;
    }
  }
  return "";
}
//重置搜索
const handleReset = () => {
  queryForm.value.resetFields()
  getList()
}
//获取数据
const getList = async () => {
  console.log('getList')
  let params = {
    ...queryParams,
    ...pageInfo
  }
  loading.value = true
  getTopoList(params).then(res => {
    if (res.code === 1000) {
      list.value = res.data.rows
      total.value = res.data.total
      loading.value = false
    } else {
      ElMessage.error(res.msg)
    }
  })
}
//重置from表单
const restFrom = () => {
  form.value = {
    dataSourceId: null,
    uqName: null,
    uqDescribe: null
  }

}
//添加
const handleAdd = async () => {
  formRules.value.dataSourceId[0].required = true
  restFrom()
  title.value = "新增拓扑"
  isVisited.value = true
  nextTick(() => {
    // 清空校验
    formInstance.value.clearValidate()
  })
}
//修改
const handleEdit = async (id) => {
  restFrom()
  getTopoDetails(id).then(res => {
    console.log('详情', res.data)
    if (res.code === 1000) {
      formRules.value.dataSourceId[0].required = false
      form.value = res.data
      title.value = "编辑拓扑"
      isVisited.value = true
      nextTick(() => {
        // 清空校验
        formInstance.value.clearValidate()
      })
    } else {
      ElMessage.error(res.msg)
    }
  })
}
//设计
const handleDesign = (row) => {
  router.push({path: `/topo/design/${row.id}`})
}
//下线
const handleDownLine = (row) => {
  ElMessageBox.confirm(`确认撤销名称为${row.uqName}的数据吗? 撤销后分配的查询权限将全部失效`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    customClass: 'red-warning'
  }).then(() => {
    topoDownLine(row.id).then(res => {
      if (res.code === 1000) {
        ElMessage.success(res.msg)
        getList()
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}
//查看
const handleView=(id)=>{
  //router.push({path: `/custom/query/page/${id}`})
}
//单个删除
const handleDelete = async (id) => {
  // let list = []
  // if(Array.isArray(id)){
  //   list=Object.values(id)
  // }else {
  //   list.push(id)
  // }
  // console.log(list,'list')
  // ElMessageBox.confirm(`确认删除名称为${row.uqName}的拓扑图吗?`, '系统提示', {
  //   confirmButtonText: '确定',
  //   cancelButtonText: '取消',
  //   type: 'warning'
  // }).then(() => {
    delTopo(id).then(res => {
      if (res.code === 1000) {
        ElMessage.success(res.msg)
        getList()
      } else {
        ElMessage.error(res.msg)
      }
    })
  // })
}
//取消
const handleCancel = () => {
  restFrom()
  isVisited.value = false
}

//提交
const handleSubmit = async (instance) => {
  if (!instance) return
  instance.validate(async (valid) => {
    if (!valid) return
    if (title.value === '新增拓扑') {
      addTopo(form.value).then(res => {
        if (res.code === 1000) {
          ElMessage.success(res.msg)
          getList()
          isVisited.value = false
        } else {
          ElMessage.error(res.msg)
        }
      })
    } else {
      editTopo(form.value).then(res => {
        if (res.code === 1000) {
          ElMessage.success(res.msg)
          getList()
          isVisited.value = false
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}
//勾选table数据行事件
const handleSelect = async (selection) => {
  if (selection.length !== 0) {
    disabled.value = false
    uqIds.value=selection.map(item => item.id).join()
    uqNameList.value = selection.map(item => item.uqName).join()
  } else {
    disabled.value = true
  }
}
//切换每页显示条数
const handleSizeChange = async (val) => {
  pageInfo.pageSize = val
  await getList()
}

//点击页码进行分页功能
const handleCurrentChange = async (val) => {
  pageInfo.pageNum = val
  await getList()
}
getOption()
getList()
</script>

<style  lang="scss">
.red-warning{
  .el-message-box__content{
    .el-message-box__container{
      .el-icon{
        color: red !important;
      }
    }
  }
}
</style>
