<script setup lang="ts">
import { useRenderIcon } from "/@/components/ReIcon/src/hooks";
import { httpBusinesslist } from "/@/api/interest/organize";
import { httpAdd, httpUpdate } from "/@/api/serviceParam/terrace";
import { computed, onMounted, ref } from "vue";
import { useVModel } from "@vueuse/core"

import PlatformModal from "./platform-modal.vue"

import { platformTypeOptions, platformOptions, hasPlatformOptions, rules, initialData } from "./../config/_options"
import { ElMessage } from "element-plus";

const emit = defineEmits(['refresh'])
const props = defineProps<{ data: any; visible: boolean; disabled: boolean }>()

const business = ref<any[]>([])
const title = computed(() => data.value.id ? (props.disabled ? '查看平台' : '编辑平台') : '添加平台')

const data = useVModel(props, 'data')
const visible = useVModel(props, 'visible')
const chooseVisible = ref(false)

const formRef = ref<any | null>(null)

async function requestBusiness() {
  const res = await httpBusinesslist({ size: 100 })
  business.value = res.code === 0 ? res.data.list : []
}

function handleClose() {
  data.value = initialData()
  visible.value = false
}


const loading = ref(false)
async function onSubmit() {
  try {
    await formRef.value.validate();
    const { id, platform_name, platform_type, use_type, is_select_pay_rate, pay_list, desc } = data.value;
    const parameter = { id, platform_name, platform_type, use_type, is_select_pay_rate, pay_list, desc }
    const isCreate = id === undefined || !id

    if (parameter.is_select_pay_rate === '1') {
      // 开启支付渠道
      if (parameter.pay_list.length === 0) {
        ElMessage.warning('请添加至少一个支付渠道!')
        return
      } else {
        parameter.pay_list = parameter.pay_list.map(({ id, ...rest }) => ({ ...rest, channel_id: id }))
      }
    } else {
      // 关闭支付渠道(清空支付渠道)
      parameter.pay_list = []
    }

    // 删除ID
    if (isCreate) {
      delete parameter['id']
    }

    const api = isCreate ? httpAdd : httpUpdate
    loading.value = true
    const res = await api(parameter)
    loading.value = false
    if (res.code === 0) {
      visible.value = false
      ElMessage.success(`${isCreate ? '添加' : '更新'}成功`)
      emit('refresh')
    } else {
      ElMessage.warning(`${isCreate ? '添加' : '更新'}失败`)
    }
  } catch (err) {
    console.log(err);
  }
}

onMounted(requestBusiness)
</script>


<template>
  <ElDialog v-model="visible" :title="title" center @close="handleClose">
    <ElForm :model="data" :rules="rules" size="small" ref="formRef" :disabled="disabled">
      <ElRow :gutter="10">
        <ElCol :span="24">
          <ElFormItem label="平台名称" prop="platform_name">
            <ElInput v-model="data.platform_name" style="width:100%" placeholder="平台名称" :maxlength="50"
              show-word-limit />
          </ElFormItem>
        </ElCol>

        <ElCol :span="8">
          <ElFormItem label="平台类型" prop="use_type">
            <ElSelect v-model="data.use_type" :disabled="data.id" style="width:100%" placeholder="平台类型">
              <ElOption v-for="opt in platformTypeOptions" :key="opt.value" :value="opt.value" :label="opt.label" />
            </ElSelect>
          </ElFormItem>
        </ElCol>

        <ElCol :span="8">
          <ElFormItem label="对接平台" prop="platform_type">
            <ElSelect v-model="data.platform_type" :disabled="data.id" style="width:100%" placeholder="对接平台">
              <ElOption v-for="opt in platformOptions" :key="opt.value" :value="opt.value" :label="opt.label" />
            </ElSelect>
          </ElFormItem>
        </ElCol>

        <ElCol :span="8">
          <ElFormItem label="是否开启支付渠道" prop="is_select_pay_rate">
            <ElSelect v-model="data.is_select_pay_rate" :disabled="data.id" style="width:100%" placeholder="是否开启支付渠道">
              <ElOption v-for="opt in hasPlatformOptions" :key="opt.value" :value="opt.value" :label="opt.label" />
            </ElSelect>
          </ElFormItem>
        </ElCol>

        <ElCol :span="24" v-if="data.is_select_pay_rate === '1'">
          <ElFormItem label="支付渠道">
            <ElTable :data="data.pay_list" border size="small" max-height="200px">
              <ElTableColumn label="渠道名称" prop="channel_name" showOverflowTooltip />
              <ElTableColumn label="业务公司" prop="companyName" showOverflowTooltip />
              <ElTableColumn label="操作" width="80px" v-if="!data.id">
                <template #header>
                  <div class="flex justify-between">
                    <p>操作</p>
                    <ElTooltip placement="top" content="添加">
                      <ElButton size="small" type="primary" link :icon="useRenderIcon('add')"
                        @click="chooseVisible = true" />
                    </ElTooltip>
                  </div>
                </template>

                <template #="{ $index }">
                  <ElButton size="small" type="primary" link :icon="useRenderIcon('delete')"
                    @click="() => data.pay_list.splice($index, 1)" />
                </template>
              </ElTableColumn>
            </ElTable>
          </ElFormItem>
        </ElCol>
      </ElRow>

      <div class="flex w-full justify-end">
        <ElButton type="primary" :loading="loading" @click="onSubmit">保存</ElButton>
      </div>
    </ElForm>

    <PlatformModal v-model:visible="chooseVisible" v-model:pay_list="data.pay_list" />
  </ElDialog>
</template>
