<script setup>
import { ref, onMounted } from 'vue';
import request from "@/utils/request.js";
import {
  ElTable,
  ElTableColumn,
  ElPagination,
  ElInput,
  ElButton,
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElMessageBox,
  ElMessage,
  ElDialog,
  ElDatePicker
} from 'element-plus';
import { newsMap } from "./newsMap.js";
import MyEdit from "@/views/xyjsxx/zwxxfb/components/MyEdit.vue";
import {Plus} from "@element-plus/icons-vue";

const tableData = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const searchTitle = ref('');
const searchSpecialColumn = ref('');
const multipleSelection = ref([]);
const specialColumns = ref([]);
const dialogVisible = ref(false);
const myEdit = ref(null);
const imageUrl = ref({id: '',imagesUrl:''});
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const minioUrl = import.meta.env.VITE_MINIO_BASE_API;
const form = ref({
  title: '',
  specialColumn: '',
  date: '',
  content: '',
  dataSource: '',
  introduce: ''
});
const previewDialogVisible = ref(false);
const previewContent = ref('');

const getList = async () => {
  const conditionJson = [
    {
      column: 'create_time',
      type: 'orderByDesc'
    }
  ];
  if (searchTitle.value) {
    conditionJson.push({
      column: 'title',
      value: searchTitle.value,
      type: 'like'
    });
  }
  if (searchSpecialColumn.value) {
    conditionJson.push({
      column: 'special_column',
      value: searchSpecialColumn.value,
      type: 'eq'
    });
  }
  const res = await request.get('/xcrNewsRelease/findByPage', {
    params: {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      conditionJson: encodeURIComponent(JSON.stringify(conditionJson))
    }
  });
  tableData.value = res.records;
  total.value = res.total;
};

const handleSizeChange = (newPageSize) => {
  pageSize.value = newPageSize;
  getList();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  getList();
};

const handleSearch = () => {
  currentPage.value = 1; // 重置页码为第一页
  getList();
};

const handleReset = () => {
  searchTitle.value = '';
  searchSpecialColumn.value = '';
  currentPage.value = 1; // 重置页码为第一页
  getList();
};

const handleSubmit = (event) => {
  event.preventDefault();
  handleSearch();
};

const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该记录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await request.post('/xcrNewsRelease/delete', [id]);
    ElMessage.success('删除成功');
    getList();
  } catch (error) {
    ElMessage.error('删除失败');
  }
};

const handleBatchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的记录');
    return;
  }
  try {
    await ElMessageBox.confirm('确定要删除选中的记录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const ids = multipleSelection.value.map(item => item.id.toString());
    await request.post('/xcrNewsRelease/delete', ids);
    ElMessage.success('删除成功');
    getList();
  } catch (error) {
    ElMessage.error('删除失败');
  }
};

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const handleAdd = () => {
  form.value = {
    title: '',
    specialColumn: '',
    date: '',
    content: '',
    dataSource: '',
    introduce: ''
  };
  imageUrl.value.imagesUrl = '';
  imageUrl.value.id = '';
  nextTick(()=>{
    myEdit.value.setContent('');
  })
  dialogVisible.value = true;
};

const handleAddSubmit = async () => {
  try {
    form.value.content = myEdit.value.getContent();
    form.value.files = [{id:imageUrl.value.id}];
    if (form.value.id) {
      // 修改
      await request.post('/xcrNewsRelease/updateById', form.value);
      ElMessage.success('修改成功');
    } else {
      // 新增
      await request.post('/xcrNewsRelease/save', form.value);
      ElMessage.success('新增成功');
    }
    dialogVisible.value = false;
    getList();
  } catch (error) {
    ElMessage.error('操作失败');
  }
};

const handleAddCancel = () => {
  console.log(form.value);
  ElMessageBox.confirm('确定退出编辑页面吗？')
      .then(() => {
        dialogVisible.value = false;
      });
};

const handlePreview = (content) => {
  previewContent.value = content;
  previewDialogVisible.value = true;
};

const handleModify = async (id) => {
  try {
    const res = await request.get(`/xcrNewsRelease/getById/${id}`);
    form.value = res.data;
    // console.log(res.data);
    if(res.data.files.length>0){
      imageUrl.value.imagesUrl = minioUrl+res.data.files[0].fileUrl;
      imageUrl.value.id = res.data.files[0].id;
    }else {
      imageUrl.value.imagesUrl = '';
      imageUrl.value.id = '';
    }
    nextTick(()=>{
      myEdit.value.setContent(res.data.content);
    })
    dialogVisible.value = true;
  } catch (error) {
    ElMessage.error('获取数据失败');
  }
};

const handleSuccess = (res)=>{
  imageUrl.value.imagesUrl = minioUrl+res.data.fileUrl;
  imageUrl.value.id = res.data.id;
}


onMounted(() => {
  newsMap.forEach((k, v) => {
    specialColumns.value.push({ value: v, label: k });
  });
  getList();
});
</script>

<template>
  <div class="p-20px">
    <el-form @submit="handleSubmit" inline>
      <el-form-item label="请输入标题">
        <el-input
            v-model="searchTitle"
            placeholder="请输入标题进行筛选"
            style="width: 300px;"
            @keyup.enter="handleSubmit"
        />
      </el-form-item>
      <el-form-item label="选择专栏">
        <el-select v-model="searchSpecialColumn" placeholder="请选择专栏" style="width: 200px;">
          <el-option
              v-for="item in specialColumns"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
        <el-button type="success" @click="handleAdd">新增</el-button>
      </el-form-item>
    </el-form>
    <el-table
        :data="tableData"
        style="width: 100%"
        max-height="80vh"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"/>
      <el-table-column prop="title" label="标题" width="180" :show-overflow-tooltip="true"/>
      <el-table-column prop="specialColumn" label="专栏" width="180" :show-overflow-tooltip="true">
        <template #default="{ row }">
          {{ newsMap.get(row.specialColumn) }}
        </template>
      </el-table-column>
      <el-table-column prop="date" label="发布时间" width="180" :show-overflow-tooltip="true"/>
      <el-table-column prop="content" label="内容" :show-overflow-tooltip="true"/>
      <el-table-column prop="dataSource" label="数据来源" :show-overflow-tooltip="true"/>
      <el-table-column prop="introduce" label="介绍" :show-overflow-tooltip="true"/>
      <el-table-column prop="createBy" label="创建者" width="180" :show-overflow-tooltip="true"/>
      <el-table-column prop="createTime" label="创建时间" width="180" :show-overflow-tooltip="true"/>
      <el-table-column prop="updateBy" label="更新者" width="180" :show-overflow-tooltip="true"/>
      <el-table-column prop="updateTime" label="更新时间" width="180" :show-overflow-tooltip="true"/>
      <el-table-column label="预览">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handlePreview(row.content)">预览</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button type="danger" size="small" @click="handleDelete(row.id)">删除</el-button>
          <el-button type="warning" size="small" @click="handleModify(row.id)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 30, 50]"
    />
    <el-dialog
        :title="form.value?.id ? '修改记录' : '新增记录'"
        v-model="dialogVisible"
        width="50%"
        :before-close="handleAddCancel"
        destroy-on-close
    >
      <el-form :model="form" label-width="120px">
        <el-form-item label="标题">
          <el-input v-model="form.title" placeholder="请输入标题"/>
        </el-form-item>
        <el-form-item label="专栏">
          <el-select v-model="form.specialColumn" placeholder="请选择专栏">
            <el-option
                v-for="item in specialColumns"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="内容">
          <el-input v-model="form.content" type="textarea" v-show="false" placeholder="请输入内容"/>
          <MyEdit ref="myEdit" />
        </el-form-item>
        <el-form-item label="介绍">
          <el-input v-model="form.introduce" type="textarea" placeholder="请输入介绍"/>
        </el-form-item>
        <el-form-item label="封面">
          <el-upload
              class="avatar-uploader"
              :action="imageUrl.id?baseUrl+'/xcrFile/updateById':baseUrl+'/xcrFile/save'"
              :on-success="handleSuccess"
              :show-file-list="false"
              :limit="100"
              :data="{id:imageUrl.id,moduleName:'封面图'}"
          >
            <img alt="封面" v-if="imageUrl" :src="imageUrl.imagesUrl" class="w-100px h-a" />
            <el-icon v-else class="w-100px h-a "><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="数据来源">
          <el-input v-model="form.dataSource" placeholder="请输入数据来源"/>
        </el-form-item>
        <el-form-item label="发布时间">
          <el-date-picker
              v-model="form.date"
              type="datetime"
              placeholder="选择日期时间"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleAddCancel">取消</el-button>
          <el-button type="primary" @click="handleAddSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
        title="内容预览"
        v-model="previewDialogVisible"
        width="60%"
        :before-close="() => previewDialogVisible = false"
        destroy-on-close
    >
      <pre v-html="previewContent"></pre>
    </el-dialog>
  </div>
</template>