<template>
  <div class="task-panel">
    <BasicForm @register="registerForm" class="task-form"/>
  </div>
</template>

<script lang="ts" setup>
    import { ref, watch, reactive, computed, toRaw, isProxy, onMounted, nextTick } from 'vue'
    import {BasicForm, useForm} from '/@/components/Form/index';
    import {FormSchema} from '/@/components/Table';
    import { useModelerStore } from '../store/modeler-store.js'
    import { StrUtil } from '../common/StrUtil'
    import { defHttp } from '/@/utils/http/axios';
    import { debounce } from 'lodash-es';

    const emit = defineEmits(['register','success', 'update']);
    const modelerStore = useModelerStore()

    interface BpmnFormData {
      userType?: string
      assignee?: string
      candidateGroups?: string
      dueDate?: string
      priority?: string
      dataType?: string
      expId?: string
      async?: boolean
      userName?: string
      [key: string]: any
    }

    interface SelectData {
      assignee?: any
      candidateGroups?: any
      userName?:any
      exp?: any
    }

    const props = defineProps<{
      id: string
      readonly?: boolean
    }>()

    const bpmnFormData = reactive<BpmnFormData>({
      async: false,
      userType: 'user'
    });

    const selectData = reactive<SelectData>({})
    const isUser = ref(true);
    const loading = ref(false);
    
    // 监听用户类型变化，动态更新表单字段显示
    watch(isUser, (newValue) => {
      nextTick(() => {
        if (updateSchema) {
          updateSchema({
            field: 'assignee',
            show: newValue,
            componentProps: {
              disabled: props.readonly
            }
          });
          updateSchema({
            field: 'candidateGroups',
            show: !newValue,
            componentProps: {
              disabled: props.readonly
            }
          });
        }
      });
    });

    // 监听只读状态变化
    watch(() => props.readonly, (readonly) => {
      updateFormReadonly(readonly);
    });

    const debouncedResetTaskForm = debounce(() => {
      resetTaskForm();
    }, 100);

    // 监听 id 变化
    watch(() => props.id, (newVal) => {
      if (StrUtil.isNotBlank(newVal)) {
        debouncedResetTaskForm();
      }
    }, { immediate: false });

    // 监听当前选中的元素变化
    watch(() => modelerStore.element, (newElement) => {
      if (newElement && newElement.type !== 'bpmn:Process') {
        debouncedResetTaskForm();
      }
    }, { immediate: false });

    // 获取所有角色
    const getAllRole = async (params) => {
      try {
        loading.value = true;
        const rolesList = await defHttp.get({ url: "/sys/role/queryall", params });
        return rolesList;
      } catch (error) {
        console.error('获取角色列表失败:', error);
        return [];
      } finally {
        loading.value = false;
      }
    }

    // 获取用户列表
    // const getUserList = async (params) => {
    //   try {
    //     loading.value = true;
    //     const userList = await defHttp.get({ url: "/sys/user/list", params });
    //     return userList;
    //   } catch (error) {
    //     console.error('获取用户列表失败:', error);
    //     return [];
    //   } finally {
    //     loading.value = false;
    //   }
    // }

    const formSchema: FormSchema[] = [
      {
        label: '异步',
        field: 'async',
        component: 'JSwitch',
        defaultValue: false,
        componentProps: {
          options: [true, false],
          labelOptions: ['是', '否'],
          disabled: props.readonly,
          onChange: (async: boolean) => {
            bpmnFormData.async = async
            updateCustomElement("async", async)
            emit('update', { async })
          }
        }
      },
      {
        label: '用户类型',
        field: 'userType',
        component: 'JDictSelectTag',
        defaultValue: 'user',
        componentProps: {
          type: 'radio',
          options: [
            {"value": "user", "label": "用户"},
            {"value": "role", "label": "角色"},
          ],
          disabled: props.readonly,
          onChange: (userType: string) => {
            isUser.value = userType === 'user';
            bpmnFormData.userType = userType
            updateCustomElement("userType", userType)
            emit('update', { userType })
            
            // 切换用户类型时清空另一个字段
            if (userType === 'user') {
              bpmnFormData.candidateGroups = ''
              updateCustomElement("candidateGroups", '')
            } else {
              bpmnFormData.assignee = ''
              updateCustomElement("assignee", '')
            }
          }
        },
      },
      {
        label: '指定人员',
        field: 'assignee',
        component: 'JSelectUser',
        componentProps: {
          rowKey: 'id',
          labelKey: 'realname',
          disabled: props.readonly,
          onChange: (assignee: string) => {
            bpmnFormData.assignee = assignee
            updateCustomElement("assignee", assignee)
            updateCustomElement("userType", "user")
            emit('update', { assignee, userType: 'user' })
       
            if (bpmnFormData.userType !== 'user') {
              bpmnFormData.userType = 'user'
              isUser.value = true
              updateCustomElement("userType", "user")
            }
          }
        },
        ifShow: ({ values }) => values.userType === 'user',
      },
      {
        label: '指定角色',
        field: 'candidateGroups',
        component: 'ApiSelect',
        componentProps: {
          multiple: false,
          api: getAllRole,
          labelField: 'roleName',
          valueField: 'id',
          immediate: false,
          disabled: props.readonly,
          loading: loading,

          onChange: (candidateGroups: string) => {
            bpmnFormData.candidateGroups = candidateGroups
            updateCustomElement("candidateGroups", candidateGroups)
            updateCustomElement("userType", "role")
            emit('update', { candidateGroups, userType: 'role' })
     
            if (bpmnFormData.userType !== 'role') {
              bpmnFormData.userType = 'role'
              isUser.value = false
              updateCustomElement("userType", "role")
            }
          }
        },
        ifShow: ({ values }) => values.userType === 'role',
      },
      {
        label: '过期时间',
        field: 'dueDate',
        component: 'DatePicker',
        componentProps: {
          showTime: false,
          valueFormat: 'YYYY-MM-DD',
          placeholder: '请选择',
          disabled: props.readonly,
          onChange: (dueDate: string) => {
            bpmnFormData.dueDate = dueDate
            updateCustomElement("dueDate", dueDate)
            emit('update', { dueDate })
          }
        }
      },
      {
        label: '优先级',
        field: 'priority',
        component: 'Select',
        componentProps: {
          options: [
            { label: '低', value: 'low' },
            { label: '中', value: 'medium' },
            { label: '高', value: 'high' },
          ],
          disabled: props.readonly,
          onChange: (priority: string) => {
            bpmnFormData.priority = priority
            updateCustomElement("priority", priority)
            emit('update', { priority })
          }
        }
      }
    ];

    const [registerForm, { updateSchema, setFieldsValue, getFieldsValue, setProps }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: { span: 24 },
        autoSubmitOnEnter: false,
        disabled: props.readonly,
    });

    // 更新表单只读状态
    const updateFormReadonly = (readonly: boolean = false) => {
      setProps({ disabled: readonly });
      
      // 更新所有表单项的只读状态
      formSchema.forEach(schema => {
        if (schema.componentProps) {
          updateSchema({
            field: schema.field,
            componentProps: {
              ...schema.componentProps,
              disabled: readonly
            }
          });
        }
      });
    };

    // 更新自定义流程节点/参数信息
    const updateCustomElement = (key: string, value: any) => {
      if (!modelerStore.modeler || !modelerStore.element) {
        console.warn('Modeler or element not available')
        return
      }

      try {
        const taskAttr: Record<string, any> = {}
        taskAttr[key] = value
        
        const success = safeUpdateProperties(modelerStore.element, taskAttr)
        
        if (!success) {
          console.error('更新自定义属性失败')
        }
      } catch (error) {
        console.error('更新自定义属性失败:', error)
      }
    }

    // 安全的属性更新方法
    const safeUpdateProperties = (element: any, properties: Record<string, any>) => {
      if (!modelerStore.modeler || !element) {
        console.warn('Modeler or element not available')
        return false
      }

      try {
        const modeling = modelerStore.modeler.get('modeling')
        if (!modeling) {
          return false
        }

        // 获取原始对象，避免 Vue 响应式代理问题
        let targetElement = element
        
        // 如果是 Vue 代理对象，获取原始对象
        if (isProxy(element)) {
          targetElement = toRaw(element)
        }

        // 执行更新
        modeling.updateProperties(targetElement, properties)
        return true
        
      } catch (error) {
        console.error('更新属性失败:', error)
        return false
      }
    }

    const resetTaskForm = async () => {
      if (!modelerStore.element?.businessObject || modelerStore.element.type === 'bpmn:Process') {
        return
      }
      const businessObject = modelerStore.element.businessObject

      // 重置表单数据
      const formData: BpmnFormData = {
        async: businessObject.async || false,
        userType: businessObject.userType || 'user',
        assignee: businessObject.assignee || '',
        candidateGroups: businessObject.candidateGroups || '',
        dueDate: businessObject.dueDate || '',
        priority: businessObject.priority || 'medium'
      }

      isUser.value = formData.userType === "user"

      // 更新响应式数据
      Object.assign(bpmnFormData, formData)
      Object.assign(selectData, {
        assignee: null,
        userName: "",
        candidateGroups: null,
      })

      // 更新表单字段显示
      await checkValuesEcho(formData)
      
      // 触发更新事件
      emit('update', formData)
    }

    // 设计器右侧表单数据回显
    const checkValuesEcho = async (formData: BpmnFormData) => {
      try {
        await setFieldsValue(formData)
        
        updateSchema({
          field: 'assignee',
          show: isUser.value,
          componentProps: {
            disabled: props.readonly
          }
        })
        
        updateSchema({
          field: 'candidateGroups',
          show: !isUser.value,
          componentProps: {
            disabled: props.readonly
          }
        })
        
        if(isUser.value){
          updateCustomElement("userType", "user")
        } else {
          updateCustomElement("userType", "role")
        }

      } catch (error) {
        console.error('表单数据回显失败:', error)
      }
    }

    // 获取表单数据
    const getFormData = (): BpmnFormData => {
      return { ...bpmnFormData }
    }

    // 设置表单数据
    const setFormData = (data: Partial<BpmnFormData>) => {
      Object.assign(bpmnFormData, data)
      setFieldsValue(data)
    }

    // 组件挂载时初始化
    onMounted(() => {
      if (modelerStore.element) {
        resetTaskForm()
      }
    })

    // 暴露方法给父组件
    defineExpose({
      getFormData,
      setFormData,
      resetTaskForm,
      updateFormReadonly
    })
</script>

<style lang="less" scoped>
  .task-panel {
    padding: 0;
    
    .task-form {
      padding: 0 16px;
    }
  }

  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-picker) {
    width: 100%;
  }

  /** 表单标签样式 */
  :deep(.ant-form-item-label) {
    font-weight: 500;
  }

  /** 加载状态样式 */
  :deep(.ant-spin-nested-loading) {
    min-height: 60px;
  }
</style>