<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 { listExpression,delExpression,batchDelete,add,update } from "@/components/Process/api/expression"
import { VxeUI, VxeFormInstance, VxeFormProps, VxeFormItemPropTypes, VxeSelectProps } from 'vxe-pc-ui'
import XEUtils from 'xe-utils'

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

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

const isDetail = ref(false)

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

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

const tableRef = ref<VxeGridInstance>(); // 添加类型定义

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

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


const statusCellRender = reactive<VxeColumnPropTypes.CellRender>({
  name: 'VxeRadioGroup',
  props: {
    disabled: true
  },
  options: [
  { label: '成功', value: '1' },
  { label: '失败', value: '0' }
  ]
})

const dataTypeCellRender = reactive<VxeColumnPropTypes.CellRender>({
  name: 'VxeRadioGroup',
  props: {
    disabled: true
  },
  options: [
    { label: '指定类型', value: 'fixed' },
    { label: '动态选择', value: 'dynamic'}
  ]
})


const gridOptions = reactive<VxeGridProps<RowVO>>({
  border: true,
  rowConfig: {
    keyField: 'id'
  },
  columnConfig: {
    resizable: true
  },
  checkboxConfig: {
    reserve: true
  },
  pagerConfig: {
    enabled: true,
    pageSize: 10
  },
  // editConfig: {
  //   trigger: 'dblclick',
  //   mode: 'cell'
  // },
  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: 'left', width: '10%' },
    { title: '名称', field: 'name', align: 'left', minWidth: '20%' , editRender: { name: 'input' }},
    { title: '表达式内容', field: 'expression', align: 'left', minWidth: '20%' , editRender: { name: 'input' }},
    { title: '指定类型', field: 'dataType', align: 'left', width: '10%', cellRender: dataTypeCellRender},
    { title: '状态', field: 'status', align: 'left', width: '10%', cellRender: statusCellRender},
    { 
      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 listExpression({
    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)
}

const 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 delExpression(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 defaultData: RowVO = {
  id: null,
  name: '',
  expression: '',
  dataType: ''
}

const dataTypeItemRender = reactive<VxeFormItemPropTypes.ItemRender<RowVO, VxeSelectProps>>({
  name: 'VxeRadioGroup',
  options: [
    { label: '指定类型', value: 'fixed' },
    { label: '动态选择', value: 'dynamic' }
  ]
})

const statusItemRender = reactive<VxeFormItemPropTypes.ItemRender<RowVO, VxeSelectProps>>({
  name: 'VxeRadioGroup',
  options: [
    { label: '成功', value: '1' },
    { label: '失败', value: '0' }
  ]
})


const formOptions = reactive<VxeFormProps<RowVO>>({
  titleWidth: 'auto',
  titleAlign: 'left',
  titleColon: false,
  data: XEUtils.clone(defaultData, true),
  rules: {
    name: [
      { required: true, message: '请输入名称' },
      { min: 3, max: 16, message: '长度在 3 到 16 个字符' }
    ],
    expression: [
      { required: true, message: '表达式内容' },
      { min: 3, max: 64, message: '长度在 3 到 64 个字符' }
    ],
    dataType: [
      { required: true, message: '请指定类型' },
    ],
    status: [
      { required: true, message: '状态' },
    ],
  },
  items: [
    { field: 'name',span:'24',title: '名称', itemRender: { name: 'VxeInput' } },
    { field: 'expression',span:'24', title: '表达式内容', itemRender: { name: 'VxeInput' } },
    { field: 'dataType',span:'24', title: '指定类型',  itemRender: dataTypeItemRender },
    { field: 'status',span:'24', title: '状态',  itemRender: statusItemRender },

  ]
})

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>