<template>
  <div style="margin:10px">
    <vxe-grid ref="tableRef" v-bind="gridOptions">
      <template #toolbarButtons>
        <vxe-button status="primary" icon="vxe-icon-add" @click="handleAdd">新增</vxe-button>
        <vxe-button status="primary" icon="vxe-icon-delete" @click="handleBatchDelete">删除</vxe-button>
      </template>
      <template #operate="{ row }">
        <vxe-button type="text" status="primary" @click="handleDetail(row)">详情</vxe-button>
        <vxe-button type="text" status="danger" @click="handleEdit(row)">修改</vxe-button>
        <vxe-button type="text" status="danger" @click="handleDelete(row)">删除</vxe-button>
      </template>
    </vxe-grid>
    <a-drawer
      :title="drawerTitle"
      width="40%"
      :mask="true"
      v-model:open="drawerOpen"
      placement="right"
      @after-open-change=""
    >
    <template #extra>
      <a-space>
        <a-button type="primary" @click="handleSave" v-show="!isDetail">保存</a-button>
        <a-button style="margin-right: 8px" @click="handleClose">关闭</a-button>
      </a-space>
    </template>
    <vxe-form ref="formRef"  v-bind="formOptions"></vxe-form>
    </a-drawer>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { VxeGridInstance,VxeColumnPropTypes,VxeGridProps } from 'vxe-table';
import { listListener,delListener,batchDelete,add,update } from "@/components/Process/api/listener"
import { VxeUI, VxeFormInstance, VxeFormProps, VxeFormItemPropTypes, VxeSelectProps } from 'vxe-pc-ui'

import XEUtils from 'xe-utils'

interface RowVO {
  id: string
  username: string
  nickname: string
}

interface SrhParam {
  username: string
  column: string
  order: string
  pageNo: number
  pageSize: number
}

const defaultData: RowVO = {
  id: null,
  name: '',
  eventType: '',
  valueType: '',
  type: '',
  value:''
}


const tableRef = ref<VxeGridInstance>(); 

const isDetail = ref(false)
const formRef = ref()
const loading = ref(false)

const isUpdate = ref(false)
const drawerOpen = ref(false)
const drawerTitle = ref("")

const emit = defineEmits(['callBack']);

const srhParams = ref<SrhParam>({
  username: '',
  column: '',
  order: '',
  pageNo: 1,
  pageSize: 10
});

const eventTypeItemRender = reactive<VxeFormItemPropTypes.ItemRender<RowVO, VxeSelectProps>>({
  name: 'VxeRadioGroup',
  options: [
    { label: 'start', value: 'start' },
    { label: 'end', value: 'end' },
    { label: 'take', value: 'take' },
  ]
})


const typeItemRender = reactive<VxeFormItemPropTypes.ItemRender<RowVO, VxeSelectProps>>({
  name: 'VxeRadioGroup',
  options: [
    { label: '任务监听', value: '1' },
    { label: '执行监听', value: '2' }
  ]
})


const valueTypeItemRender = reactive<VxeFormItemPropTypes.ItemRender<RowVO, VxeSelectProps>>({
  name: 'VxeRadioGroup',
  options: [
    { label: 'JAVA类', value: 'classListener' },
    { label: '表达式', value: 'expressionListener' },
    { label: '代理表达式', value: 'delegateExpressionListener' },
  ]
})

const valueTypeCellRender = reactive<VxeColumnPropTypes.CellRender>({
  name: 'VxeRadioGroup',
  props: {
    disabled: true
  },
  options: [
    { label: 'JAVA类', value: 'classListener' },
    { label: '表达式', value: 'expressionListener' },
    { label: '代理表达式', value: 'delegateExpressionListener' }
  ]
})

const typeCellRender = reactive<VxeColumnPropTypes.CellRender>({
  name: 'VxeRadioGroup',
  props: {
    disabled: true
  },
  options: [
    { label: '任务监听', value: '1' },
    { label: '执行监听', value: '2' }
  ]
})

const eventTypeCellRender = reactive<VxeColumnPropTypes.CellRender>({
  name: 'VxeRadioGroup',
  props: {
    disabled: true
  },
  options: [
    { label: 'start', value: 'start' },
    { label: 'end', value: 'end' },
    { label: 'take', value: 'take' },
  ]
})

const gridOptions = reactive<VxeGridProps<RowVO>>({
  border: true,
  rowConfig: {
    keyField: 'id'
  },
  columnConfig: {
    resizable: true
  },
  checkboxConfig: {
    reserve: true
  },
  pagerConfig: {
    enabled: true,
    pageSize: 10
  },
  toolbarConfig: {
    refresh: false,
    zoom: true,
    custom: true,
    export: true,
    print: true,
    slots: {
      buttons: 'toolbarButtons'
    }
  },
  columns: [
    { type: 'checkbox', visible: true, width: '40', showOverflow: false },
    { title: '主键', field: 'id', align: 'center', width: '10%' },
    { title: '名称', field: 'name', align: 'center', minWidth: '10%' },
    { title: '监听类型', field: 'type', align: 'center', minWidth: '10%',cellRender:typeCellRender },
    { title: '事件类型', field: 'eventType', align: 'center', width: '10%',cellRender:eventTypeCellRender},
    { title: '值类型', field: 'valueType', align: 'center', width: '10%',cellRender:valueTypeCellRender},
    { title: '执行内容', field: 'value', align: 'center', width: '10%'},
    { 
      title: '操作', 
      align: 'center', 
      width: '20%', 
      fixed: 'right', 
      slots: { default: 'operate' }
    }
  ],
  proxyConfig: {
    seq: true,
    props: {
      result: 'result',
      total: 'page.total'
    },
    ajax: {
      query: ({ page }) => {
        return findPageList(page.currentPage, page.pageSize)
      }
    }
  }
})

const findPageList = async (currentPage: number, pageSize: number) => {
  srhParams.value.pageNo = currentPage;
  srhParams.value.pageSize = pageSize;
  const retData = await setData();
  return {
    page: {
      total: retData.total
    },
    result: retData.records
  };
};

async function iniData() {
  await findPageList(1, 10)
}

async function setData() {
  return await listListener({
    pageNo: srhParams.value.pageNo,
    pageSize: srhParams.value.pageSize
  })
}


function handleDetail(row) {
  isDetail.value = true
  drawerOpen.value =  true
  drawerTitle.value = "详情"
  formOptions.data = Object.assign(XEUtils.clone(defaultData, true), row)
}

const handleAdd = () => {
  isDetail.value = false
  drawerOpen.value =  true
  isUpdate.value = false
  drawerTitle.value = "添加"
  formOptions.data = XEUtils.clone(defaultData, true)
}


function handleEdit(row) {
  isDetail.value = false
  drawerOpen.value =  true
  drawerTitle.value = "编辑"
  isUpdate.value = true
  formOptions.data = Object.assign(XEUtils.clone(defaultData, true), row)
}

async function handleDelete(row) {
  await delListener(row.id,handleSuccess)
}

async function handleBatchDelete() {
  const ids = await getSelectIds();
  if (ids.length === 0) {
    return;
  }
  await batchDelete({ ids: ids.join(",") },handleSuccess)
}

async function getSelectIds() {
  let ids = [];
  const $table = tableRef.value;
  if ($table) {
    const selRecords = $table.getCheckboxRecords();
    selRecords.forEach(function (ele) {
      ids.push(ele.id);
    })
  }
  return ids;
}

// 修改 handleSuccess 方法，确保正确刷新表格
const handleSuccess = async () => {
  if (tableRef.value) {
    await tableRef.value.commitProxy('query');
  }
}


const formOptions = reactive<VxeFormProps<RowVO>>({
  titleWidth: '100',
  titleAlign: 'left',
  titleColon: false,
  data: XEUtils.clone(defaultData, true),
  rules: {
    name: [
      { required: true, message: '请输入名称' },
      { min: 3, max: 16, message: '长度在 3 到 16 个字符' }
    ],
    type: [
    { required: true, message: '请指定监听类型' },
    ],
    eventType: [
      { required: true, message: '请只当事件类型' },
    ],
    valueType: [
    { required: true, message: '请指定值类型' },
    ],
    value: [
    { required: true, message: '请填写执行内容' },
    { min: 3, max: 64, message: '长度在 3 到 64 个字符' }
    ],
   
  },
  items: [
    { field: 'name',span:'24',title: '名称', itemRender: { name: 'VxeInput' } },
    { field: 'type',span:'24', title: '监听类型', itemRender: typeItemRender },
    { field: 'eventType',span:'24', title: '事件类型', itemRender: eventTypeItemRender },
    { field: 'valueType',span:'24', title: '值类型',  itemRender: valueTypeItemRender  },
    { field: 'value',span:'24', title: '执行内容', itemRender:  { name: 'VxeInput' } },

  ]
})

const handleSave = async () => {
  const $form = formRef.value
  if ($form) {
    loading.value = true
    const errMap = await $form.validate()
    if (!errMap) {
      if(isUpdate.value){
        await update(formOptions.data)
      } else {
        await add(formOptions.data)
      }
      await handleSuccess();
      await handleClose();
    }
    loading.value = false
  }
}

const handleClose = async() => {
  drawerOpen.value =  false
}

defineExpose({
  iniData
});
</script>