<template>
  <div class="w-full h-full bg-white p-4">
    <p class="font-bold text-lg leading-10 border-b-2">资料库管理</p>
    <el-form class="pt-4" ref="formRef" :model="form" inline>
      <el-form-item v-for="(item, index) in formColumn" :label="item" :key="index" :prop="item">
        <el-input v-model="form[item]" placeholder="" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="default" @click="onReset">重置</el-button>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button type="primary" @click="onCopy">查询参数</el-button>
      </el-form-item>
    </el-form>
    <div>
      <vxe-toolbar>
        <template #buttons>
          <el-button type="primary" @click="handleAdd">新增</el-button>
          <el-button type="primary" @click="handleImport">导入</el-button>
          <!-- <el-button type="danger" @click="handleDel">删除</el-button> -->
        </template>
      </vxe-toolbar>
      <vxe-table ref="xTable" size="small" min-height="460" border :loading="loading" :data="tableData">
        <vxe-column v-for="(row, index) in tableColumn" :field="row" min-width="150" :title="row" :key="index" />
        <vxe-column title="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleUpdate(row)">修改</el-button>
            <el-button link type="danger" size="small" @click="handleDel(row)">删除</el-button>
          </template>
        </vxe-column>
      </vxe-table>
      <vxe-pager v-if="total > 0" size="small" background v-model:current-page="form.currentPage"
        v-model:page-size="form.pageSize" :total="total" @page-change="onSearch"
        :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes', 'FullJump', 'Total']">
      </vxe-pager>
    </div>
    <InformationInfoDialog :visible="visible" :title="title" :informationInfo="informationInfo" @onChange="onChange" />
    <UploadInformationInfoDialog :visible="importVisible" @onImportChange="onImportChange" />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { getInformationListTitlesApi, getInformationListApi, delInformationInfoApi } from '@/api/customer'
import { ElMessage, ElMessageBox, type FormInstance, type Action } from 'element-plus'
import type { VxeTableInstance } from 'vxe-table'
import { useRoute } from 'vue-router'
import InformationInfoDialog from './components/information-info-dialog.vue';
import UploadInformationInfoDialog from './components/upload-information-info-dialog.vue';

const route = useRoute()
const loading = ref(false)
const formRef = ref<FormInstance>()
const formColumn = ref([])
const form = ref<any>({})
const total = ref(0)
const xTable = ref<VxeTableInstance>()
const tableData = ref([])
const tableColumn = ref([])
const visible = ref(false)
const informationInfo = ref({})
const title = ref("新增资料")
const importVisible = ref(false)

const initData = async () => {
  loading.value = true
  try {
    const params = {
      informationType: route.query.informationType
    }
    const { data } = await getInformationListTitlesApi(params)
    if (data?.code == 200) {
      tableColumn.value = data?.result.filter((item: any) => {
        if (!['id', '_X_ROW_KEY'].includes(item)) {
          return item
        }
      })
      formColumn.value = data?.result.filter((item: any) => {
        if (!['id', '_X_ROW_KEY'].includes(item)) {
          return item
        }
      })
      formColumn.value.forEach((ele: any) => {
        form.value[ele] = ""
      });
      getInformationListApi(params).then((res) => {
        if (res.data?.code == 200) {
          tableData.value = res.data?.result
        }
      })
    }
  } catch (error) {

  } finally {
    loading.value = false
  }
}

const getInformationList = async (params: any) => {
  loading.value = true
  try {
    const res = await getInformationListApi(params);
    if (res.data?.code == 200) {
      tableData.value = res.data?.result
    }
  } catch (error) {

  } finally {
    loading.value = false
  }
}

const onReset = () => {
  if(formRef?.value) {
    formRef?.value.resetFields()
  }
  const params = {
    informationType: route.query.informationType
  }
  getInformationList(params)
}

const onSearch = () => {
  const params = {
    informationType: route.query.informationType,
    json: JSON.stringify(form.value)
  }
  getInformationList(params)
}

const onCopy = () => {
  const data = Object.keys(form.value).reduce((acc: any, key) => {
    if (form.value[key]) {
      acc[key] = form.value[key]
    }
    return acc
  }, {})
  ElMessageBox.confirm(data, '查询参数', {
    confirmButtonText: '复制',
    cancelButtonText: '取消'
  }).then(() => {
    const input = document.createElement("input")
      input.value = JSON.stringify(data)
      document.body.appendChild(input)
      input.select()
      document.execCommand("Copy")
      document.body.removeChild(input)
      ElMessage({
        type: 'success',
        message: '复制成功'
      })
  })
}

const onChange = (type: any) => {
  visible.value = false
  if (type != 'close') {
    onReset()
  }
}

const handleAdd = () => {
  visible.value = true
  title.value = "新增资料"
  informationInfo.value = form.value
}

const handleUpdate = (row: any) => {
  visible.value = true
  title.value = "修改资料"
  informationInfo.value = Object.assign(form.value, row)
}

const handleDel = async (row: any) => {
  const params = {
    informationType: route.query.informationType,
    id: row.id
  }
  const { data } = await delInformationInfoApi(params)
  if (data?.code == 200) {
    ElMessage.success(`${data?.message}`)
    onReset()
  } else {
    ElMessage.error(`${data?.message}`)
  }
}

const handleImport = () => {
  importVisible.value = true
}

const onImportChange = (type: any) => {
  importVisible.value = false
  if (type != 'close') {
    initData()
  }
}

onMounted(() => {
  if (!route.query.informationType) {
    return
  }
  initData()
})
</script>

<style lang="scss" scoped></style>
