<script setup lang="ts">
import AForm from '@/components/AForm/index.vue'
import { FormConfigType } from '@/components/AForm/type'
import { ToolbarConfigType } from '@/components/AToolbar/type'
import { ColumnConfigType } from '@/components/ATable/type'
import { StrAnyObj, StrAnyObjArr } from '@/typings'
import { useHandleData } from '@/utils/useHandleData'
import {
  getDefinitionPageApi,
  getDefinitionApi,
  addDefinitionApi,
  updateDefinitionApi,
  deleteDefinitionApi,
  getChartNoColorApi,
  activeApi,
  unActiveApi,
  publishApi,
  unPublishApi,
  copyDefApi
} from '@/api/flow/definition'
import Design from '@/views/flow/definition/design.vue'

const queryRef = ref<InstanceType<typeof AForm>>()
const formRef = ref<InstanceType<typeof AForm>>()
const designVisibleRef = ref<InstanceType<typeof Design>>()

const designVisible = ref<boolean>(false)

const showQuery = ref<boolean>(true)
const pageTotal = ref<number>(0)

const queryData = ref<StrAnyObj>({ pageNum: 1, pageSize: 10 })
const tableData = ref<StrAnyObjArr>([])
const formData = ref<StrAnyObj>({})

const dialogTitle = ref<string>('')
const dialogVisible = ref<boolean>(false)

const chartVisible = ref(false)
const imgUrl = ref('')

const queryConfig: FormConfigType[] = [
  {
    type: 'input',
    prop: 'flowCode',
    label: '流程编码'
  },
  {
    type: 'input',
    prop: 'flowName',
    label: '流程名称'
  },
  {
    type: 'version',
    prop: 'version',
    label: '流程版本'
  }
]

const toolbarConfig: ToolbarConfigType[] = [
  {
    common: 'search',
    click() {
      queryData.value.pageNum = 1
      getPage()
    }
  },
  {
    common: 'reset',
    click() {
      queryRef.value?.resetFields()
      getPage()
    }
  },
  {
    common: 'add',
    click() {
      dialogVisible.value = true
      dialogTitle.value = '新增'
    }
  }
]

const columnConfig: ColumnConfigType[] = [
  {
    prop: 'flowCode',
    label: '流程编码'
  },
  {
    prop: 'flowName',
    label: '流程名称'
  },
  {
    prop: 'version',
    label: '流程版本'
  },
  {
    prop: 'isPublish',
    label: '是否发布',
    dict: 'is_publish'
  },
  {
    prop: 'activityStatus',
    label: '激活状态',
    dict: 'activity_status'
  },
  {
    prop: 'formPath',
    label: '表单路径',
    showOverflowTooltip: true
  },
  {
    width: 500,
    handleConfig: [
      {
        text: '流程设计',
        click(row) {
          designVisibleRef.value?.open(row.id, row.isPublish === 1)
        }
      },
      {
        text: '流程图',
        click(row) {
          getChartNoColorApi(row.id).then((resp) => {
            chartVisible.value = true
            imgUrl.value = 'data:image/gif;base64,' + resp
          })
        }
      },
      {
        text: '发布',
        if: (row) => row.isPublish === 0,
        click(row) {
          useHandleData(`是否发布流程编码为【${row.flowCode}】的数据项？`, () => {
            publishApi(row.id).then(() => {
              ElMessage.success('发布成功')
              getPage()
            })
          })
        }
      },
      {
        text: '取消发布',
        if: (row) => row.isPublish === 1,
        click(row) {
          useHandleData(`是否取消发布流程编码为【${row.flowCode}】的数据项？`, () => {
            unPublishApi(row.id).then(() => {
              ElMessage.success('取消发布成功')
              getPage()
            })
          })
        }
      },
      {
        text: '激活',
        if: (row) => row.activityStatus === 0,
        click(row) {
          useHandleData(`是否激活流程编码为【${row.flowCode}】的数据项？`, () => {
            activeApi(row.id).then(() => {
              ElMessage.success('激活成功')
              getPage()
            })
          })
        }
      },
      {
        text: '挂起',
        if: (row) => row.activityStatus === 1,
        click(row) {
          useHandleData(`是否挂起流程编码为【${row.flowCode}】的数据项？`, () => {
            unActiveApi(row.id).then(() => {
              ElMessage.success('挂起成功')
              getPage()
            })
          })
        }
      },
      {
        text: '复制流程',
        click(row) {
          useHandleData(`是否复制流程编码为【${row.flowCode}】的数据项？`, () => {
            copyDefApi(row.id).then(() => {
              ElMessage.success('复制成功')
              getPage()
            })
          })
        }
      },
      {
        common: 'update',
        if: (row) => row.isPublish === 0,
        click(row) {
          dialogVisible.value = true
          dialogTitle.value = '编辑'
          getDefinitionApi(row.id).then((resp: StrAnyObj) => {
            formData.value = resp
            if (formData.value.listenerType) {
              formData.value.listenerType = formData.value.listenerType.split(',')
            }
          })
        }
      },
      {
        common: 'delete',
        if: (row) => row.isPublish === 0,
        click(row) {
          handleRemove(row.id)
        }
      }
    ]
  }
]

const formConfig: FormConfigType[] = [
  {
    type: 'input',
    prop: 'flowCode',
    label: '流程编码',
    rule: [{ required: true, message: '流程编码不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'flowName',
    label: '流程名称',
    rule: [{ required: true, message: '流程名称不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'version',
    label: '流程版本',
    rule: [{ required: true, message: '流程版本不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'formPath',
    label: '表单路径',
    rule: [{ required: true, message: '表单路径不能为空', trigger: 'blur' }]
  },
  {
    type: 'input',
    itemType: 'textarea',
    prop: 'ext',
    label: '扩展字段',
    rows: 3
  },
  {
    type: 'select',
    prop: 'listenerType',
    label: '监听器类型',
    multiple: true,
    option: [
      { key: 'create', label: '创建' },
      { key: 'start', label: '开始' },
      { key: 'assignment', label: '分派' },
      { key: 'finish', label: '完成' }
    ]
  },
  {
    type: 'input',
    itemType: 'textarea',
    prop: 'listenerPath',
    label: '监听器路径',
    rows: 8
  }
]

onMounted(() => {
  getPage()
})

function getPage() {
  getDefinitionPageApi(queryData.value).then((resp) => {
    tableData.value = resp.list
    pageTotal.value = resp.total
  })
}

function formSubmit() {
  formRef.value?.validate(() => {
    formData.value.listenerType = formData.value.listenerType?.join(',')

    if (formData.value.id) {
      updateDefinitionApi(formData.value).then(() => {
        dialogVisible.value = false
        ElMessage.success('修改成功')
        getPage()
      })
    } else {
      addDefinitionApi(formData.value).then(() => {
        dialogVisible.value = false
        ElMessage.success('新增成功')
        getPage()
      })
    }
  })
}

function formClosed() {
  formRef.value?.resetFields()
}

function handleRemove(id: string) {
  useHandleData('是否确认删除？', () => {
    deleteDefinitionApi(id).then(() => {
      ElMessage.success('删除成功')
      getPage()
    })
  })
}
</script>

<template>
  <div>
    <el-card v-if="showQuery">
      <a-form ref="queryRef" v-model="queryData" :config="queryConfig" :span="6"> </a-form>
    </el-card>

    <a-table
      :data="tableData"
      :page-total="pageTotal"
      :toolbar-config="toolbarConfig"
      :column-config="columnConfig"
      v-model:showQuery="showQuery"
      v-model:page-num="queryData.pageNum"
      v-model:page-size="queryData.pageSize"
      @page-num-change="getPage"
      @page-size-change="getPage"
    >
    </a-table>

    <a-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      @submit="formSubmit"
      @closed="formClosed"
    >
      <a-form ref="formRef" v-model="formData" :config="formConfig" :span="24"> </a-form>
    </a-dialog>

    <design ref="designVisibleRef" v-model="designVisible" />

    <a-dialog title="流程图" v-model="chartVisible" width="1200px" :footer="false" append-to-body>
      <img :src="imgUrl" width="100%" style="margin: 0 auto" alt="" />
    </a-dialog>
  </div>
</template>
