<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import {
  getRepIndexSetListApi,
  saveRepIndexSetApi,
  delRepIndexSetListApi,
  delRepIndexSetApi,
  queryRepIndexSetApi,
  importExcelApiUrl,
  exportExcelApi
} from '@/api/dataset/RepIndexSet'

import { TableData } from '@/api/dataset/RepIndexSet/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 } 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 { Dialog } from '@/components/Dialog'
import { getWidth } from '@/utils';
import Detail from './components/Detail.vue'
import { Upload } from '@/components/Upload'
import { useRouter } from 'vue-router'
import { getIndexType } from '@/api/dataset/RepIndexSet';
import {
  getIndexCategoryTreeApi
} from '@/api/dataset/IndexCategory'
import { transfDictList } from '@/utils';
const router = useRouter();
const { t } = useI18n()

const ids = ref<string[]>([])
let indexType_param_LIST = ref([]);//处理后的指标类型列表
let IndexTypeParamsList = ref([]);//处理之前的指标类型列表
let frequency_param_LIST = ref([]);


//获取字典项
const getDictInfoList = async ()=>{
       const res = await getIndexType({ paramName: 'frequency_param', systemCode: 'ordb' });
       frequency_param_LIST.value = transfDictList(res.body.result);
}
getDictInfoList();

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

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

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'selection',
    type: 'selection',
    fixed: true
  },
  {
    field: 'indexsetCode',
    label: '指标集编码'
  },
  {
    field: 'indexsetName',
    label: '指标集名称'
  },
  {
    field: 'indexsetType',
    label: '指标集类型',
    slots:{
        default:(data)=>{
            const node = indexType_param_LIST.value.filter(item=>{
                return item.id == data.row.indexsetType
            })[0];
            return <span>{node?node?.nodeName:''}</span>
        }
    }
  },
  {
    field: 'modelCode',
    label: '数据模型编码',
    slots:{
      default:(data:any)=>{
        return <ElLink type="primary" underline={true} onClick={() => turnToDataModule(data.row)}>{data.row.modelCode}</ElLink>
      }
    }
  },
  {
    field: 'beginDate',
    label: '开始日期'
  },
  {
    field: 'endDate',
    label: '结束日期'
  },
  {
    field: 'frequency',
    label: '频度',
    slots:{
         default:(data)=>{
            return <span>{data.row.frequency?frequency_param_LIST.value[data.row.frequency]?.label:''}</span>
         }
    }
  },
  {
    field: 'description',
    label: '描述'
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    width: 200,
    fixed: 'right',
    slots: {
      default: (data: any) => {
        return (
          <>
           <ElLink type="primary" underline={false} onClick={() => getDataConfig(data.row)}>
              数据配置
            </ElLink>
            <ElLink type="primary" underline={false} onClick={() => action(data.row, 'edit')}>
              {t('tableDemo.edit')}
            </ElLink>
            <ElPopconfirm
              title={t('common.delTableMsg')}
              width={200}
              v-slots={{
                reference: () => {
                  return (
                    <>
                      <ElLink type="primary" underline={false}>
                        {t('tableDemo.del')}
                      </ElLink>
                    </>
                  )
                }
              }}
              onConfirm={() => delData(data.row)}
            ></ElPopconfirm>
          </>
        )
      }
    }
  }
].map(item => ({ minWidth: item.label ? getWidth(item.label) : 120, ...item }) as TableColumn))

const searchSchema = reactive<FormSchema[]>([
  {
    field: 'indexsetCode',
    label: '指标集编码',
    componentProps: {},
    component: 'Input'
  },
  {
    field: 'indexsetType',
    label: '指标集类型',
    colProps: { span: 100 },
         componentProps: {
           checkStrictly: true,
           nodeKey: 'id',
           props: { children: 'childs', label: 'nodeName' },
           filterable: true,
           multiple: true,
           collapseTags: true,
           showCheckbox: true,
           style: { minWidth: '200px' },
           checkOnClickNode: true,
         },
         component: 'TreeSelect',
         optionApi: async () => {
           const res = await getIndexCategoryTreeApi();
           IndexTypeParamsList.value = res;
           indexType_param_LIST.value = res;
           res.forEach(item=>{
                indexType_param_LIST.value = indexType_param_LIST.value.concat(item.childs);
           });
           console.log(indexType_param_LIST,"indexType_param_LIST");
           return res;
         }
  },
  {
      field: 'indexDate',
      label: '日期范围',
      componentProps: {
        type:'daterange',
        valueFormat: 'YYYYMMDD'
      },
      component: 'DatePicker'
  }
])

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 turnToDataModule = (data)=>{
  router.push(
    {
      name:'repDataModel',
      query:{
        modelCode:data.modelCode
      }
    }
  )
}

/**单行查询**/
const action = async (row: TableData, type: string) => {
  let detailLoading = ElLoading.service({
    background: 'rgba(0, 0, 0, 0.7)'
  })
  const res = await queryRepIndexSetApi(row.indexsetCode, row.beginDate, row.endDate)
    .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 getDataConfig = (data)=>{
  router.push({
    name:'indexMannageMs',
    query:{
      indexsetCode:data.indexsetCode,
    }
  })
}

const AddAction = () => {
  dialogTitle.value = t('tableDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = 'add'
}
const saveLoading = ref(false)

/** 保存 **/
const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const res = await saveRepIndexSetApi(formData)
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}

const delLoading = ref(false)

/** 批量删除  **/
const delDataBatch = async () => {
  const elTableExpose = await getElTableExpose()
  ids.value = elTableExpose?.getSelectionRows().map((v: TableData) => { v.indexsetCode, v.beginDate, v.endDate }) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

/** 单行删除 */
const delData = async (row: TableData) => {
  const res = await delRepIndexSetApi(row.indexsetCode, row.beginDate, row.endDate)
  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
}

/** 导出Excel */
const exportExcel = async () => {
  const data = { ...unref(searchParams),fileName:'指标集.xls' }
  await exportExcelApi(data)
}
</script>

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

    <Table
      :columns="tableColumns"
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      default-expand-all
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @selection-change="onSelectionChange"
      @register="tableRegister"
      @refresh="refresh"
    >
      <template #buttons>
        <ElButton type="primary" @click="AddAction">{{ t('tableDemo.add') }}</ElButton>
        <Upload :url="importExcelApiUrl" :callback="getList"> <ElButton type="primary">导入</ElButton> </Upload>
        <ElButton type="primary" @click="exportExcel()">导出</ElButton>
        <ElButton :loading="delLoading" type="primary" :disabled="disabled" @click="delDataBatch()">
          {{ t('tableDemo.del') }}
        </ElButton>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :current-row="currentRow"
      :indexTypeParam="IndexTypeParamsList"
      :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>