<script setup lang="tsx">
import { onMounted, reactive, ref, unref } from 'vue'
import {
  getIndexCategoryListApi,
  delIndexCategoryListApi,
  delIndexCategoryApi,
  queryIndexCategoryApi,
  getIndexCategoryTreeApi
} from '@/api/dataset/IndexCategory'
import { TableData } from '@/api/role/types'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import {
  ElButton,
  ElLink,
  ElLoading,
  ElPopconfirm,
  ElMessage,
  ElRow,
  ElCol,
  ElTree
} from 'element-plus'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { Dialog } from '@/components/Dialog'
import router from '@/router'

defineOptions({
  name: 'IndexSearchServiceMs',
});
const { t } = useI18n()

const ids = ref<string[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getIndexCategoryListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.body.list,
      total: res.body.total
    }
  },
  fetchDelApi: async () => {
    const res = await delIndexCategoryListApi(unref(ids))
    return !!res
  }
})

const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, refresh } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'selection',
    type: 'selection'
  },
  {
    field: 'dicid',
    label: '分类编号'
  },
  {
    field: 'dicname',
    label: '分类名称'
  },
  {
    field: 'dicvalue',
    label: '分类值'
  },
  {
    field: 'parentname',
    label: '上级分类'
  },
  {
    field: 'description',
    label: '分类描述'
  },
  {
    field: 'status',
    label: '分类状态'
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    width: 160,
    slots: {
      default: (data: any) => {
        return (
          <>
            <ElLink type="primary" underline={false} onClick={() => lookRule(data.row)}>
              {'查询'}
            </ElLink>
          </>
        )
      }
    }
  }
])

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'dicname',
    label: '指标名称',
    component: 'Input'
  }
])

const searchParams = ref({})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref()
const actionType = ref('')

const writeRef = ref<ComponentRef<typeof Write>>()

/**单行查询**/
const action = async (row: any, type: string) => {
  let detailLoading = ElLoading.service({
    background: 'rgba(0, 0, 0, 0.7)'
  })
  const res = await queryIndexCategoryApi(row.dicid)
    .catch(() => {})
    .finally(() => {
      detailLoading.close()
    })
  detailLoading.close()
  if (res) {
    const data = res.body.result
    dialogTitle.value = t(type === 'edit' ? 'tableDemo.edit' : 'tableDemo.detail')
    actionType.value = type
    currentRow.value = data
    dialogVisible.value = true
  }
}

/** 指标查询 **/
const lookRule = (data)=>{
  router.push({
    name:'IndexSearchServiceMs',
    query:{
      dicid:data.dicid,
    }
  })
}

/** 单行删除 */
const delData = async (row: TableData) => {
  const res = await delIndexCategoryApi(row.dicid)
  if (res) {
    const { code, errMsg } = res.head
    if (code === '0') {
      ElMessage.success('删除成功!')
      getList()
    } else {
      ElMessage.error(errMsg || '删除失败!')
    }
  }
}

const disabled = ref(true)

const onSelectionChange = (selection: TableData[]) => {
  disabled.value = selection.length === 0
}

const treeData = ref<any>([])

onMounted(() => {
  getIndexCategoryTreeApi().then((res) => (treeData.value = res))
})

const defaultProps = { children: 'childs', label: 'nodeName' }
const queryOntInfo = (node,data)=>{
    console.log(node,data)
    setSearchParams({dicid:data.id});
    /*queryIndexCategoryApi(data.props.dicid).then(res=>{
     console.log(res,"查询的信息");
        dataList = [];
        if(res.body.result){
            dataList.push(res.body.result);
        }


    })*/
}
</script>

<template>
  <ContentWrap>
    <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />

    <ElRow>
      <ElCol :span="6" style="padding: 10px"
      ><ElTree :data="treeData" :props="defaultProps" nodeKey="id">
        <template #default="{ node, data }">
          <span class="r-tree-title">
            <span class="r-plain-tree-title" @click="queryOntInfo(node,data)">{{ node.label }}</span>
            <span>
              <ElLink :underline="false" @click="(e) => AddAction(e, data)">
                <Icon icon="ep:circle-plus" :size="14" />
              </ElLink>
              <ElLink :underline="false" @click="() => action(data, 'edit')">
                <Icon icon="ep:edit" :size="14" />
              </ElLink>
              <ElPopconfirm
                @confirm="() => delData(data)"
                :title="t('common.delTableMsg')"
                :width="200"
              >
                <template #reference>
                  <ElLink :underline="false">
                    <Icon icon="ep:remove" :size="14" />
                  </ElLink>
                </template>
              </ElPopconfirm>
            </span>
          </span>
        </template>
      </ElTree>
      </ElCol>
      <ElCol :span="18">
        <Table
          :columns="tableColumns"
          v-model:pageSize="pageSize"
          v-model:currentPage="currentPage"
          default-expand-all
          node-key="id"
          :data="dataList"
          :loading="loading"
          :pagination="{
            total
          }"
          @selection-change="onSelectionChange"
          @register="tableRegister"
          @refresh="refresh"
        />
      </ElCol>
    </ElRow>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :current-row="currentRow"
      :action-type="actionType"
    />
    <Detail v-if="actionType === 'detail'" :current-row="currentRow" />
    <template #footer>
      <ElButton v-if="actionType !== 'detail'" type="primary" :loading="saveLoading" @click="save">
        {{ t('dialogDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>

<style lang="less" scoped>
.el-tree-node {
  .el-link {
    opacity: 0;
    margin-left: 6px;
  }
}

.el-tree-node__content:hover .el-link {
  opacity: 1;
}
</style>
