<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="渠道类型" />
        <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="appName" label="备注" />
        <el-table-column label="操作" fixed="right">
          <template #default="scope">
            <div class="button">
              <el-button class="button-item" type="primary" style="margin-bottom: 5px;" @click="edit(scope.row)">
                编辑
              </el-button>
              <el-popconfirm placement="left" title="确认删除该广告位?" @confirm="removeType(scope.row)">
                <template #reference>
                  <el-button class="button-item" style="margin-bottom: 5px;" type="danger">删除
                  </el-button>
                </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="渠道类型名称：" required prop="placementName">
              <el-input v-model="formEdit.placementName" placeholder="请输入渠道类型名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="10">
            <el-form-item label="用途：" required prop="appData">
              <el-select v-model="formEdit.appData" filterable placeholder="请选择用途">
                <el-option v-for="item in useWayOptions" :key="item.label" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </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 v-for="item in agencyOptions" :key="item.label" :label="item.label" :value="item.value">
                </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="remark">
              <el-input v-model="formEdit.remark" placeholder="请输入备注" clearable />
            </el-form-item>
          </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 { getUserList, getStaticList, riskBannedUser, riskLockUser } from '@/api/userModule.js'
import { riskChangeUserStatus } from '@/api/riskModule.js'
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,
  limit: 20,
  total: 0,
});

// 分页参数, 供table使用
const appPage = reactive({
  pageNum: 1,
  pageSizes: 999,
  limit: 999,
  total: 0,
});

// 用途options
const useWayOptions = reactive([
  { value: 1, label: '应用商城' },
  { value: 2, label: '投放' },
  { value: 3, label: '代理' },
  { value: 4, label: '游戏赚' },
])

// 所属代理options
const agencyOptions = reactive([
  { value: 1, label: '乐助客' },
  { value: 2, label: '众人帮' },
  { value: 3, label: '秒单' },
  { value: 4, label: '赏帮赚' },
  { value: 5, label: '兴旺富贵' },
  { value: 6, label: '合众' },
])

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

const changeAppTableData = () => {
  appFormSearch.value.pageNum = appPage.pageNum;
  appFormSearch.value.pageSizes = appPage.pageSizes;
  appFormSearch.value.limit = appPage.limit;
  // 分页切换
  getAppList();
};

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


const appFormSearch = ref({
  page: 1,// 当前页码
  pageSizes: 999,// 总页数
  limit: 999,
  total: null,// 总条数
});

const dynamicFormItems = ref([])

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

// 获取缓存数据设置筛选数据
const settingData = () => {
  loadDictData().then(() => {
    dynamicFormItems.value = [
      {
        label: '渠道名称',
        prop: 'placementId',
        type: 'input',
      },
      {
        label: '所属代理',
        prop: 'placementId1',
        type: 'select',
        options: agencyOptions
      },
    ]
  })
}

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

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

// 搜索
const handleFormSubmitted = (formData) => {
  // console.log("接收到子组件传递的数据", formData);
  formSearch.value.page = 1;
  formSearch.value.pageSizes = 20;
  formSearch.value.total = page.total;
  formSearch.value.limit = 20;
  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,// 当前页码
    pageSizes: 20,// 总页数
    registryTime: null,// 注册时间
    total: null,// 总条数
    userType: null,// 用户类型
  };
  getList();
};

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

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

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 = appData.value.find(item => item.appId === 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.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 {
  .button {
    display: flex;
    flex-direction: column;

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