<template>
  <div class="w-full h-full bg-white p-4">
    <p class="font-bold text-lg leading-10 border-b-2">{{ route.query.informationType }}</p>
   
    <vxe-form
      title-overflow
      title-colon
      title-width="120"
      title-align="right"
      :data="form"
      @submit="onSearch"
      @reset="onReset">
      <vxe-form-item  v-for="(item, index) in formColumn"   :key="index"  :field="item"   :title="item" span="6" :item-render="item">
        <template #default>
          <vxe-input v-model="form[item]"></vxe-input>
        </template>
      </vxe-form-item>

      <vxe-form-item align="right" span="24" :item-render="{}">
        <template #default>
          <vxe-button type="submit" status="primary" content="查询"></vxe-button>
          <vxe-button type="reset" content="重置"></vxe-button>
          <vxe-button type="primary" @click="onCopy">查询参数</vxe-button>
        </template>
      </vxe-form-item>
    </vxe-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" min-height="460" border :loading="loading" :data="tableData" :row-config="{keyField:'id',isHover: true}">
        <vxe-column field="id" title="ID" width="100"></vxe-column>

        <vxe-column v-for="(row, index) in tableColumn" :field="row" min-width="150" :title="row" :key="index" 
        show-overflow/>

        <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 defualtForm = 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] = ""
        defualtForm.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()
  }
  onReset()
}

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

const handleUpdate = (row: any) => {
  visible.value = true
  title.value = "修改资料"
  informationInfo.value = row
  //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>
