<script setup lang="tsx">
import { ContentWrap } from '../../../components/ContentWrap'
import { Search } from '../../../components/Search'
import { Dialog } from '../../../components/Dialog'
import { Table } from '../../../components/Table'
import {
  list,
  update,
  create,
  del,
  deleteMult,
  deployment,
  find
} from '../../../api/system-config/lowcode'
import type { IFlowRow } from '../../../api/system-config/lowcode'

import { useTable } from '../../../hooks/web/useTable'
import { ref, unref, reactive } from 'vue'
import Write from './components/Write.vue'
import { CrudSchema, useCrudSchemas } from '../../../hooks/web/useCrudSchemas'
import { BaseButton } from '../../../components/Button'
import BpmnComponent from './components/Bpmn/App.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 批量操作的参数
const ids = ref<number[]>([])
const deployIds = ref<string[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await list({
      current: unref(currentPage),
      size: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list,
      total: res.data.totalCount
    }
  },
  fetchDelApi: async () => {
    const res = await deleteMult({
      ids: unref(ids),
      deployIds: unref(deployIds)
    })
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'index',
    label: '序号',
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'name',
    label: '流程名称',
    table: {
      slots: {
        default: (data: any) => {
          return <>{data.row.name}</>
        }
      }
    },
    form: {
      component: 'Input'
    }
  },
  {
    field: 'description',
    label: '描述',
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return <>{data.row.description || '-'}</>
        }
      }
    },
    form: {
      component: 'Input'
    }
  },
  {
    field: 'deployId',
    label: '状态',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return <>{data.row.deployId ? '启用' : '未启用'}</>
        }
      }
    }
  },
  {
    field: 'action',
    width: '280px',
    label: '操作',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <BaseButton size="small" type="primary" onClick={() => action(data.row, 'edit')}>
                编辑
              </BaseButton>
              {data.row.deployId ? null : (
                <BaseButton size="small" type="success" onClick={() => deploy(data.row)}>
                  发布
                </BaseButton>
              )}
              <BaseButton size="small" type="primary" onClick={() => design(data.row)}>
                流程设计
              </BaseButton>
              <BaseButton size="small" type="danger" onClick={() => delData(data.row)}>
                删除
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<IFlowRow | null>(null)
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = '新增'
  currentRow.value = null
  dialogVisible.value = true
  actionType.value = 'add'
}

const delLoading = ref(false)

const delData = async (row: IFlowRow | null) => {
  if (row) {
    ElMessageBox.confirm('确认删除？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      await del(row?.id || 0).then(() => {
        getList()
      })
    })
  } else {
    const elTableExpose = await getElTableExpose()
    ids.value = elTableExpose?.getSelectionRows().map((v: IFlowRow) => v.id) || []

    if (ids.value.length === 0) {
      ElMessage.warning('请选择要删除的数据')
      return
    }

    deployIds.value = elTableExpose?.getSelectionRows().map((v: IFlowRow) => v.deployId) || []
    delLoading.value = true

    await delList(unref(ids).length).finally(() => {
      delLoading.value = false
    })
  }
}

const action = (row: IFlowRow, type: string) => {
  dialogTitle.value = type === 'edit' ? '编辑' : '详情'
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    const res = await (actionType.value === 'add' ? create(formData) : update(formData))
      .catch(() => {})
      .finally(() => {
        saveLoading.value = false
      })
    if (res) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}

// 流程设计部分

const designDialogVisible = ref(false)
const saveFlowLoading = ref(false)
const bpmn = ref()
const rowXml = ref('')
const design = async (row: IFlowRow) => {
  currentRow.value = row
  designDialogVisible.value = true
  const data = await getRowData(row.id || 0)
  rowXml.value = data
}

// 获取当前行的详情
const getRowData = async (id) => {
  const { success, data } = await find(id)
  if (success && data) {
    return Promise.resolve(data.jsonXml)
  } else return ''
}

const saveFlow = async () => {
  const xml = await bpmn.value.xmlString
  if (!xml) {
    ElMessage.warning('未配置流程')
    return
  }
  // const xml = await bpmn.value.getXML()
  // if (xml) {
  saveFlowLoading.value = true
  const res = await update({
    id: Number(currentRow.value?.id),
    jsonXml: xml
  })
    .catch(() => {})
    .finally(() => {
      saveFlowLoading.value = false
    })
  if (res) {
    designDialogVisible.value = false
    currentPage.value = 1
    getList()
  }
  // }
}

// 发布
const deploy = async (row: IFlowRow) => {
  if (row.deployId) {
    ElMessage.warning('已发布，不可继续操作')
    return
  }
  const xml = await getRowData(row?.id || 0)
  if (!xml) {
    ElMessage.warning('未设计流程，不可发布')
    return
  }
  ElMessageBox.confirm('确认发布？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deployment(row?.id || 0).then(() => {
      getList()
    })
  })
}
</script>

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

    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">新增</BaseButton>
      <BaseButton :loading="delLoading" type="danger" @click="delData(null)"> 批量删除</BaseButton>
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="currentRow"
    />

    <!-- <Detail
      v-if="actionType === 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="currentRow"
    /> -->

    <template #footer>
      <BaseButton v-if="actionType !== 'detail'" type="primary" :loading="saveLoading" @click="save"
        >保存
      </BaseButton>
      <BaseButton @click="dialogVisible = false">关闭</BaseButton>
    </template>
  </Dialog>

  <Dialog
    v-model="designDialogVisible"
    title="设计"
    width="90%"
    maxHeight="700px"
    class="design-dialog"
  >
    <BpmnComponent ref="bpmn" :xml="rowXml" />
    <template #footer>
      <BaseButton type="primary" :loading="saveFlowLoading" @click="saveFlow">保存</BaseButton>
      <BaseButton @click="designDialogVisible = false">关闭</BaseButton>
    </template>
  </Dialog>
</template>
