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

    <!-- 表格 -->
    <div class="layout-container">
      <Table @getTableData="changeTableData" v-model:page="page" ref="table" :data="tableData"
        @selection-change="handleSelectionChange">
        <el-table-column prop="ditchId" label="渠道ID" />
        <el-table-column prop="ditchType" label="渠道类型">
          <template #default="scope">
            {{ getDictionaryName("app_type", scope.row.ditchType) }}
          </template>
        </el-table-column>
        <el-table-column prop="ditchName" label="渠道类型名称" />
        <el-table-column prop="createTime" label="创建时间">
          <template #default="scope">
            {{ convertUTCToBeijing(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" v-permission="'permission'">
          <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="120px" style="margin-right:30px;">
        <el-form-item label="渠道类型：" required prop="ditchType">
          <el-select v-model="formEdit.ditchType" placeholder="请选择渠道类型" filterable style="width: 100%;">
            <el-option v-for="option in getOptions('app_type').slice(1,3)" :key="option.label" :label="option.label"
              :value="option.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="渠道类型名称：" required prop="ditchName">
          <el-input v-model="formEdit.ditchName" placeholder="请输入渠道类型名称" clearable />
        </el-form-item>
      </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 { ditchList, ditchAddOne, ditchDeleteOne, ditchUpdateOne } from '@/api/outBagModule.js'
import { usePermission } from '@/hooks/usePermission.js'

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

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

const formSearch = ref({
  ditchName: null,
  page: 1,// 当前页码
  limit: 20,// 当前页数量(查询量)
});

const dynamicFormItems = ref([])

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

// 获取缓存数据设置筛选数据
const settingData = () => {
  loadDictData().then(() => {
    dynamicFormItems.value = [
      {
        label: '渠道名称',
        prop: 'ditchName',
        type: 'input',
        labelWidth: 100,
        needEnterEvent: true
      },
    ]
  })
}

// 分页数据
const getList = async () => {
  let res = await ditchList({ ...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.ditchName = formData.ditchName;

  getList();
};

// 表单重置
const handleFormReset = () => {
  formSearch.value = {
    ditchName: null,
    page: 1,// 当前页码
    limit: 20,// 当前页数量(查询量)
    total: 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: '30vw',
  edit: false, //是否编辑
});

const formEdit = ref({
  ditchId: undefined,
  ditchName: undefined,
  ditchType:undefined,
})

const edit = (row) => {
  ruleForm.value?.resetFields()
  if (row) {
    layer.value.title = '编辑渠道类型'
    layer.value.edit = true
    formEdit.value.ditchId = row.ditchId
    formEdit.value.ditchName = row.ditchName
    formEdit.value.ditchType = Number(row.appType) || undefined
  } else {
    layer.value.title = '新增渠道类型'
    layer.value.edit = false
    // 重置数据
    formEdit.value = {
      ditchId: undefined,
      ditchName: undefined,
      ditchType:undefined,
    }
  }
  layer.value.show = true
}

const ruleForm = ref(null);

const rules = reactive({
  ditchName: [
    { required: true, message: "请输入新增渠道类型名称", trigger: "blur" },
  ],
  ditchType: [
    { required: true, message: "请选择渠道类型", trigger: "change" },
  ],
});

const submit = async (formEl) => {
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // 提交内容
      // console.log('新增提交的内容', formEdit.value)
      if (layer.value.edit) {
        await ditchUpdateOne({ ...formEdit.value }).then((res) => {
          ElMessage.success('保存成功')
          layer.value.show = false
          getList();
        })
      } else {
        await ditchAddOne({ ...formEdit.value }).then((res) => {
          ElMessage.success('保存成功')
          layer.value.show = false
          getList();
        })
      }
    } else {
      console.log("error submit!", fields);
    }
  })
}

// 删除用户
const removeType = async (row) => {
  await ditchDeleteOne({ ditchId: row.ditchId }).then((res) => {
    ElMessage.success('删除成功')
    getList();
  })
}

</script>

<style scoped lang="scss">
.layout-container {
  .button {
    display: flex;
    // flex-direction: column;

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