<template>
  <div class="ma-content-block">
    <sa-table
      ref="crudRef"
      :options="options"
      :columns="columns"
      :searchForm="searchForm"
      @selectionChange="selectChange">
      <!-- 搜索区 tableSearch -->
      <template #tableSearch>
        <a-col :sm="8" :xs="24">
          <a-form-item label="渠道ID" field="agent_id">
            <a-input v-model="searchForm.agent_id" placeholder="请输入渠道ID" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :sm="8" :xs="24">
          <a-form-item label="渠道名称" field="agent_name">
            <a-input v-model="searchForm.agent_name" placeholder="请输入渠道名称" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :sm="8" :xs="24">
          <a-form-item label="负责人" field="auth_id">
            <auth-select v-model="searchForm.auth_id" multiple />
          </a-form-item>
        </a-col>
        <a-col :sm="8" :xs="24">
          <a-form-item label="广告位ID" field="id">
            <a-input v-model="searchForm.id" placeholder="请输入广告位ID" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :sm="8" :xs="24">
          <a-form-item label="广告位名称" field="name">
            <a-input v-model="searchForm.name" placeholder="请输入广告位名称" allow-clear />
          </a-form-item>
        </a-col>
      </template>

      <template #tableBeforeButtons>
        <a-button type="primary" @click="addApk" :disabled="selecteds.length === 0"> APK打包 </a-button>
        <a-button type="primary" status="warning" @click="addGdt" :disabled="selecteds.length === 0"
          >广点通分包</a-button
        >

        <a-button type="primary" status="success" @click="addKs" :disabled="selecteds.length === 0">快手分包</a-button>
        <a-button type="primary" status="danger" @click="addTt" :disabled="selecteds.length === 0">头条推送</a-button>
      </template>

      <template #operationAfterExtend="{ record }">
        <a-button size="mini" type="text" @click="addLinkDebug(record)"><icon-bug />联调</a-button>
      </template>
      <!-- Table 自定义渲染 -->
    </sa-table>
    <!-- 编辑弹框 -->
    <edit-form ref="editRef" @success="refresh" />

    <!-- 打包新增 -->
    <add-apk-form ref="addApkRef" @success="refresh" />

    <!-- 快手分包 -->
    <ks-pac-form ref="ksPacRef" @success="refresh" />

    <!-- 广点通分包 -->
    <gdt-pac-form ref="gdtPacRef" @success="refresh" />

    <!-- 头条推送（新） -->
    <tt-pac-form ref="ttPacRef" @success="refresh" />

    <!-- 联调 -->
    <link-debug-form ref="linkDebugRef" @success="refresh" />
  </div>
</template>

<script setup>
import { onMounted, ref, reactive } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import advertCommonApi from '../../api/advert/common'
import editForm from './edit.vue'
import addApkForm from '../../advert/gamePackageLog/edit.vue'
import api from '../../api/advert/agentSite'
import ksPacForm from './ks_pac.vue'
import gdtPacForm from './gdt_pac.vue'
import ttPacForm from './tt_pac.vue'
import linkDebugForm from './link-debug-form.vue'
import AuthSelect from '@/components/auth-select/index.vue'
import { useUserStore } from '@/store'

const userStore = useUserStore()

// 引用定义
const crudRef = ref()
const viewRef = ref()
const addApkRef = ref()
const mediaOptions = ref([])
const agentOptions = ref([])
const authOptions = ref([])
const editRef = ref()
const ksPacRef = ref()
const gdtPacRef = ref()
const ttPacRef = ref()
const selecteds = ref([])
const linkDebugRef = ref()

// 搜索表单
const searchForm = ref({
  media_id: '',
  agent_id: '',

  //默认当前登录的负责人
  auth_id: userStore.user.id == 1 ? [] : [userStore.user.id],
  name: '',
})

// SaTable 基础配置
const options = reactive({
  api: api.getPageList,
  rowSelection: { showCheckedAll: true },
  add: {
    show: false,
    auth: ['/v1/advert/AgentSite/save'],
    func: async () => {
      editRef.value?.open()
    },
  },
  edit: {
    show: true,
    auth: ['/v1/advert/AgentSite/update'],
    func: async (record) => {
      editRef.value?.open('edit')
      editRef.value?.setFormData(record)
    },
  },
  delete: {
    show: false,
    auth: ['/v1/advert/AgentSite/destroy'],
    func: async (params) => {
      const resp = await api.destroy(params)
      if (resp.code === 200) {
        Message.success(`删除成功！`)
        crudRef.value?.refresh()
      }
    },
  },
})

// SaTable 列配置
const columns = reactive([
  { title: '广告位ID', dataIndex: 'id', width: 120 },
  { title: '广告位名称', dataIndex: 'name', width: 180 },
  { title: '媒体类型', dataIndex: 'media_name', width: 180 },
  { title: '渠道ID', dataIndex: 'agent_id', width: 180 },
  { title: '渠道名', dataIndex: 'agent_name', width: 180 },
  { title: '负责人', dataIndex: 'auth_name', width: 180 },
])

// 获取媒体列表Options
const getMediaOptions = async () => {
  const res = await advertCommonApi.getMediaOptionsApi()
  if (res.code == 200) {
    mediaOptions.value = res.data
  }
}

// 获取渠道列表Options
const getAgentOptions = async () => {
  const res = await advertCommonApi.getAgentOptionsApi()
  if (res.code == 200) {
    agentOptions.value = res.data
  }
}

// 获取后台归属人列表
const getAuthList = async () => {
  const res = await advertCommonApi.getAuthOptionsApi()
  if (res.code == 200) {
    authOptions.value = res.data
  }
}

// 选中数据
const selectChange = (val) => (selecteds.value = val)

// 获取广告位详情
const getAdvertSiteDetail = async () => {
  let id = selecteds.value[0]
  const res = await api.read(id)
  if (res.code == 200) {
    return res.data
  }
  return null
}

// 打包新增
const addApk = async () => {
  let data = []
  let tableData = crudRef.value?.getTableData()
  for (let i = 0; i < selecteds.value.length; i++) {
    let id = selecteds.value[i]
    let row = tableData.find((item) => item.id == id)
    data.push({
      site_id: row.id, // 广告位
      agent_id: row.agent_id, // 渠道
    })
  }

  addApkRef.value?.open()
  addApkRef.value?.setBatchData(data)
}

// 广点通分包
const addGdt = async () => {
  let tableData = crudRef.value?.getTableData()
  for (let i = 0; i < selecteds.value.length; i++) {
    // media_id 必须都是1， 否则不给打包
    let row = tableData.find((item) => item.id == selecteds.value[i])
    if (row.media_id != 2) {
      Modal.error({
        title: '提示',
        content: `广告位ID：${row.id}，媒体类型不是广点通，不能分包!`,
      })

      return
    }
  }
  let data = []
  for (let i = 0; i < selecteds.value.length; i++) {
    let row = tableData.find((item) => item.id == selecteds.value[i])
    data.push({
      site_id: row.id, // 广告位
      agent_id: row.agent_id, // 渠道
    })
  }

  gdtPacRef.value?.open()
  gdtPacRef.value?.setBatchData(data)
}

// 快手分包
const addKs = async () => {
  let tableData = crudRef.value?.getTableData()
  for (let i = 0; i < selecteds.value.length; i++) {
    let row = tableData.find((item) => item.id == selecteds.value[i])
    if (row.media_id != 3) {
      Modal.error({
        title: '提示',
        content: `广告位ID：${row.id}，媒体类型不是快手，不能分包!`,
      })
      return false
    }
  }
  let data = []
  for (let i = 0; i < selecteds.value.length; i++) {
    let row = tableData.find((item) => item.id == selecteds.value[i])
    data.push({
      site_id: row.id, // 广告位
      agent_id: row.agent_id, // 渠道
    })
  }

  ksPacRef.value?.open()
  ksPacRef.value?.setBatchData(data)
}

// 头条推送（新）
const addTt = async () => {
  let tableData = crudRef.value?.getTableData()
  for (let i = 0; i < selecteds.value.length; i++) {
    let row = tableData.find((item) => item.id == selecteds.value[i])
    if (row.media_id != 1) {
      Modal.error({
        title: '提示',
        content: `广告位ID：${row.id}，媒体类型不是头条，不能推送!`,
      })
      return false
    }
  }
  let siteIds = []
  for (let i = 0; i < selecteds.value.length; i++) {
    let row = tableData.find((item) => item.id == selecteds.value[i])
    siteIds.push(row.id)
  }

  ttPacRef.value?.open()
  ttPacRef.value?.setSiteIds(siteIds.join(','))
}

// 联调
const addLinkDebug = async (record) => {
  linkDebugRef.value?.open()
  linkDebugRef.value?.setFormData(record)
}

// 页面数据初始化
const initPage = async () => {
  await getMediaOptions()
  await getAgentOptions()
  await getAuthList()
}

// SaTable 数据请求
const refresh = async () => {
  crudRef.value?.refresh()
}

// 页面加载完成执行
onMounted(async () => {
  initPage()
  refresh()
})
</script>

<script>
export default { name: 'v1/advert/agentSite' }
</script>
