<template>
  <div style="background-color: #fff; padding: 100px">
    <a-spin :spinning="loading">
      <BasicForm @register="registerForm">
        <template #planBasis="{ model, field }">
          <div v-if="model[field]">
            <div v-if="isValidJson(model[field])">
              <a-tag 
                v-for="item in safeJsonParse(model[field])" 
                @click="viewBasisDetail(item)" 
                :key="item.id" 
                style="margin-bottom: 8px; cursor: pointer;"
              >
                {{ item.name }}
              </a-tag>
            </div>
            <a-alert v-else type="warning" :message="`无效的数据格式: ${model[field]}`" />
          </div>
          <a-empty v-else description="暂无数据" />
        </template>
      </BasicForm>
    </a-spin>

    <div style="width: 100%; text-align: center; margin-top: 24px" v-if="!formDisabled">
      <a-space>
        <a-button @click="submitForm" type="primary" :loading="submitting" pre-icon="ant-design:check">提 交</a-button>
        <a-button @click="handleReset">重 置</a-button>
      </a-space>
    </div>

    <AuditInnerDetailDrawer ref="auditInnerDetailDrawerRef" :visible="showDetailDrawer" :basis="selectedBasis"  @close="handleDrawerClose" />
  </div>
</template>

<script lang="ts" setup>
import { BasicForm, useForm } from '/@/components/Form/index';
import { computed, ref, onMounted,watchEffect,toRaw  } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import { getBpmFormSchema } from '../StPlanMan.data';
import { saveOrUpdate } from '../StPlanMan.api';
import { useMessage } from '/@/hooks/web/useMessage';
import AuditInnerDetailDrawer from '/@/views/newlib/components/modal/AuditInnerDetailDrawer.vue';
import { getAuthCache, setAuthCache, removeAuthCache } from '/@/utils/auth';
import { TOKEN_KEY} from '/@/enums/cacheEnum';
import { useUserStore } from '/@/store/modules/user';
import { useRoute } from 'vue-router';
const route = useRoute();


interface Props {
  formData: {
    disabled?: boolean;
    [key: string]: any;
  };
}
const showDetailDrawer = ref(false);
const props = defineProps<Props>();
const { createMessage } = useMessage();
const loading = ref(false);
const submitting = ref(false);
const formData = ref<Record<string, any>>({});
const idsystoken = ref('');

const [registerForm, { setFieldsValue, setProps, getFieldsValue, resetFields, validate }] = useForm({
  labelWidth: 150,
  schemas: getBpmFormSchema(props.formData),
  showActionButtonGroup: false,
  baseColProps: { span: 24 },
});

const formDisabled = computed(() => {
  return props.formData?.disabled !== false;
});

// 安全解析JSON
const safeJsonParse = (str: string) => {
  try {
    return JSON.parse(str);
  } catch (e) {
    console.error('JSON解析错误:', e);
    return [];
  }
};

// 验证是否为有效JSON
const isValidJson = (str: string) => {
  try {
    JSON.parse(str);
    return true;
  } catch (e) {
    return false;
  }
};

// 依据详情抽屉
const auditInnerDetailDrawerRef = ref();
const selectedBasis = ref<any>(null);
const viewBasisDetail = (item: any) => {
    selectedBasis.value = item;
    const data = {
      name: item.name,
      comeFrom: item.comeFrom,
    };
    showDetailDrawer.value = true;
    auditInnerDetailDrawerRef.value.open(data);
   
  };

const handleDrawerClose = () => {
  showDetailDrawer.value = false;
  selectedBasis.value = null;
};

// 从URL获取参数
const getUrlParams = () => {
  const winurl = window.location.href;
  const params = new URLSearchParams(winurl.split('?')[1]);

  console.log('winurl:', winurl);
  return {
    cctoken: params.get('Token') || '',
    WorkID: params.get('WorkID') || '',
  };
};

// 初始化表单数据
const initFormData = async () => {
  try {
    loading.value = true;
    //const { cctoken, WorkID } = getUrlParams();
    //console.log('Token:', cctoken, 'WorkID:', WorkID);
  
    const timestamp = new Date().getTime();
    /**
    const gettokeyUrl = '/api/jflow/getCCWorkTokenAndTid';
    const {tid,token} = await defHttp.get({
      url: gettokeyUrl,
      params: {
        "targetKey":"targetKey",
        "flowToken":cctoken,
        "WorkID":WorkID,
        "_t": timestamp},
    });
    */

    let  tid = toRaw(route.query).id;
    console.log('tid:', tid);

    //setAuthCache(TOKEN_KEY, token);

    //console.log('tid:', tid, 'token:', token);

    const queryByIdUrl = '/plan.main/stPlanMan/queryById';
    const data = await defHttp.get({
      url: queryByIdUrl,
      params: { id: tid,  "_t": timestamp },
    });

    formData.value = { ...data };
    if (data.planBasis && !isValidJson(data.planBasis)) {
      console.warn('planBasis不是有效的JSON格式:', data.planBasis);
      formData.value.planBasis = '[]';
    }

    await setFieldsValue(formData.value);
    await setProps({ disabled: formDisabled.value });
  } catch (error) {
    console.error('初始化表单数据失败:', error);
    createMessage.error('初始化表单数据失败');
  } finally {
    loading.value = false;
  }
};
onMounted(() => {
  initFormData();
});


</script>

<style scoped>
.ant-tag {
  margin-right: 8px;
  cursor: pointer;
}
</style>