<template>
  <div class="tenant">
    <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        highlight-current-row
        :selectConfig="selectConfig"
        :table-events="{
        select: select,
      }"
        :action-list="[
        {
          text: '添加栏目文章',
          action: () => openModal('add'),
        },
      ]"
        @get-list="getList">

    </byTable>
    <el-dialog z-index="100" :title="modalType == 'add' ? '添加栏目文章' : '编辑栏目文章'" v-if="dialogVisible" v-model="dialogVisible" width="600" v-loading="loading">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="byform">
        <template #coverList>
          <el-row style="width: 100%">
            <el-col :span="6">
              <el-form-item  prop="coverList">
                <el-upload
                    class="avatar-uploader"
                    action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
                    :data="uploadDataOne"
                    :show-file-list="false"
                    accept=".gif, .jpeg, .jpg, .png"
                    :on-success="coverListSuccess"
                    :before-upload="uploadFileOne">
                  <el-image
                      v-if="formData.data.coverList && formData.data.coverList.length > 0"
                      :src="formData.data.coverList[0].fileUrl"
                      fit="scale-down"
                      class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
                <el-button
                    class="delete-btn"
                    type="danger"
                    v-if="formData.data.coverList && formData.data.coverList.length > 0"
                    @click="formData.data.coverList = []">
                  删除
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </template>

        <template #videoList>
          <el-row style="width: 100%">
            <el-col :span="6">
              <el-form-item  prop="videoList">
                <el-upload
                    class="avatar-uploader"
                    action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
                    :data="uploadDataTwo"
                    :show-file-list="false"
                    accept="video/*"
                    :on-success="videoListSuccess"
                    :before-upload="uploadFileTwo">


                  <video
                      v-if="formData.data.videoList && formData.data.videoList.length > 0"
                      :src="formData.data.videoList[0].fileUrl"
                      style="width: 300px; height: 300px"
                      controls></video>
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
                <el-button
                    class="delete-btn"
                    type="danger"
                    v-if="formData.data.videoList && formData.data.videoList.length > 0"
                    @click="formData.data.videoList = []">
                  删除
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </template>



        <template #detailsContent>
          <div style="width: 100%" v-if="dialogVisible">
            <TinymceEditor
                :value="formData.data.content"
                @updateValue="updateHandover"
                ref="contentEditor"
            />
          </div>
        </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>
import { ElMessage, ElMessageBox } from "element-plus";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import {computed, nextTick, reactive, ref} from "vue";
import TinymceEditor from "@/components/Editor/TinymceEditor.vue";
import {getDictOneByXmhjc, getFileList,getFileStr} from "@/api/XMHJC/common";
import {addColumnArticle, editColumnArticle, findColumnArticleList, getColumnArticle} from "@/api/XMHJC/column";
import {deleteAboutUsCulture} from "@/api/XMHJC/aboutUs";

const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
  },
});
let dialogVisible = ref(false);
let modalType = ref("add");

let rules = ref({
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  subTitle: [{ required: true, message: "请输入副标题", trigger: "blur" }],
  briefly: [{ required: true, message: "请输入简述", trigger: "blur" }],
  bodyType: [{ required: true, message: "请输入列表类型", trigger: "change" }],
  videoUrl: [{ required: true, message: "请输入第三方链接", trigger: "blur" }],
  sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
  status: [{ required: true, message: "请选择启用状态", trigger: "change" }],
});
const { proxy } = getCurrentInstance();
const bodyListType = ref([]);
const enableStatus = ref([]);
const selectConfig = [];
const config = computed(() => {
  return [
    {
      attrs: {
        label: "标题",
        prop: "title",
      },
    },
    {
      attrs: {
        label: "副标题",
        prop: "subTitle",
      },
    },
    {
      attrs: {
        label: "列表类型",
        prop: "bodyType",
        width: '90'
      },
      render(type) {
        return proxy.dictValueLabel(type, bodyListType.value);
      },
    },
    {
      attrs: {
        label: "状态",
        prop: "status",
        width: '80'
      },
      render(type) {
        return proxy.dictValueLabel(type, enableStatus.value);
      },

    },

    {
      attrs: {
        label: "排序",
        prop: "sort",
        width: '80'
      },
    },

    {
      attrs: {
        label: "发表时间",
        prop: "time",
        width: '160'
      },
    },
    {
      attrs: {
        label: "操作",
        width: "120",
        align: "right",
      },
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "修改",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              getDtl(row);
            },
          },
          {
            attrs: {
              label: "删除",
              type: "danger",
              text: true,
            },
            el: "button",
            click() {
              ElMessageBox.confirm("此操作将永久删除该数据, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }).then(() => {
                deleteAboutUsCulture({
                  id: row.id,
                })
                    .then((res) => {
                      ElMessage({
                        message: "删除成功",
                        type: "success",
                      });
                      getList();
                    });
              });
            },
          },
        ];
      },
    },
  ];
});
let formData = reactive({
  data: {
    coverList:[],
    videoList:[],
  },
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);
const formConfig = computed(() => {
  return [
    {
      type: "input",
      prop: "title",
      label: "标题",
      required: true,
    },
    {
      type: "input",
      prop: "subTitle",
      label: "副标题",
      required: true,
    },
    {
      type: "input",
      prop: "briefly",
      label: "简述",
      itemType: "textarea",
      required: true,
    },
    {
      type: "slot",
      slotName: "coverList",
      prop: "coverList",
      label: "封面",
      required: true,
    },
    {
      type: "select",
      prop: "bodyType",
      label: "正文类型",
      data: bodyListType.value,
      required: true,
    },
    {
      type: "slot",
      slotName: "detailsContent",
      prop: "detailsContent",
      label: "详情内容",
      isShow: formData.data.bodyType == "1"
    },
    // {
    //   type: "input",
    //   prop: "videoUrl",
    //   label: "视频链接",
    //   required: true,
    //   isShow: formData.data.bodyType == "2"
    // },

    {
      type: "slot",
      slotName: "videoList",
      prop: "videoList",
      label: "视频",
      required: true,
      isShow: formData.data.bodyType == "2"
    },
    {
      label: "启用状态",
      prop: "status",
      type: "select",
      data: enableStatus.value,
      required: true,
    },
    {
      type: "input",
      prop: "sort",
      label: "排序",
      itemType: "number",
      precision: 0,
      max: 999,
      required: true,
    },
  ];
});

const getDictlist = async () => {

  const res = await getDictOneByXmhjc(["enable_status","column_body_type"]);
  enableStatus.value = res["enable_status"].map((x) => ({
    label: x.dictValue,
    value: x.dictKey,
  }));
  bodyListType.value = res["column_body_type"].map((x) => ({
    label: x.dictValue,
    value: x.dictKey,
  }));
};

const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;

  const res = await findColumnArticleList(sourceList.value.pagination);
  sourceList.value.data = res.data.rows;
  sourceList.value.pagination.total = res.data.total;
  setTimeout(() => {
    loading.value = false;
  }, 200);

};

const openModal = () => {
  dialogVisible.value = true;
  modalType.value = "add";
  formData.data = {
    content:'',
  };

};
const selection = ref({
  data: [],
});
const select = (_selection, row) => {
  selection.value.data = _selection;
};
const submitForm = () => {
  byform.value.handleSubmit(() => {


    if (!formData.data.coverList ) {
      ElMessage({message: "请上传封面",type: "error",});
      return
    }



    if (formData.data.bodyType == '2' &&  !formData.data.videoList) {
      ElMessage({message: "请上传视频",type: "error",});
      return
    }

    if (formData.data.bodyType == '1' &&
        !formData.data.content) {
      ElMessage({message: "请填写详情内容",type: "error",});
      return
    }

    submitLoading.value = true;
    if (modalType.value === 'add'){
      addColumnArticle(formData.data).then(response => {
        ElMessage({
          message: "添加成功",
          type: "success",
        });
        dialogVisible.value = false;
        submitLoading.value = false;
        getList();
      }).catch(()=>{
        submitLoading.value = false;
      });
    }else {
      editColumnArticle(formData.data).then(response => {
        ElMessage({
          message: "编辑成功",
          type: "success",
        });
        dialogVisible.value = false;
        submitLoading.value = false;
        getList();
      }).catch(()=>{
        submitLoading.value = false;
      });


    }
  });
};

const getDtl = async (row) => {
  modalType.value = "edit";
  const response = await getColumnArticle({ id: row.id })
  formData.data = response.data;

  const resFile = await getFileList({businessIdList: [response.data.id], fileType: 1})
  formData.data.coverList = resFile.data[response.data.id];
  const resFile1 = await getFileList({businessIdList: [response.data.id], fileType: 2})
  formData.data.videoList = resFile1.data[response.data.id];

  dialogVisible.value = true;
};


const updateHandover = (val) => {
  formData.data.content = val;
};


const uploadDataOne = ref({});
const uploadFileOne = async (file) => {
  const res = await getFileStr({ fileName: file.name });
  uploadDataOne.value = res.data.uploadBody;
  file.id = res.data.id;
  file.fileName = res.data.fileName;
  file.fileUrl = res.data.fileUrl;
  return true;
};
const uploadDataTwo = ref({});
const uploadFileTwo = async (file) => {
  const res = await getFileStr({ fileName: file.name });
  uploadDataTwo.value = res.data.uploadBody;
  file.id = res.data.id;
  file.fileName = res.data.fileName;
  file.fileUrl = res.data.fileUrl;
  return true;
};

const coverListSuccess = (response, uploadFile) => {
  formData.data.coverList = [
    {
      id: uploadFile.raw.id,
      fileName: uploadFile.raw.fileName,
      fileUrl: uploadFile.raw.fileUrl,
    },
  ];
};
const videoListSuccess = (response, uploadFile) => {
  formData.data.videoList = [
    {
      id: uploadFile.raw.id,
      fileName: uploadFile.raw.fileName,
      fileUrl: uploadFile.raw.fileUrl,
    },
  ];
};



getDictlist()
getList()

</script>

<style lang="scss" scoped>
.tenant {
  padding: 20px;
  .delete-btn{
    margin-top: 10px;
    margin-left: 25px;
  }
}
.avatar-uploader .avatar {
  width: 110px;
  height: 110px;
  display: block;
  background-color: black;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 110px;
  height: 110px;
  text-align: center;
  border: 1px dashed var(--el-border-color);
}
</style>
