<template>
  <div class="carousel">
    <!-- <Banner /> -->
    <div class="content">
      <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        highlight-current-row
        :action-list="[
          {
            text: '添加轮播图',
            action: () => openModal('add'),
          },
        ]"
        @get-list="getList">
        <template #slotName="{ item }">
          {{ item.createTime }}
        </template>
      </byTable>
    </div>
    <el-dialog :title="modalType == 'add' ? '新增' : '编辑'" v-model="dialogVisible" width="800" v-loading="loading">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="byform">
        <template #carouselUrl>
          <el-row style="width: 100%">
            <el-col :span="6">
              <el-form-item prop="carouselUrl">
                <el-upload
                    class="uploader-icon"
                    action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
                    :data="carouselUrlOne"
                    :show-file-list="false"
                    accept=".gif, .jpeg, .jpg, .png"
                    :on-success="carouselUrlSuccess"
                    :before-upload="uploadCarouselUrl">
                  <el-image
                      v-if="formData.data.carouselUrlList && formData.data.carouselUrlList.length > 0"
                      :src="formData.data.carouselUrlList[0].fileUrl"
                      fit="scale-down"
                      class="avatar" />
                  <el-icon v-else class="uploader-icon"><Plus /></el-icon>
                </el-upload>
                <el-button
                    class="delete-btn"
                    type="danger"
                    v-if="formData.data.carouselUrlList && formData.data.carouselUrlList.length > 0"
                    @click="formData.data.carouselUrlList = []">
                  删除
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </template>

        <template #menuId>
          <el-form-item prop="menuId">
            <el-select
                v-model="formData.data.columnId"
                :rule="rules.columnId"
                placeholder="请选择菜单"
                no-data-text="无数据，请到栏目菜单添加"
                @change="(val) => getArticleListSelect(val)"
            >
              <el-option
                  v-for="item in columnListData"
                  :label="item.name"
                  :value="item.id"
              >
              </el-option>
            </el-select>

          </el-form-item>

        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button type="primary" v-no-double-click="submitForm" size="large" :loading="submitLoading">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
/* eslint-disable vue/no-unused-components */
import { ElMessage, ElMessageBox } from "element-plus";
import byTable from "@/components/byTable/index.vue";
import byForm from "@/components/byForm/index.vue";
import { computed, ref } from "vue";
import {getDictOneByXmhjc, getFileList, getFileStr} from "@/api/XMHJC/common";
import {findColumnArticleList, findMenuListByOpen} from "@/api/XMHJC/column";
const loading = ref(false);
const submitLoading = ref(false);
const enableStatus = ref([]);
const carouselModules = ref([]);
const articleList = ref([]);
const columnListData = ref([]);
const targetType = ref([]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
  },
});
let dialogVisible = ref(false);
let modalType = ref("add");
let rules = ref({
  modules: [{ required: true, message: "请选择所属模块" }],
  title: [{ required: true, message: "请输入标题" }],
  status: [{ required: true, message: "请选择启用状态", trigger: "change" }],
  sort: [{ required: true, message: "请输入排序", trigger: "blur" }],

  carouselUrl: [{ required: true, message: "请上传轮播图", trigger: "blur" }],
});
const { proxy } = getCurrentInstance();
const config = computed(() => {
  return [
    {
        attrs: {
            label: "所属模块",
            prop: "modules",
        },
      render(type) {
        return proxy.dictValueLabel(type, carouselModules.value);
      },
    },
    {
      attrs: {
        label: "标题",
        prop: "title",
      },
    },
    {
      attrs: {
        label: "副标题",
        prop: "subTitle",
      },
    },
    {
      attrs: {
        label: "排序",
        prop: "sort",
        align: "center",
      },
    },
    {
      attrs: {
        label: "状态",
        prop: "status",
      },
      render(type) {
        return proxy.dictValueLabel(type, enableStatus.value);
      },
    },
    {
      attrs: {
        label: "操作",
        width: "200",
        align: "right",
      },
      // 渲染 el-button，一般用在最后一列。
      renderHTML(row) {
        return [
          {
            attrs: {
              label: row.status == 1 ? "禁用" : "启用",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              changeStatus(row);
            },
          },
          {
            attrs: {
              label: "编辑",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              getDetail(row);
            },
          },
          {
            attrs: {
              label: "删除",
              type: "danger",
              text: true,
            },
            el: "button",
            click() {
              del(row);
            },
          },
        ];
      },
    },
  ];
});

let formData = reactive({
  data: {},
  treeData: [],
  carouselUrlList:[],
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);
const formConfig = computed(() => {
  return [
    {
      label: "所属模块",
      prop: "modules",
      type: "select",
      data: carouselModules.value,
      required: true,
    },
    {
      type: "input",
      prop: "title",
      label: "标题",
      itemWidth: 100,
      maxlength: 10,
      itemType: "text",
    },
    {
      type: "input",
      prop: "subTitle",
      label: "副标题",
      maxlength: 30,
    },
    {
      type: "slot",
      slotName: "carouselUrl",
      prop: "carouselUrl",
      label: "轮播图",
    },
    {
      label: "跳转方式",
      prop: "targetType",
      type: "select",
      data: targetType.value,
    },
    {
      type: "input",
      prop: "url",
      label: "外链URL",
      maxlength: 100,
      isShow: formData.data.targetType == 2,
    },
    {
      type: "slot",
      slotName: "menuId",
      prop: "menuId",
      label: "菜单",
      required: true,
    },
    {
      label: "跳转文章",
      prop: "articleId",
      type: "select",
      data: articleList.value,
      filterable: true,
      isShow: formData.data.targetType == 1,
    },
    {
      label: "启用状态",
      prop: "status",
      type: "select",
      data: enableStatus.value,
      required: true,
    },
    {
      type: "input",
      itemType: "number",
      prop: "sort",
      label: "排序",
      style: {
        width: "50%",
      },
    },
  ];
});
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
    proxy.post("/carouselManager/page", sourceList.value.pagination).then((message) => {
    console.log(message);
    sourceList.value.data = message.rows;
    sourceList.value.pagination.total = message.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
const openModal = () => {
  dialogVisible.value = true;
  modalType.value = "add";
  formData.data = {};
};
const submitForm = () => {
  byform.value.handleSubmit((valid) => {
    submitLoading.value = true;
    proxy.post("/carouselManager/" + modalType.value, formData.data)
      .then((res) => {
        ElMessage({
          message: modalType.value == "add" ? "添加成功" : "编辑成功",
          type: "success",
        });
        dialogVisible.value = false;
        submitLoading.value = false;
        getList();
      })
      .catch((err) => {
        submitLoading.value = false;
      });
  });
};

const changeStatus = (row) => {
  modalType.value = "edit";
  let status = row.status=='1' ? 0 : 1;
  proxy.post("/carouselManager/detail", { id: row.id }).then((res) => {
    res.status = status;
    formData.data = res;
    ElMessageBox.confirm("你是否确认此操作?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      // 更新状态
      proxy.post("/carouselManager/" + modalType.value, formData.data).then((res) => {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        getList();
      });
    });
  });
};

//编辑详情
const getDetail = (row) => {
  modalType.value = "edit";
  proxy.post("/carouselManager/detail", { id: row.id }).then((res) => {
    formData.data = res;
    getFileList({businessIdList: [res.id], fileType: 1}).then((resFile) => {
      formData.data.carouselUrlList = resFile.data[res.id];
      formData.data.carouselUrl = resFile.data[res.id];
      dialogVisible.value = true;
    });
  });
};

//删除
const del = (row) => {
  modalType.value = "edit";
  ElMessageBox.confirm("你是否确认此操作?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    proxy.post("/carouselManager/delete", { id: row.id }).then((res) => {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        getList();
      });
  });
};
//获取字典
const getDictlist = async () => {
  const res = await getDictOneByXmhjc(["enable_status", "carousel_modules", "carousel_target_type"]);
  enableStatus.value = res["enable_status"].map((x) => ({
    label: x.dictValue,
    value: x.dictKey,
  }));
  carouselModules.value = res["carousel_modules"].map((x) => ({
    label: x.dictValue,
    value: x.dictKey,
  }));
  targetType.value = res["carousel_target_type"].map((x) => ({
    label: x.dictValue,
    value: x.dictKey,
  }));
};


//获取文章列表
const getArticleListSelect = async (value) => {
  formData.data.articleId = ""
  await getArticleList(value)

};

//获取文章列表
const getArticleList = async (value) => {
  const res = await findColumnArticleList({
    pageNum: 1,
    pageSize: 99999,
    status: 1,
    columnId: value,
  });
  articleList.value = res.data.rows.map((x) => ({
    label: x.title,
    value: x.id,
  }));
};


//图片上传相关
const carouselUrlOne = ref({});
const uploadCarouselUrl = async (file) => {
  const res = await getFileStr({ fileName: file.name });
  carouselUrlOne.value = res.data.uploadBody;
  file.id = res.data.id;
  file.fileName = res.data.fileName;
  file.fileUrl = res.data.fileUrl;
  return true;
};

const carouselUrlSuccess = (response, uploadFile) => {
  formData.data.carouselUrlList = [
    {
      id: uploadFile.raw.id,
      fileName: uploadFile.raw.fileName,
      fileUrl: uploadFile.raw.fileUrl,
    },
  ];
  formData.data.carouselUrl = uploadFile.raw.fileUrl;
};

const getMenuList = async () => {
  const res = await findMenuListByOpen({})
  columnListData.value = res.data
};

getMenuList()
getList();
getDictlist();
</script>

<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
.el-icon.uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 110px;
  height: 110px;
  text-align: center;
  border: 1px dashed var(--el-border-color);
}
</style>
