
<template>
  <a-drawer
    v-model:visible="vdata.isShow"
    :title="vdata.isAdd ? '新增广告' : '编辑广告'"
    width="60%"
    :mask-closable="false"
    @close="vdata.isShow = false"
  >
    <a-form
      ref="infoFormModel"
      :model="vdata.saveObject"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 15 }"
      :rules="rules"
    >
      <a-row justify="center" type="flex">
        <a-col :span="24">
          <a-form-item label="标题" name="title">
            <a-input v-model:value="vdata.saveObject.title" />
          </a-form-item>
        </a-col>
        <a-col v-if="!(vdata.groupKey == 'agentAdvert' || vdata.groupKey == 'mchAdvert')" :span="24">
          <a-form-item label="状态" name="releaseState">
            <a-radio-group v-model:value="vdata.saveObject['releaseState']">
              <a-radio :value="1">
                立即发布
              </a-radio>
              <a-radio :value="0">
                手动发布
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col v-if="vdata.groupKey == 'afterAdvert'" :span="24">
          <a-form-item label="广告位置" name="appPlace">
            <a-radio-group v-model:value="vdata.saveObject['appPlace']" @change="adRadioChange">
              <a-radio :value="4">
                点金计划广告
              </a-radio>
              <a-radio :value="5">
                小程序广告
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col v-if="vdata.groupKey == 'afterAdvert' && vdata.saveObject.appPlace == 5" :span="24">
          <div class="tips">建议尺寸 700 x 380px</div>
          <a-form-item label="广告图片" name="imgUrl">
            <JeepayUpload v-model:src="vdata.saveObject.imgUrl" bizType="notice" />
          </a-form-item>
        </a-col>
        <a-col v-if="vdata.groupKey == 'afterAdvert'" :span="24">
          <a-form-item label="广告链接" name="linkUrl">
            <a-input v-model:value="vdata.saveObject.linkUrl" />
          </a-form-item>
        </a-col>
        <div v-if="vdata.groupKey == 'afterAdvert'" style="margin:10px 30px"> <a-alert message="注意：小程序打开链接需配置合法请求域名!" type="warning" /></div>
      </a-row>

      <a-row v-if="(vdata.groupKey == 'appMchAdvert' || vdata.groupKey == 'appAgentAdvert') && vdata.isAdd" justify="center" type="flex">
        <a-divider orientation="left">APP广告配置</a-divider>
        <a-col :span="24">
          <a-form-item label="广告位置" name="appPlace">
            <a-radio-group v-model:value="vdata.saveObject['appPlace']" @change="adRadioChange">
              <a-radio :value="1">
                启动页
              </a-radio>
              <a-radio :value="2">
                首页
              </a-radio>
              <a-radio :value="3">
                我的页
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col v-if="vdata.saveObject.appPlace != 1" :span="24">
          <a-form-item label="广告类型" name="appPlaceType">
            <a-radio-group v-model:value="vdata.saveObject['appPlaceType']" @change="appPlaceTypeFunc">
              <a-radio :value="1">
                卡片广告
              </a-radio>
              <a-radio :value="2">
                轮播广告
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row
        v-if="(vdata.groupKey == 'agentAdvert' || vdata.groupKey == 'mchAdvert' || vdata.groupKey == 'faceAdvert' || vdata.groupKey == 'appMchAdvert' || vdata.groupKey == 'appAgentAdvert')"
      >
        <a-divider orientation="left">{{ vdata.saveObject.appPlaceType == 1?'卡片广告设置':'轮播广告设置' }}</a-divider>
  
        <a-col v-if="vdata.saveObject.appPlaceType != 1 && (vdata.saveObject.appPlaceType == 3 || vdata.saveObject.appPlaceType == 4)" :span="24">
          <a-form-item label="轮播时间（秒）" name="changeTime">
            <a-input-number v-model:value="vdata.saveObject['changeTime']" style="width: 100%;" :min="0" :max="100" />
          </a-form-item>
        </a-col>

        <a-col :span="24">
          <a-button
            class="editable-add-btn"
            style="margin-bottom: 8px;margin-left: 30px;"
            type="dashed"
            @click="handleAdd"
          >
            <PlusOutlined />新增
          </a-button>
          <span v-if="vdata.saveObject.appPlaceType == 1" style="margin-left: 15px;">卡片广告最多添加两张图片！</span>
          <div v-if="vdata.groupKey == 'appMchAdvert' || vdata.groupKey == 'appAgentAdvert'" style="margin:10px 30px"> <a-alert message="注意：小程序打开链接需配置合法请求域名!" type="warning" /></div>
          <div v-if="vdata.saveObject.appPlaceType == 1" style="margin:10px 30px"> <a-alert message="广告图片单张建议宽度680px,建议最大高度680px 多张建议宽度320px,建议最大高度400px。" type="warning" /></div>
          <a-table bordered :data-source="vdata.saveObject.infoList" :columns="columns">
            <template #headerCell="{ title, column }">
              <a-tooltip v-if="column.ellipsis" :title="title" :overlayStyle="{ whiteSpace: 'nowrap',maxWidth:'1000px'}">
                {{ title }}
              </a-tooltip>
              <div v-else>{{ title }}</div>
            </template>
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'imgUrl'">
                <div class="editable-cell">
                  <div class="editable-cell-input-wrapper">
                    <JeepayUpload v-model:src="record.imgUrl" bizType="notice" listType="picture-card" />
                  </div>
                </div>
              </template>
              <template v-else-if="column.dataIndex === 'sort'">
                <div class="editable-cell-input-wrapper">
                  <a-input-number v-model:value="record.sort" :min="0" :max="10" />
                </div>
              </template>
              <template v-else-if="column.dataIndex === 'linkUrl' && vdata.groupKey != 'faceAdvert'">
                <div class="editable-cell-input-wrapper">
                  <a-input v-model:value="record.linkUrl" placeholder="请以http://或https://开头" />
                </div>
              </template>
              <template v-else-if="column.dataIndex === 'operation'">
                <a style="color: red" @click="onDelete(record)">删除</a>
              </template>
            </template>
          </a-table>
        </a-col>
      </a-row>

      <div v-if="vdata.isAdd">
        <a-row v-if="vdata.groupKey == 'faceAdvert'" justify="center" type="flex">
          <a-divider orientation="left">所属商户配置</a-divider>
          <a-col :span="24">
            <a-form-item label="发布商户" name="bindType">
              <a-space>
                <a-radio-group v-model:value="vdata.saveObject.bindType">
                  <a-radio :value="0">全部商户</a-radio>
                  <a-radio :value="1">指定商户</a-radio>
                </a-radio-group>
                <a-button v-if="vdata.saveObject.bindType == 1" type="primary" @click="showQrcSelectModel">选择商户</a-button>
              </a-space>
            </a-form-item>
          </a-col>
          <a-col v-if="vdata.saveObject.bindType == 1" :span="24">
            <a-form-item label="所属商户" name="infoIds">
              <a-textarea v-model:value="vdata.saveObject.infoIds" disabled />
            </a-form-item>
          </a-col>
        </a-row>
      </div>
    </a-form>


    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" @click="vdata.isShow = false"><close-outlined /> 取消</a-button>
      <a-button type="primary" :loading="vdata.confirmLoading" @click="handleOkFunc"><check-outlined /> 保存</a-button>
    </div>
  </a-drawer>
  <!-- 选择商户组件 -->
  <JeepayModelSelectMchList ref="jeepayModelSelectMchRef" @selectFinishFunc="selectQrcFinishFunc" />
</template>
<script lang="ts" setup>
import { req, API_URL_ADVERT } from '@/api/manage'

import { reactive, ref, getCurrentInstance, computed ,watch} from 'vue'

const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties

const infoFormModel = ref()
const jeepayModelSelectMchRef = ref()

const props = defineProps({
  callbackFunc: { type: Function, default: () => { } },
  columnsType: { type: Number, default: 0 }
})


const columnsObj: any = {
  0: [
    { title: '广告图片（建议尺寸 800x1280px）', dataIndex: 'imgUrl', width: '30%',ellipsis:true, },
    { title: '轮播排序', dataIndex: 'sort', },
    { title: '操作', dataIndex: 'operation', },
  ],
  1: [
    { title: '广告图片', dataIndex: 'imgUrl', width: '30%',ellipsis:true,},
    { title: '轮播排序', dataIndex: 'sort', },
    { title: '轮播图链接', dataIndex: 'linkUrl', },
    { title: '操作', dataIndex: 'operation', },
  ],

}
// 侦听数据 发成变化 重新赋值表头
watch(() => props.columnsType, () => {
  columns.value = columnsObj[props.columnsType]
})

const columns = ref(columnsObj[props.columnsType])
const count = computed(() => vdata.saveObject.infoList.length + 1)

const onDelete = (item) => {
  // vdata.saveObject.infoList = vdata.saveObject.infoList.filter(item => item.key !== key)
  const index = vdata.saveObject.infoList.indexOf(item)
  if (index != -1) {
    vdata.saveObject.infoList.splice(index, 1)
  }
}

const handleAdd = () => {
  if (vdata.saveObject.appPlaceType == '1' && vdata.saveObject.infoList.length > 1) {
    return $infoBox.message.error('卡片广告最多添加两条记录！')
  }
  const newData = { key: `${count.value}`, imgUrl: ``, sort: '', linkUrl: ``, }
  vdata.saveObject.infoList.push(newData)
}

const vdata: any = reactive({
  confirmLoading: false, // 显示确定按钮loading图标
  isAdd: true, // 新增 or 修改页面标识
  isShow: false, // 是否显示弹层/抽屉
  saveObject: {
    infoList: [{ key: '0', imgUrl: '', linkUrl: '', sort: '' }]
  } as any, // 数据对象
  recordId: null, // 更新对象ID
  groupKey: '',
})

const rules = {
  title: [{ required: true, message: '请输入广告标题', trigger: 'blur' }],
  releaseState: [{ required: true, message: '请选择发布状态', trigger: 'blur' }],
  imgUrl: [{ required: true, message: '请上传广告图片', trigger: 'blur' }],
  linkUrl: [{ required: true, message: '请输入广告链接', trigger: 'blur' }],
  content: [{ required: true, message: '请输入广告内容', trigger: 'blur' }],
  bindType: [{ required: true, message: '请选择发布商户类型', trigger: 'blur' }],
  infoIds: [{ required: true, message: '请选择要发布的商户', trigger: 'blur' }],
  appPlace: [{ required: true, message: '请选择广告位置', trigger: 'blur' }],
  appPlaceType: [{ required: true, message: '请选择广告类型', trigger: 'blur' }],
  advertSort: [{ required: true, message: '请输入广告排序', trigger: 'blur' }],
  changeTime: [{ required: true, message: '请输入轮播时间', trigger: 'blur' }],
}


function show(groupKey, recordId, searchData) { // 弹层打开事件
  if (infoFormModel.value !== undefined) {
    infoFormModel.value.resetFields()
  }
  console.log(groupKey,'groupKeygroupKey')
  vdata.groupKey = groupKey
  vdata.isAdd = !recordId
  
  // 数据恢复为默认数据
  vdata.saveObject = { bindType: 0, releaseState: 1 }
  vdata.saveObject.infoList = [{ imgUrl: '', linkUrl: '', sort: '' }]

  vdata.confirmLoading = false // 关闭loading
  if (searchData) {
    Object.assign(vdata.saveObject, searchData)
  }
  if (!vdata.isAdd) { // 修改信息 延迟展示弹层
    vdata.recordId = recordId
    req.getById(API_URL_ADVERT, recordId).then(res => {
      vdata.saveObject = res
      if (vdata.saveObject.appContent) {
        vdata.saveObject.infoList = JSON.parse(vdata.saveObject.appContent)
      }
    })
  }
  vdata.isShow = true // 立马展示弹层信息
}

function handleOkFunc() { // 点击【确认】按钮事件
  infoFormModel.value.validate().then(valid => {

    vdata.confirmLoading = true // 显示loading
    if (vdata.groupKey != 'afterAdvert' && vdata.saveObject.infoList.length < 1) {
      vdata.confirmLoading = false
      return $infoBox.message.error('轮播配置不可为空')
    } 

    if (vdata.groupKey == 'faceAdvert') {
      vdata.saveObject.advertType = '1'
      if (vdata.saveObject.infoIds && vdata.isAdd) {
        vdata.saveObject.infoIds = vdata.saveObject.infoIds.join(',')
      }
    } else if (vdata.groupKey == 'afterAdvert') {
      vdata.saveObject.advertType = '2'
    } else if (vdata.groupKey == 'appMchAdvert') {
      vdata.saveObject.advertType = '3'
    } else if (vdata.groupKey == 'appAgentAdvert') {
      vdata.saveObject.advertType = '4'
    } else if (vdata.groupKey == 'mchAdvert') {
      vdata.saveObject.advertType = '5'
      vdata.saveObject.releaseState = '1'
    } else if (vdata.groupKey == 'agentAdvert') {
      vdata.saveObject.advertType = '6'
      vdata.saveObject.releaseState = '1'
    }

    if (vdata.groupKey != 'afterAdvert') {
      if (vdata.saveObject.infoList) {
        var firstInfo = vdata.saveObject.infoList[0]
        if (!firstInfo.imgUrl) {
          vdata.confirmLoading = false
          return $infoBox.message.error('轮播图不可为空')
        }
        vdata.saveObject.imgUrl = firstInfo.imgUrl
        vdata.saveObject.linkUrl = firstInfo.linkUrl
      }
      vdata.saveObject.appContent = JSON.stringify(vdata.saveObject.infoList)
    }

    // 请求HTTP 
    req.addOrUpdate(vdata.isAdd ? null : vdata.recordId, API_URL_ADVERT, vdata.saveObject).then(res => {
      vdata.isShow = false
      vdata.confirmLoading = false
      props.callbackFunc() // 刷新列表
    }).catch(valid => {
      vdata.confirmLoading = false
    })
  })
}

// 选择商户弹窗
function showQrcSelectModel() {
  if (vdata.saveObject.bindType == 1) {
    jeepayModelSelectMchRef.value.show(vdata.saveObject.infoIds, { advertFlag: '1' })
  }
}

// 选择商户完成
function selectQrcFinishFunc(e) {

  if (!e || e.length <= 0) {
    return $infoBox.message.error('请选中要发布广告的商户！')
  }

  vdata.saveObject.infoIds = e
  jeepayModelSelectMchRef.value.close()
}

function appPlaceTypeFunc(e) {
  console.log(e)
  if (vdata.saveObject.appPlaceType == 1 && vdata.saveObject.infoList.length > 2) {
    vdata.saveObject.infoList = vdata.saveObject.infoList.splice(0, 2)
  }
  if(e.target.value ==2){
    columns.value[0].title = '广告图片（建议尺寸 680 x 300px）'
  }else if(e.target.value ==1){
    columns.value[0].title = '广告图片'
  }
}
// 切换广告位置
const adRadioChange=(e:any)=>{
  if(e.target.value ==1){
    columns.value[0].title = '广告图片（建议尺寸 1080 x 1882px）'
  }else{
    console.log(vdata.saveObject?.appPlace)
    if(vdata.saveObject?.appPlaceType) return appPlaceTypeFunc({target:{value:vdata.saveObject.appPlaceType}})
    columns.value[0].title = '广告图片'
  }
  
}
watch(()=>vdata.groupKey,()=>{

  if( vdata.groupKey=='mchAdvert' || vdata.groupKey=='agentAdvert'){
    columns.value[0].title = '广告图片（建议尺寸 960 x 500px）'
  }else if(props.columnsType==1){
    columns.value[0].title = '广告图片'
  }
})
defineExpose({ show })
</script>
<style lang="less" scoped>
.ant-btn-dangerous {
  position: absolute;
  right: 50px;
}

.ant-row-space-between {
  position: relative;
}

</style>