<template>
  <div>
    <el-table v-loading="loading" :data="list" border>
      <el-table-column type="index" width="50" />
      <el-table-column label="来源名称" width="200px">
        <template #default="{ row }">
          <el-input v-model="row.source" placeholder="请输入" :clearable="false" />
        </template>
      </el-table-column>
      <el-table-column label="渠道" width="300px">
        <template #default="{ row }">
          <el-select
            v-if="row.edit"
            v-model="row.resource"
            placeholder="选择渠道"
            clearable
            filterable
            @change="handleChange(row)"
          >
            <el-option
              v-for="item in resourceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <span>{{ row.channel }}</span>
        </template>
      </el-table-column>
      <el-table-column label="获取连接" prop="url" />
      <el-table-column label="参数详情" prop="params" />
      <el-table-column label="是否启用" width="100px">
        <template #default="{ row }">
          <el-switch v-model="row.status" :active-value="0" :inactive-value="1" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100px">
        <template #default="{ $index }">
          <el-button type="primary" style="padding: 0px" text @click="handleRemove($index)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="mt-20px flex justify-center">
      <el-button type="primary" @click="handleInsert">新增规则</el-button>
      <el-button type="primary" @click="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script setup name="ClueSet">
import { getClueGainRuleList, deleteClueGainRule } from '@/api/clue/clueGetSet'

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const list = ref([])
const loading = ref(false)
const resourceOptions = ref([])

async function getList() {
  loading.value = true
  try {
    const data = await getClueGainRuleList()
    list.value = data
  } finally {
    loading.value = false
  }
}

function handleInsert() {
  list.value.push({ source: '', url: '', edit: true, status: 0 })
}

function onSubmit() {
  console.log('保存成功')
}

async function handleRemove(idx) {
  if (list.value[idx].ruleId) {
    try {
      // 删除的二次确认
      await message.delConfirm()
      // 发起删除
      await deleteClueGainRule(list.value[idx].ruleId)
      message.success(t('common.delSuccess'))
      // 刷新列表
      await getList()
    } catch (err) {
      console.log(err)
    }
  } else {
    list.value.splice(idx, 1)
  }
}

function handleChange(row) {
  row.url = `https://sscrm.ahduima.com/clue/get?cid=1001&aid=1001&res=${row.resource}`
  row.params = '参数详情'
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped></style>
