<script setup>
import { reactive,onMounted,computed } from 'vue'
import { getProcessPage,addProcess,updateProcess,deleteProcess,getProcessDetail,start } from './api'
import { baseModelOptions,baseFilterOptions } from './options'
import { getFormPage,getFormFields } from '../form/api'
import useUserStore from '@/store/modules/user'

const user = useUserStore()
const { proxy } = getCurrentInstance();

const state = reactive({
  baseModelOptions: baseModelOptions(),
  baseFilterOptions: baseFilterOptions(),
  title: "Process管理",
  baseModelName: 'Process信息',
  addBtnName: '添加Process',
  editBtnName: '',
  delBtnName: '',
  primaryKey: 'id',
  getTableFn: getProcessPage,
  addFn: addProcess,
  editFn: updateProcess,
  deleteFn: deleteProcess,
  detailFn: getProcessDetail,
  showEditBtn: false,
  showDeleteBtn: false,
  handleAdd: () => {
    proxy.$router.push({ path: '/workflow/modeler' });
  },
  handleEdit: (index,row) => {
    proxy.$router.push({ 
      path: '/workflow/modeler',
      query: {
        id: row.id
      }
    });
  },
  // rowControl: {
  //   showEditBtn: false,
  //   showDelBtn: false
  // },
  permission: {//菜单管理中添加权限
    add: 'system:user:list',
    edit: 'system:user:list',
    delete: 'system:user:list',
    detail: 'system:user:list',
  },
  pageInfo: { total: 0, base:{limit: 8,current: 1} },
  pageKeys: {
    limit: 'maxResults',
    start: 'firstResult'
  },
  dynamicFormOptions: [],
  formOptions: [
    {
      tag: 'BaseRadioGroup',
      label: '是否绑定表单:',
      key: 'needForm',
      value: 1,
      default: 1,
      attribute: {//配置项内容
          options:[
              {label: '是',value: 1},
              {label: '否',value: 2},
          ]
      }
    },
    {
        tag: 'BaseSelect',
        label: '表单名称',
        key: 'formId',
        value: '',
        default: '',
        attribute: {
            clearable: true,
            options: []
        },
        event: {
            change: (val) => {
              console.log('object :>> ', val);
              const path = state.formData.find(item => item.id == val).formPath
                getFormFields({path}).then(res => {
                    state.dynamicFormOptions = res.data ? res.data : []
                    // state.formOptions = state.formOptions.concat(formOptions)
                })
            }
        }
    },
    // {
    //     tag: 'BaseSelect',
    //     label: '表单的值(模拟)',
    //     key: 'formValues',
    //     value: JSON.stringify({first: "张三", second: "李四"}),
    //     default: '',
    //     attribute: {
    //         disabled: true,
    //         options: []
    //     }
    // },
  ],
  viewForm: false,
  formData: null,
  currentRow: null
})

onMounted(() => {
  getFormPage({ page: 1, limit: 9999}).then(res => {
    state.formData = res.data.list
    state.formOptions[1].attribute.options = res.data.list.map(item => {
      return {
        label: item.formName,
        value: item.id
      }
    })
  })
})

// 合并静态和动态选项配置项
const mergedFormOptions = computed(() => {
  return [...state.formOptions, ...state.dynamicFormOptions];
});

const startProcess = (row) => {
  state.viewForm = true
  state.currentRow = row
}
const doStartProcess = (data) => {
  let needForm = state.formOptions[0].value;
  if(needForm == 1 && !data.formId){
    proxy.$message.error('请选择绑定的表单')
    return
  }
   // 获取所有表单项的值
  let formValues = {};
  mergedFormOptions.value.forEach((item,index) => {
    if(index > 1){
      formValues[item.key] = item.value
    }
  });
  start({
    processKey: state.currentRow.key,
    formId: state.formOptions[1].value,
    createUser: user.userId,
    formValues: JSON.stringify(formValues)
  }).then(res => {
    if(res.code == 200){
      state.viewForm = false
      proxy.$message.success('启动成功')
    }
  })
}
const viewProcess = (row) => {
  proxy.$router.push({
    path: '/workflow/processInstance',
    query: {
      processKey: row.key
    }
  })
}
</script>

<template>
  <div class="app-container">
    <BaseTablePage 
      :tableOptions="state" 
    >
      <template v-slot:column>
        <el-table-column align="center" prop="key" label="流程Key" />
        <el-table-column align="center" prop="name" label="流程名称" />
        <el-table-column align="center" prop="version" label="流程版本" />
        
      </template>
      <template #before="scope">
        <el-button type="text" icon="View" @click="viewProcess(scope.row)">查看实例</el-button>
        <el-button type="text" icon="VideoPlay" @click="startProcess(scope.row)">启动新实例</el-button>
      </template>
    </BaseTablePage>
    <BaseModel
      v-if="state.formOptions"
      :title="'启动新流程'"
      :modelType="'edit'"
      :columnCount="1"
      :showModel="state.viewForm"
      :width="'35%'"
      :modelOptions="mergedFormOptions"
      @dialogClose="state.viewForm=false"
      @dialogSubmit="doStartProcess"
    >
    </BaseModel>
  </div>
</template>

<style scoped>

</style>
