<script lang="ts" setup>
import { watch, ref, shallowRef } from "vue"
import { useVModel } from "@vueuse/core"
import { httpChannels } from "/@/api/list-collection";
import { useResponseHandle } from "/@/hooks/core/useAsync";
import { ElMessage } from "element-plus";

const initialParameter = {
  channel_name: '',
  page: 1,
  size: 15
}

const props = defineProps<{ visible: boolean, pay_list: any[] }>()
const loading = shallowRef(false)
const payList = useVModel(props, 'pay_list')
const visible = useVModel(props, 'visible')

const list = ref<any[]>([])
const selected = ref<any[]>([])
const recordTotal = shallowRef(0)
const responseHandle = useResponseHandle()
const parameter = ref({ ...initialParameter })

async function requestChannels() {
  loading.value = true
  const { code, message, data } = await httpChannels(parameter.value)
  loading.value = false
  responseHandle({
    code,
    message,
    handler: () => {
      list.value = data.list
      recordTotal.value = data.count
    }
  })
}

function unique(){
  const sourceIds:any[] = payList.value.map(({id}) => id)
  return selected.value.filter(({id}) => !sourceIds.includes(id))
}

function save(){
  if(selected.value.length === 0){
    ElMessage.warning('请至少选择一个平台')
    return
  }
  const values = unique()
  payList.value = [...payList.value, ...values];
  visible.value = false
}

function onClose(){
  parameter.value = { ...initialParameter }
  selected.value = []
}

watch(() => props.visible, () => {
  if (!props.visible) return
  requestChannels()
}, {
  immediate: true
})
</script>


<template>
  <ElDialog v-model="visible" title="选择平台" center @close="onClose">
    <div class="flex flex-col" v-loading="loading">
      <ElRow class="mb-[10px]">
        <ElCol :span="4">
          <ElInput size="small" placeholder="渠道名称" v-model="parameter.channel_name" @change="requestChannels" />
        </ElCol>
      </ElRow>

      <ElTable border size="small" :data="list"  @selection-change="val => selected = val">
        <ElTableColumn type="selection" width="45" />
        <ElTableColumn label="渠道名称" prop="channel_name" showOverflowTooltip />
        <ElTableColumn label="业务公司名称" prop="companyName" showOverflowTooltip />
      </ElTable>

      <div class="flex justify-between mt-[10px]">
        <el-pagination 
          v-model:current-page="parameter.page" 
          v-model:page-size="parameter.size"
          :page-sizes="[15, 50, 100]" 
          :small="true" :background="true"
          layout="total, sizes, prev, pager, next, jumper" 
          :total="recordTotal" 
          @size-change="requestChannels"
          @current-change="requestChannels" 
        />

        <ElButton type="primary" size="small" @click="save">保存</ElButton>
      </div>
    </div>
  </ElDialog>
</template>
