import { Ref, ref, watch, onMounted } from 'vue'
import * as api from './api'

interface Props {
  data: {
    campaignId: string
    campaignType: string
    profileId: string
    ruleType: number
  }
  RuleStatusButton?: { [key: string]: any }
}

export const userFormData = (props: Props) => {
  const formData: Ref<AutoCampaignRule> = ref({
    campaignId: props.data.campaignId,
    campaignType: props.data.campaignType,
    profileId: props.data.profileId,
    ruleType: props.data.ruleType,
    templateName: '',
    useTmpl: false,
    rule: {
      type: props.data.ruleType,
      campaignType: props.data.campaignType,
      campaignAd: [],
      action: {},
      activeModel: '',
      setTime: '',
      weekdays: [],
      conditions: [],
    },
    RuleStatusButton: props.RuleStatusButton,
  })
  const initData = async () => {
    const resp = await api.getCampaignRuleInfo(props.data)
    const info = resp.data[0]
    if (info) {
      // ruleStatusButton.value = info.RuleStatusButton || {}
      // delete info['RuleStatusButton']
      formData.value = info
      if (info.template) {
        formData.value.useTmpl = true
        formData.value.rule = info.template.rule
      } else {
        formData.value.useTmpl = false
      }
    }
  }

  const submitFormData = async () => {
    const body: AutoCampaignRule = {
      campaignId: formData.value.campaignId,
      campaignType: formData.value.campaignType,
      profileId: formData.value.profileId,
      ruleType: formData.value.ruleType,
      RuleStatusButton: formData.value.RuleStatusButton,
      rule: null,
      templateName: formData.value.templateName,
    }
    if (formData.value.useTmpl) {
      body.templateId = formData.value.template.id
    } else {
      body.rule = formData.value.rule
      delete body.rule['modifier_name']
      delete body.rule.id
    }
    await api.saveCampaignRule(body)
    console.log("=>(common.ts:68) body", body);
  }

  watch(
    () => props.RuleStatusButton,
    () => {
      formData.value.RuleStatusButton = props.RuleStatusButton
    },
    { deep: true }
  )

  onBeforeMount(async () => {
    await initData()
  })

  return { formData, submitFormData }
}
