<template>
  <div class="layout-container">
    <!-- 菜单栏 -->
    <From :form-items="dynamicFormItems" @formSubmitted="handleFormSubmitted" @formReset="handleFormReset"
          is_add_button="新增" @addForm="edit"/>

    <!-- 表格 -->
    <div class="layout-container">
      <Table @getTableData="changeTableData" v-model:page="page" ref="table" :data="tableData"
             @selection-change="handleSelectionChange">
        <el-table-column prop="placementId" label="广告位ID"/>
        <el-table-column prop="placementName" label="广告位名称"/>
        <el-table-column prop="adFormat" label="广告位样式">
          <template #default="scope">
            {{ getDictionaryName("ad_format", scope.row.adFormat) }}
          </template>
        </el-table-column>
        <el-table-column prop="appName" label="所属平台应用"/>
        <el-table-column prop="networkAppName" label="所属渠道应用"/>
        <el-table-column prop="appType" label="类型" width="100">
          <template #default="scope">
            {{ getDictionaryName("app_type", scope.row.appType) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="广告位状态" width="100">
          <template #default="scope">
            {{ getDictionaryName("placement_status", scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <div class="button">
              <el-link class="button-item" type="primary" style="margin-bottom: 5px;"
                         @click="edit(scope.row)">
                编辑
              </el-link>
              <el-popconfirm placement="left" title="确认删除该广告位?" @confirm="removeType(scope.row)">
                <template #reference>
                  <el-link class="button-item" style="margin-bottom: 5px;"
                             type="danger">删除
                  </el-link>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </Table>
    </div>

    <!-- 操作弹窗 -->
    <Layer :layer="layer" @confirm="submit(ruleForm)" @close="layer.show = false">
      <el-form :model="formEdit" :rules="rules" ref="ruleForm" label-width="240px" style="margin-right:30px;">
        <el-row :gutter="5">
          <el-col :span="10">
            <el-form-item label="关联app：" required prop="appData">
              <el-select v-model="formEdit.appData" filterable placeholder="请选择">
                <el-option
                    v-for="item in appData"
                    :key="item.appId"
                    :label="item.appName"
                    :value="item.appId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2" ></el-col>
          <el-col :span="10">
            <el-form-item label="广告位名称：" required prop="placementName">
              <el-input v-model="formEdit.placementName" placeholder="请输入广告位名称" clearable/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="5">
          <el-col :span="10">
            <el-form-item label="广告样式：" required prop="adFormat">
              <el-select v-model="formEdit.adFormat" placeholder="请选择广告样式">
                <el-option value="native" label="原生(信息流)"/>
                <el-option value="banner" label="横幅"/>
                <el-option value="rewarded_video" label="激励视频"/>
                <el-option value="interstitial" label="插屏(插屏视频/插屏图片)"/>
                <el-option value="splash" label="开屏广告"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="10">
            <el-form-item label="备注：" required prop="remark">
              <el-input v-model="formEdit.remark" placeholder="请输入备注" clearable/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="5">
          <el-col :span="10">
            <el-form-item label="广告位状态：" required prop="status">
              <el-select v-model="formEdit.status" placeholder="请选择广告位状态">
                <el-option :value="1" label="锁定"/>
                <el-option :value="2" label="待审核"/>
                <el-option :value="3" label="正常"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="10">

          </el-col>
        </el-row>

      </el-form>
    </Layer>
  </div>
</template>

<script setup>
import {onBeforeMount, ref, reactive} from "vue";
import From from "@/components/from/index.vue";
import Table from "@/components/table/index.vue";
import Layer from '@/components/layer/index.vue'
import {ElMessage} from 'element-plus'
import {convertUTCToBeijing} from '@/utils/index.js'
import {useGetDictList} from '@/hooks/useGetDictList.js'
import {useStore} from 'vuex'
import {appList, placementList, placementDel, placementSave} from "@/api/formworkErection";

const store = useStore()
const {dictData, loadDictData, getOptions, getDictionaryName} = useGetDictList();
const form = ref(null);
const tableData = ref([]);
const appData = ref([]);

// 分页参数, 供table使用
const page = reactive({
  pageNum: 1,
  pageSize: 20,
  total: 0,
});

// 分页数据
const getAppList = async () => {
  let res = await appList({page: 1, limit: 999,});
  appData.value = res.data;
  console.log('appData.value',appData.value)
};

function findByDitchName(id) {
  return appData.value.find(item => item.appId === id)
}

const formSearch = ref({
  channelOrigin: null,// 渠道来源
  channelType: null,// 渠道类型
  lastLoginTime: '',// 最新登录时间
  limit: 20,// 当前页数量(查询量)
  nickName: null,// 用户昵称
  page: 1,// 当前页码
  registryTime: null,// 注册时间
  userType: null,// 用户类型
});

const dynamicFormItems = ref([])

onBeforeMount(() => {
  settingData()
  getList();
  getAppList();
});

// 获取缓存数据设置筛选数据
const settingData = () => {
  loadDictData().then(() => {
    dynamicFormItems.value = [
      {
        label: '广告位ID',
        prop: 'placementId',
        type: 'input',
        needEnterEvent: true
      },
      {
        label: '广告位名称',
        prop: 'placementName',
        type: 'input',
        needEnterEvent: true
      },
      {
        label: '平台应用',
        prop: 'appName',
        type: 'input',
        needEnterEvent: true
      },
      {
        label: '广告位状态',
        prop: 'channelType',
        type: 'select',
        options: getOptions('placement_status')
      },
      // { label: '登录日期', prop: 'loginTime', type: 'daterange' },
    ]
  })
}

// 分页数据
const getList = async () => {
  let res = await placementList({...formSearch.value});
  tableData.value = res.data;
  page.total = res.pageMeta.total;
};

const changeTableData = (type) => {
    formSearch.value.page = type ? 1 : page.pageNum;
    formSearch.value.limit = page.pageSize;
    // 分页切换
    getList();
};

// 搜索
const handleFormSubmitted = (formData) => {
  // console.log("接收到子组件传递的数据", formData);
  formSearch.value.page = page.pageNum;
  formSearch.value.limit = page.pageSize;
  formSearch.value.nickName = formData.nickName;
  formSearch.value.channelOrigin = formData.channelOrigin;
  formSearch.value.channelType = formData.channelType;
  formSearch.value.userType = formData.userType;
  formSearch.value.lastLoginTime = formData.lastLoginTime || null
  formSearch.value.registryTime = formData.registryTime || null

  getList();
};

// 表单重置
const handleFormReset = () => {
  formSearch.value = {
    channelOrigin: null,// 渠道来源
    channelType: null,// 渠道类型
    lastLoginTime: null,// 最新登录时间
    limit: 20,// 当前页数量(查询量)
    nickName: null,// 用户昵称
    page: 1,// 当前页码
    registryTime: null,// 注册时间
    userType: null,// 用户类型
  };
  page.pageNum = 1
  page.pageSize = 20
  page.total = 0
  getList();
};

// 选择监听器
const handleSelectionChange = (val) => {
  context.emit("selection-change", val)
}

// 弹窗
const layer = ref({
  show: false,
  title: "新增广告位",
  showButton: true,
  width: '70vw'
});

const formEdit = ref({
  adFormat: undefined,//广告样式 *
  appId: undefined,//应用ID *
  appName: undefined,//应用名称 *
  enabled: undefined,//启用状态
  networkAppId: '1210971759',//广告渠道应用ID
  networkAppName: 'youlianghui',//广告渠道应用名称
  placementId: undefined,//广告位id
  placementName: undefined,//广告位名称 *
  remark: undefined, //备注 *
  status: undefined, //广告位状态 1-锁定 2-待审核 3-正常 *
  appData: [],//关联应用
})

const edit = (row) => {
  ruleForm.value?.resetFields()
  if (row) {
    layer.value.title = '编辑广告位'
    formEdit.value.placementName = row.placementName
    formEdit.value.adFormat = row.adFormat
    formEdit.value.remark = row.remark
    formEdit.value.status = row.status
    formEdit.value.placementId = row.placementId
    formEdit.value.appData = row.appId;

  } else {
    layer.value.title = '新增广告位'
    // 重置数据
    let formDatas = {
      adFormat: undefined,//广告样式
      appId: undefined,//应用ID
      appName: undefined,//应用名称
      enabled: undefined,//启用状态
      networkAppId: '1210971759',//广告渠道应用ID
      networkAppName: 'youlianghui',//广告渠道应用名称
      placementId: undefined,//广告位id
      placementName: undefined,//广告位名称
      remark: undefined, //备注
      status: undefined, //广告位状态 1-锁定 2-待审核 3-正常
      appData: [],//关联应用
    }
    Object.assign(formEdit.value, formDatas)
  }
  layer.value.show = true

}

const ruleForm = ref(null);

const rules = reactive({
  appData: [
    {required: true, message: "请选择关联应用", trigger: "change"},
  ],
  placementName: [
    {required: true, message: "请输入广告位名称", trigger: "blur"},
  ],
  adFormat: [
    {required: true, message: "请选择广告样式", trigger: "change"},
  ],
  remark: [
    {required: true, message: "请输入备注", trigger: "blur"},
  ],
  status: [
    {required: true, message: "请选择广告位状态", trigger: "change"},
  ],
});

const submit = async (formEl) => {
  formEdit.value.appData = findByDitchName(formEdit.value.appData)
  formEdit.value.appId = formEdit.value.appData.appId
  formEdit.value.appName = formEdit.value.appData.appName
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // 提交内容
      delete formEdit.value.appData
      console.log('新增提交的内容', formEdit.value )
     
      await placementSave({...formEdit.value}).then((res) => {
        ElMessage.success('保存成功')
        getList();
      })

      layer.value.show = false
    } else {
      console.log("error submit!", fields);
    }
  })
}

// 删除用户
const removeType = async (row) => {
  console.log('删除', row)
  await placementDel({placementId: row.placementId}).then((res)=> {
    ElMessage.success('删除成功')
    getList();
  })
}

</script>

<style scoped lang="scss">
.layout-container {

  .card {
    .title {
      margin-bottom: 10px;
      font-weight: 600;
    }

    display: flex;
    flex-direction: column;
    align-items: start;
    width: calc(100% - 60px);
    margin: 30px 30px 0;
  }

  .button {
    display: flex;
    // flex-direction: column;

    .button-item {
      margin: 4px;
    }
  }
}
</style>