<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import type { ExperimentItem } from '../types'
import { ElMessage } from 'element-plus'
import { getTripConfig, updateTripConfig, getLiveCommodity } from '../api'
import { useConnection, useUserAttr, useMetaEvent, useTag, useGroup, useMaterial } from '../composables/useAllData'
import { useDocumentVisibility } from '@vueuse/core'
import { dmlMenus } from '@/utils/dmlMenus'

import { useAppConfig } from '@/composables/useAppConfig'
const appConfig = useAppConfig()

const props = defineProps<{
  data: ExperimentItem
}>()

const emit = defineEmits<{
  (e: 'update'): void
  (e: 'update:modelValue', visible: boolean): void
}>()

const { connectionList } = useConnection(props.data.id)
const { userAttrList } = useUserAttr(props.data.id)
const { metaEventList } = useMetaEvent(props.data.id)
const { tagList } = useTag(props.data.id)
const { groupList } = useGroup(props.data.id)
const { materialList } = useMaterial(props.data.id)

const dmlURL = computed(() => {
  return `${appConfig.dmlURL || import.meta.env.VITE_DML_URL}/trip/template?experiment_id=${props.data.id}`
})

const formRef = $ref<FormInstance>()
const form = reactive({
  experiment_id: props.data.id,
  itinerary_id: '',
  connect_ids: [],
  user_attr_config: { is_all: true, items: [] },
  event_config: { is_all: true, items: [] },
  is_use_common: 0,
  is_use_common_tags: 0,
  is_use_common_groups: 0,
  is_use_common_materials: 0,
  ids: ['教师维护的用户和事件数据'],
  tag_ids: [],
  group_ids: [],
  material_ids: [],
  auth_config: dmlMenus,
  is_use_common_live_commodities: 0,
  live_commodity_ids: [],
})

// 模板列表
let templateList = $ref<{ id: string; name: string }[]>([])

const checked = ref(false)

function fetchInfo() {
  getTripConfig({ experiment_id: props.data.id }).then((res) => {
    const data = res.data
    if (data.itinerary?.id) {
      templateList = [data.itinerary]
    }
    const connect_ids = data.connections.map((item: any) => item.id)
    if (!data.is_config_created) {
      Object.assign(form, { itinerary_id: data.itinerary.id, connect_ids })
      return
    }
    const user_attr_config = {
      is_all: data.user_attr_config.is_all,
      items: data.user_attr_config.items.map((item: any) => item.id),
    }
    const event_config = {
      is_all: data.event_config.is_all,
      items: data.event_config.items.map((item: any) => item.id),
    }
    const tag_ids = data.tags.map((item: any) => item.id)
    const group_ids = data.groups.map((item: any) => item.id)
    const material_ids = data.marketing_materials.map((item: any) => item.id)

    // 递归合并配置
    interface MenuItem {
      id: number
      name: string
      is_checked: boolean
      pid: number
      children: MenuItem[]
    }

    const mergeConfig = (defaultItems: MenuItem[], backendItems: MenuItem[]): MenuItem[] => {
      return defaultItems.map((defaultItem) => {
        const backendItem = backendItems.find((item: MenuItem) => item.id === defaultItem.id)
        if (backendItem) {
          return {
            ...defaultItem,
            is_checked: backendItem.is_checked,
            children:
              defaultItem.children.length > 0 ? mergeConfig(defaultItem.children, backendItem.children || []) : [],
          }
        }
        return defaultItem
      })
    }

    // Ensure auth_config structure is maintained
    let authConfig = dmlMenus
    if (data.auth_config && data.auth_config.length > 0) {
      authConfig = mergeConfig(dmlMenus, data.auth_config)
    }

    Object.assign(form, {
      itinerary_id: data.itinerary.id,
      connect_ids,
      user_attr_config,
      event_config,
      is_use_common: data.is_use_common,
      is_use_common_tags: data.is_use_common_tags,
      is_use_common_groups: data.is_use_common_groups,
      is_use_common_materials: data.is_use_common_materials,
      tag_ids,
      group_ids,
      material_ids,
      auth_config: authConfig,
      live_commodity_ids: data?.live_commodities.reduce((a: any, b: any) => {
        a.push(b.id)
        return a
      }, []),
      is_use_common_live_commodities: data.is_use_common_live_commodities,
    })
    // checked
    if (data.auth_config.length) {
      checked.value = data.auth_config.find((item: any) => item.is_checked === false) ? false : true
    }
  })
}
watchEffect(() => fetchInfo())

const visibility = useDocumentVisibility()
watch(visibility, (current, previous) => {
  if (current === 'visible' && previous === 'hidden') fetchInfo()
})

const step = ref(-1)
// 上一步
function handlePrev() {
  step.value--
}
// 下一步
function handleNext() {
  step.value++
}

// 提交
function handleSubmit() {
  formRef?.validate().then(() => {
    const params = {
      ...form,
      connect_ids: JSON.stringify(form.connect_ids),
      user_attr_config: JSON.stringify(form.user_attr_config),
      event_config: JSON.stringify(form.event_config),
      tag_ids: JSON.stringify(form.tag_ids),
      group_ids: JSON.stringify(form.group_ids),
      material_ids: JSON.stringify(form.material_ids),
      auth_config: JSON.stringify(form.auth_config),
      live_commodity_ids: JSON.stringify(form.live_commodity_ids),
    }
    params.itinerary_id = params.itinerary_id === '' ? (params.itinerary_id = '0') : params.itinerary_id
    updateTripConfig(params).then(() => {
      ElMessage({ message: '保存成功', type: 'success' })
      emit('update')
      emit('update:modelValue', false)
    })
  })
}

// 多选
const handleH2Check = (item: any) => {
  if (item.is_checked) {
    item.children.map((d: any) => {
      d.is_checked = false
      return d
    })
  } else {
    item.children.map((d: any) => {
      d.is_checked = true
      return d
    })
  }
  setTimeout(() => {
    checked.value = form.auth_config.find((item: any) => item.is_checked === false) ? false : true
  }, 100)
}

const handleItemCheck = (item: any) => {
  const isCheck = item.children.findIndex((d: any) => d.is_checked === true)
  if (isCheck === -1) {
    item.is_checked = false
  } else {
    item.is_checked = true
  }
  setTimeout(() => {
    checked.value = isChe()
  }, 100)
  function isChe() {
    for (let i = 0; i < form.auth_config.length; i++) {
      if (form.auth_config[i].is_checked === false) {
        return false
      }
      const c = form.auth_config[i].children.findIndex((cItem: any) => cItem.is_checked === false)
      if (c !== -1) {
        return false
      }
    }
    return true
  }
}

// 直播商品列表
const liveList: any = ref([])
getLiveCommodity({ experiment_id: props.data.id }).then((res: any) => {
  liveList.value = res.data?.items || []
})

// 功能全选按钮
const handleSelectAll = () => {
  form.auth_config.map((item: any) => {
    item.is_checked = !checked.value
    item.children.map((cItem: any) => {
      cItem.is_checked = !checked.value
    })
  })
}
</script>

<template>
  <el-dialog
    title="配置数字营销实验"
    :close-on-click-modal="false"
    width="1000px"
    @update:modelValue="(value) => $emit('update:modelValue', value)">
    <el-form ref="formRef" :model="form" label-suffix="：">
      <el-row justify="space-between">
        <el-form-item label="实验名称">{{ data.name }}</el-form-item>
        <el-form-item label="实验类型">{{ data.type_name }} </el-form-item>
        <el-form-item label="实验总成绩">{{ data.score }}</el-form-item>
      </el-row>
      <el-tabs v-model="step" tab-position="left">
        <el-tab-pane label="功能" :name="-1">
          <el-checkbox @click="handleSelectAll" v-model="checked" label="全选" size="large" />
          <div class="check-ul">
            <div class="li" v-for="item in form?.auth_config" :key="item?.id">
              <div class="check-h2">
                <el-checkbox @click="handleH2Check(item)" v-model="item.is_checked" :label="item.name" size="large" />
              </div>
              <div class="check-item">
                <template v-for="cItem in item.children" :key="cItem?.id">
                  <el-checkbox
                    @change="handleItemCheck(item)"
                    v-model="cItem.is_checked"
                    :label="cItem.name"
                    size="large" />
                </template>
              </div>
              <el-divider />
            </div>
          </div>
          <!-- <el-checkbox v-model="checked1" label="Option 1" size="large" /> -->
        </el-tab-pane>
        <el-tab-pane label="模板与连接" :name="0">
          <el-form-item label="旅程模板" label-width="82" prop="itinerary_id">
            <template v-if="templateList.length">
              <el-select v-model="form.itinerary_id" style="width: 100%">
                <el-option v-for="item in templateList" :label="item.name" :value="item.id" :key="item.id"></el-option>
              </el-select>
            </template>
            <template v-else>
              <a :href="dmlURL" target="_blank">
                <el-button type="primary">新建旅程模板</el-button>
              </a>
            </template>
          </el-form-item>
          <el-form-item label="连接" label-width="82" prop="connect_ids">
            <el-select v-model="form.connect_ids" multiple style="width: 100%">
              <el-option
                v-for="item in connectionList"
                :label="item.name"
                :value="item.id"
                :key="item.id"
                disabled></el-option>
            </el-select>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="元数据" :name="1">
          <el-form-item label="用户属性" label-width="82">
            <el-radio-group v-model="form.user_attr_config.is_all">
              <el-radio :label="true">全部</el-radio>
              <el-radio :label="false">部分</el-radio>
            </el-radio-group>
            <el-select
              v-model="form.user_attr_config.items"
              multiple
              style="margin-left: 40px"
              v-if="!form.user_attr_config.is_all">
              <el-option v-for="item in userAttrList" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="事件" label-width="82">
            <el-radio-group v-model="form.event_config.is_all">
              <el-radio :label="true">全部</el-radio>
              <el-radio :label="false">部分</el-radio>
            </el-radio-group>
            <el-select
              v-model="form.event_config.items"
              multiple
              style="margin-left: 40px"
              v-if="!form.event_config.is_all">
              <el-option v-for="item in metaEventList" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="用户/事件数据" :name="2">
          <el-form-item label="是否允许学生新建如下资源">
            <el-radio-group v-model="form.is_use_common">
              <el-radio :label="1">否</el-radio>
              <el-radio :label="0">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="用户/事件数据" label-width="118">
            <el-select v-model="form.ids" multiple style="width: 100%" disabled>
              <el-option value="教师维护的用户和事件数据"></el-option>
            </el-select>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="标签数据" :name="3">
          <el-form-item label="是否允许学生新建如下资源">
            <el-radio-group v-model="form.is_use_common_tags">
              <el-radio :label="1">否</el-radio>
              <el-radio :label="0">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="标签数据" label-width="118" prop="tag_ids">
            <el-select v-model="form.tag_ids" multiple style="width: 100%">
              <el-option v-for="item in tagList" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="用户群组" :name="4">
          <el-form-item label="是否允许学生新建如下资源">
            <el-radio-group v-model="form.is_use_common_groups">
              <el-radio :label="1">否</el-radio>
              <el-radio :label="0">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="用户群组" label-width="118" prop="group_ids">
            <el-select v-model="form.group_ids" multiple style="width: 100%">
              <el-option v-for="item in groupList" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="营销资料" :name="5">
          <el-form-item label="是否允许学生新建如下资源">
            <el-radio-group v-model="form.is_use_common_materials">
              <el-radio :label="1">否</el-radio>
              <el-radio :label="0">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="营销资料" label-width="118" prop="material_ids">
            <el-select v-model="form.material_ids" multiple style="width: 100%">
              <el-option v-for="item in materialList" :label="item.name" :value="item.id" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-tab-pane>

        <el-tab-pane label="直播商品" :name="6">
          <el-form-item label="是否允许学生新建直播商品">
            <el-radio-group v-model="form.is_use_common_live_commodities">
              <el-radio :label="1">否</el-radio>
              <el-radio :label="0">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="学生能够使用的商品">
            <el-checkbox-group v-model="form.live_commodity_ids" :disabled="form.is_use_common_live_commodities === 0">
              <el-checkbox :label="item?.id" v-for="item in liveList" :key="item?.id">{{ item?.title }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>
        <!-- <el-tab-pane label="旅程资源" :name="10">
          <el-form-item label="是否允许学生新建如下资源">
            <el-radio-group v-model="form.is_use_common">
              <el-radio :label="1">否</el-radio>
              <el-radio :label="0">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <template v-if="form.is_use_common === 1">
            <el-divider />
            <el-form-item label="用户/事件数据" label-width="118">
              <el-select v-model="form.ids" multiple style="width: 100%" disabled>
                <el-option value="教师维护的用户和事件数据"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="标签数据" label-width="118" prop="tag_ids">
              <el-select v-model="form.tag_ids" multiple style="width: 100%">
                <el-option v-for="item in tagList" :label="item.name" :value="item.id" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="用户群组" label-width="118" prop="group_ids">
              <el-select v-model="form.group_ids" multiple style="width: 100%">
                <el-option v-for="item in groupList" :label="item.name" :value="item.id" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="营销资料" label-width="118" prop="material_ids">
              <el-select v-model="form.material_ids" multiple style="width: 100%">
                <el-option v-for="item in materialList" :label="item.name" :value="item.id" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-tab-pane> -->
      </el-tabs>
    </el-form>
    <template #footer>
      <el-row justify="center">
        <el-button round auto-insert-space @click="$emit('update:modelValue', false)" v-if="step === -1"
          >关闭</el-button
        >
        <el-button round auto-insert-space @click="handlePrev" v-else>上一步</el-button>
        <el-button type="primary" round auto-insert-space @click="handleNext" v-if="step < 6">下一步</el-button>
        <el-button type="primary" round auto-insert-space @click="handleSubmit">保存</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>
<style lang="scss">
.check-ul {
  .li {
    margin-bottom: 20px;
    .check-h2 {
      .el-checkbox__label {
        color: #ba143e !important;
      }
    }
    .check-item {
      .el-checkbox__label {
        color: #606266 !important;
      }
    }
  }
  .el-divider--horizontal {
    margin: 0 !important;
  }
}
</style>
