<template>
  <a-form
    ref="formRef"
    :model="formState"
    :rules="rules"
    :label-col="labelCol"
    :wrapper-col="wrapperCol">
    <a-form-item label="投放名称" name="launchName">
      <a-input v-model:value="formState.launchName"
               @blur="formState.launchName = formState.launchName.trim()"
               placeholder="请输入投放名称" :maxlength="30">
        <template #suffix>
          <span class="suffix">
            {{ `${formState.launchName.length} / 30` }}
          </span>
        </template>
      </a-input>
    </a-form-item>
    <a-form-item label="投放描述" name="launchMessage">
      <a-textarea v-model:value="formState.launchMessage" :rows="4" :maxlength="150" showCount
                  @blur="formState.launchMessage = formState.launchMessage.trim()"
                  placeholder="请描述您本次投放的需求，包含投放位置、投放时段等，运营会根据您的描述配置投放任务">
        <template #suffix>
          <span class="suffix">
            {{ `${formState.launchMessage.length} / 150` }}
          </span>
        </template>
      </a-textarea>
    </a-form-item>
    <a-form-item label="投放触点" name="appId" v-if="channel.appCategory === 'SHOPPING_GUIDE'">
      <a-radio-group
          v-model:value="formState.appId"
          v-if="applicationList.length">
        <a-radio v-for="(item,index) in applicationList" :key="index" :value="item.appId">{{ item.appName }}</a-radio>
      </a-radio-group>
    </a-form-item>
  </a-form>
  <div class="ope">
    <a-button
        type="primary"
        class="custom-button mr-12"
        @click="onSubmit"
        :loading="submitLoading"
        :disabled="!formState.launchName ||!formState.launchMessage">
      <span>去配置</span>
    </a-button>
    <a-button class="custom-button mr-12" @click="onCancel" style="width: 98px;">
      <span>取消</span>
    </a-button>
  </div>
</template>
<script setup>
import { defineProps, onMounted, ref, watch } from 'vue';
import { getTeamSigns, savePublish,getPublishDetail } from '@/api/accurate';
import { message } from 'ant-design-vue';
import { useRoute,useRouter } from 'vue-router';
import Cookies from 'js-cookie';
const route = useRoute()
const router = useRouter()

const props = defineProps({
  channel: { type: [Number, String], default: '' }
});

const formRef = ref();
const addContactRef = ref();
const formState = ref({
  launchName: '',
  launchMessage: '',
  appId:''
});
const rules = {
  launchName: [
    {
      required: true,
      message: '请输入投放名称',
      trigger: 'blur'
    }
  ],
  launchMessage: [
    {
      required: true,
      message: '请输入投放描述',
      trigger: 'blur'
    }
  ],
  appId: [
    {
      required: true,
      message: '请选择投放触点',
    }
  ]
};
const labelCol = ref({ span: 1.5 });
const wrapperCol = ref({ span: 11 });
const dataSource = ref([]);
const applicationList = ref([])
const submitLoading = ref(false);
const getContactList = async () => {
  try {
    const res = await getTeamSigns({
      "findType": "NODE",
      "parentAppId": props.channel.appCategory,
      appType:'APPLICATION'
    });
    applicationList.value = res.data;
    if (applicationList.value.length){
      formState.value.appId = formState.value.appId?formState.value.appId:applicationList.value[0].appId
    }
  } catch (error) {
    console.error('获取触点列表失败:', error);
  }
};
const onSubmit = () => {
  formRef.value.validate().then(() => {
    console.log('values', formState);
    submitData()
  }).catch(error => {
    console.log('error', error);
  });
};
async function submitData(){
    let params = {
      ...formState.value,
      "publishSn": route.query.sn,
      appId:[props.channel.appId]
    }
    if (props.channel.appCategory === 'SHOPPING_GUIDE'){
      params.appId = [formState.value.appId]
    }
    try {
      submitLoading.value = true;
      const res = await savePublish(params);
      submitLoading.value = false
      if(res.data) {
        if (props.channel.appCategory === 'YIP'){
          const token = localStorage.getItem('plantToken');
          console.log(token);
          let url = res.data[0].redirectUrl +'&idp_token_id='+token;
          let params = {
            routeName: 'order',
            routePath: 'iframe/order',
            iframeUrl: url
          }
          console.log(params);
          window.parent.postMessage({
            code: '',
            params:params,
          }, '*')
        }else{
          window.open(res.data[0].redirectUrl)
          onCancel()
        }
      }
    }catch {
      submitLoading.value = false
    }

      // message.success('提交成功');

}
const onCancel = () => {
  router.go(-1)
};
// 监听 channel 变化
watch(() => props.channel, (newVal) => {
  if (!route.query.record) {
    formState.value = {
      launchName: '',
      launchMessage: ''
    };
  }
  if (newVal.appId === 'SHOPPING_GUIDE'){
    getContactList()
  }
});
// 获取详情数据
const getDetail = async (id) => {
  try {
    const res = await getPublishDetail({ surveyPublishId: id });
    if (res.data) {
      // 填充表单数据
      formState.value = {
        launchName: res.data.launchName,
        launchMessage: res.data.launchMessage,
        appId: res.data.appId,
      };
    }
  } catch (error) {
    console.error('获取详情失败:', error);
  }
};
// 组件挂载时检查路由参数
onMounted(() => {
  getContactList()
  const { record } = route.query;
  if (record) {
    const recordObj = JSON.parse(decodeURIComponent(record));
    if (recordObj.surveyPublishId) {
      getDetail(recordObj.surveyPublishId);
    }
  }
});
</script>
<style scoped lang="scss">
.mr-12{
  margin-right: 12px;
}
p {
  margin: 0;
  padding: 0;
}

.application {
  display: flex;
  align-items: center;
}
.custom-button.ant-btn-primary[disabled], .ant-btn.custom-button.ant-btn-primary[disabled] {
  border-color: transparent;
}
:deep(.ant-form-item-label > label){
  width: 90px;
}
</style>
