
<script lang="ts">
export default {
  name: 'infomation' ,// 资讯管理
};
</script>
<script setup lang="ts">
import { onMounted, reactive, ref, nextTick,watch } from "vue";
import { ElMessage, ElMessageBox, FormRules } from "element-plus";
import Page from '@/components/Pagination/page.vue';
import { queryAppNewsPage,addAppNews,updateAppNews,delAppNews,updateAppNewsStatus } from '@/api/appmanage'
import { useDark } from '@vueuse/core'
import tinymce from 'tinymce/tinymce'
import 'tinymce/themes/silver'
import 'tinymce/models/dom/model'
import 'tinymce/icons/default/icons'
import "tinymce/themes/silver/theme.min.js";
import 'tinymce/plugins/image'// 插入上传图片插件
import 'tinymce/plugins/media'// 插入视频插件
import 'tinymce/plugins/table'// 插入表格插件
import 'tinymce/plugins/lists'// 列表插件
import 'tinymce/plugins/wordcount'// 字数统计插件
import 'tinymce/plugins/advlist'// 字数统计插件
import 'tinymce/plugins/autosave'// 字数统计插件
import { useUserStore } from '@/store/modules/user';
const userStore = useUserStore();
const url = userStore.webApiBaseUrl;
const produrl = ref('')
const initlist = ref( {
  selector: 'textarea',
  language_url: produrl.value + '/tinymce/langs/zh_CN.js', 
  language: 'zh_CN',
  skin_url: produrl.value +'/tinymce/skins/ui/oxide',
  content_css: produrl.value +'/tinymce/skins/content/default/content.css',
  height:450, // 编辑器高度
  body_class: 'panel-body',
  toolbar: 'fontfamily fontsize lineheight bold italic underline strikethrough forecolor | outdent indent alignleft aligncenter alignright alignjustify bullist numlist',
  menubar: false,
  plugins: 'advlist autosave lists table wordcount',
  end_container_on_empty_block: true,
  powerpaste_word_import: 'clean',
  code_dialog_height: 450,
  code_dialog_width: 1000,
  advlist_bullet_styles: 'square',
  advlist_number_styles: 'default',
  imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'],
  default_link_target: '_blank',
  link_title: false,
  font_size_formats: '12px 14px 16px 18px 20px 24px 28px 30px 36px 40px 48px',
  font_family_formats: '微软雅黑=微软雅黑;宋体=宋体;黑体=黑体;',
  nonbreaking_force_tab: true,
  convert_urls: false,
  branding: false,
  // images_upload_url: url + '/api/imageserver/upload',
  // images_upload_base_path: url
})
let isDark:any = useDark().value == true? '1' : '2'
watch(useDark(), () => {
  isDark = useDark().value == true? '1' : '2'
    if (useDark().value == true) {
      initlist.value.skin_url= produrl.value +'/tinymce/skins/ui/oxide-dark'
    } else {
      initlist.value.skin_url= produrl.value +'/tinymce/skins/ui/oxide'
    }
  })
const queryInfo :any = ref({
  current:1,
  size:10,
  total:0
})
//搜索内容
const title = ref('')
const tableData:any = ref([])
const multipleSelection = ref([])
const dialogVisible = ref(false)
const dialogVisibles = ref(false)
const dialogtitle = ref('新增资讯')
const forms:any = ref({})
const form = ref();
const rules = reactive<FormRules>({
  title: [{ required: true, message: "请输入资讯名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择资讯类型", trigger: "change" }]
});
const isSwitch = ref(false)
const typeoptions = ref([{label:'知识',value:'01'},{label:'新闻',value:'02'}])
const handleSelectionChange = (val:any) => {
  multipleSelection.value = val
}
const content = ref('')
const coverimg:any = ref({})
const fileList:any = ref([])
const loading = ref(false)
watch(dialogVisible,()=>{
  if(dialogVisible.value){
    nextTick(()=>{
      if (isDark === '1') {
        initlist.value.skin_url= produrl.value +'/tinymce/skins/ui/oxide-dark'
      } else {
        initlist.value.skin_url= produrl.value +'/tinymce/skins/ui/oxide'
      }
      tinymce.init(initlist.value)
      if(forms.value.content!==''){
        if(tinymce.activeEditor) {
          content.value = forms.value.content
          tinymce.activeEditor.setContent(forms.value.content)
    }
      }
  })
  }else{
    tinymce.remove()
  }
})
onMounted(() => {
  getData();
if(import.meta.env.VITE_USER_NODE_ENV !== 'development'){
  produrl.value = '/web'
  initlist.value.language_url = produrl.value + '/tinymce/langs/zh_CN.js'
  initlist.value.content_css = produrl.value +'/tinymce/skins/content/default/content.css'
}else{
  produrl.value = ''
  initlist.value.language_url = produrl.value + '/tinymce/langs/zh_CN.js'
  initlist.value.content_css = produrl.value +'/tinymce/skins/content/default/content.css'
}
});
// 搜索
function getData(){
  const params = {
    current: queryInfo.value.current,
    size:queryInfo.value.size,
    title:title.value
  }
  loading.value = true
  queryAppNewsPage(params).then((res:any) => {
    tableData.value = res.data.records
    queryInfo.value.total = res.data.total
    loading.value = false
  })
}
function delinfos() {
  ElMessageBox.confirm("确定删除此资讯吗?", "删除提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true
    let id = [] as any[];
    multipleSelection.value.forEach((item: any) => {
      id.push(item.id)
    })
    let params = {
      ids: id.join(','),
    };
    delAppNews(params).then(() => {
      getData();
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      loading.value = false
    });
  });
}
//修改
function editinfo(row:any){
  isSwitch.value = false
  dialogtitle.value = '修改资讯'
  forms.value = JSON.parse(JSON.stringify(row))
  if(row.news_files!==undefined && row.news_files!==''){
    forms.value.coverimg = url+'/appnews/'+ row.news_files
  }else{
    forms.value.coverimg = ''
    coverimg.value = {}
  }
  if(row.news_video!==undefined && row.news_video!==''){
    fileList.value = [{name:row.news_video}]
  }else{
    fileList.value = []
  }
  dialogVisible.value = true
}
//发布
function releaseClick(row:any,statustype:any){
  const status = statustype === '02'?'发布':'撤销'
  ElMessageBox.confirm('确定'+ status +'此资讯吗?', "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true
    const params = {
    id:row.id,
    newsStatus:statustype
  }
  updateAppNewsStatus(params).then(() => {
    getData();
    ElMessage({
      message: statustype === '02'?'发布成功':'撤销成功',
      type: "success",
    });
    loading.value = false
  })
  })
}
function switchchange(index:any,e:any){
  loading.value = true
  if(e === '1'){
    let num = 0
    for(let i = 0;i<tableData.value.length;i++){
      if(tableData.value[i].recommend === '1'){
        num = num + 1
      }
    }
    if (num <= 3) {
      switchsubmit( tableData.value[index].id,'1')
    } else {
      ElMessage({
        message: "推荐内容不能超过三条",
        type: "warning",
      });
      tableData.value[index].recommend = '0'
      loading.value = false
    }
  } else {
    switchsubmit( tableData.value[index].id,'0')
  }
}
function switchsubmit(id:any,status:any){
  const params = {
    id:id,
    recommend:status
  }
  updateAppNews(params).then((res:any) => {
    getData()
    // ElMessage({
    //   message: '推荐成功',
    //     type: "success",
    // });
    loading.value = false
  })
}
function addinfo(){
 content.value = ''
 forms.value={}
 fileList.value = []
 isSwitch.value = false
 dialogtitle.value = '新增资讯'
 dialogVisible.value = true
 if (form.value != null) form.value.resetFields();
}
//删除
function delinfo(row: any) {
  ElMessageBox.confirm("确定删除此资讯吗?", "删除提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true
    let params = {
      ids: row.id,
    };
    delAppNews(params).then(() => {
      getData();
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      loading.value = false
    });
  });
}
function handleClose(){
  if (form.value != null) form.value.resetFields();
  dialogVisible.value = false
}
function infosubmit(formEl: any){
    formEl.validate((valid: any) => {
    if (valid) {
     if(isSwitch.value == true){
        return
      }
      loading.value = true
      isSwitch.value = true
      if(forms.value.id) {
      const formData = new FormData();
      if(coverimg.value !== ''&& coverimg.value.raw !== undefined){
          formData.append("image",coverimg.value.raw)
        }
        if(fileList.value.length !== 0 && fileList.value[0].raw !== undefined){
          formData.append("multipartFile",fileList.value[0].raw)
          formData.append("newsVideo",'')
        }
        formData.append("newsVideo",forms.value.news_video)
        formData.append("newsFiles",forms.value.news_files)
        formData.append("id",forms.value.id)
        formData.append("newsStatus",forms.value.news_status)
        formData.append("title",forms.value.title)
        formData.append("type",forms.value.type)
        if(tinymce.activeEditor) {
          content.value = tinymce.activeEditor.getContent()
        }else{
          formData.append("content",'')
        }
        if(content.value !== ''){
          formData.append("content",content.value)
        }else{
          formData.append("content",'')
        }
        formData.append("recommend",forms.value.recommend)
        updateAppNews(formData).then((res:any) => {
          dialogVisible.value = false
          getData();
          ElMessage({
            message: "修改成功",
            type: "success",
          })
          isSwitch.value = false
          loading.value = false
        }).catch(()=>{
          isSwitch.value = false
          loading.value = false
        })
    } else {
      const formData = new FormData();
       if(coverimg.value !== '' && coverimg.value.raw !== undefined){
          formData.append("image",coverimg.value.raw)
        }
        if(fileList.value.length !== 0 && fileList.value[0].raw !== undefined){
          formData.append("multipartFile",fileList.value[0].raw)
        }
        formData.append("newsStatus",'01')
        formData.append("title",forms.value.title)
        formData.append("type",forms.value.type)
        if(tinymce.activeEditor) {
          content.value = tinymce.activeEditor.getContent()
        }
        if(content.value !== ''){
          formData.append("content",content.value)
        }
        formData.append("recommend",'0')
        addAppNews(formData).then((res:any) => {
          dialogVisible.value = false
          getData();
          ElMessage({
            message: "新增成功",
            type: "success",
          });
          isSwitch.value = false
          loading.value = false
        }).catch(()=>{
          isSwitch.value = false
          loading.value = false
        })
     }
    }
    })
}
function uploadChange(file:any){
  forms.value.coverimg = URL.createObjectURL(file.raw)
  coverimg.value = file
}
function delcoverimg(){
  coverimg.value = ''
  forms.value.coverimg = ''
  forms.value.news_files = ''
}
function handlefilechange(file:any){
  fileList.value = []
  fileList.value.push(file) 
}
function handlefileremove(){
  fileList.value = []
  forms.value.news_video = ''
}
function lookmovie(){
  dialogVisibles.value = true
}
function handleCloses(){
  dialogVisibles.value = false
}
function dateFormat(row: any) { // 时间方法
  const daterc = row;
  if (daterc != null) {
    var date = new Date(daterc);
    var year = date.getFullYear();
    var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
    date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    // 拼接
    return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
  }
}
</script>
<template>
    <div class="activitymanage-box">
      <div class="activitymanage-box-top">
          <div class="flex">
            <el-input v-model="title" placeholder="请输入资讯标题" style="width:240px" clearable />
            <el-button type="primary" class="ml-[10px]" @click="getData">搜索</el-button>
          </div>
          <div>
            <el-button type="primary" @click="addinfo"><img src="@/assets/visionscreening/jscz_xz.png" alt="" style="margin-right: 4px;" >新增</el-button>
          <el-button @click="delinfos" :disabled="multipleSelection.length <= 0" :type="multipleSelection.length > 0 ? 'primary' : ''">
            <el-icon style="margin-right: 4px;" :color="multipleSelection.length <= 0?'#a8abb2':'#fff'"><Delete /></el-icon> 删除</el-button>
          </div>
        </div>
        <div v-loading="loading" class="visionscreening-box-bottom">
          <el-table :data="tableData" border style="width: 100%; height:calc(100vh - 280px)" @selection-change="handleSelectionChange" :header-cell-style="{background:'rgb(250 250 250)',height:'50px'}">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="title" label="资讯标题" />
            <el-table-column prop="type" label="资讯类型" width="100">
            <template #default="scope">
              <span v-if="scope.row.type === '01'">知识</span>
              <span v-else-if="scope.row.type === '02'">新闻</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <span v-if="scope.row.news_status === '01'" style="color: #4099ff;">初始创建</span>
              <span v-else-if="scope.row.news_status === '02'" style="color: #009966;">已发布</span>
              <span v-else-if="scope.row.news_status === '03'" style="color: #FF9900;">撤销</span>
            </template>
          </el-table-column>
            <el-table-column prop="recommend" label="是否推荐" width="120">
                <template #default="scope">
                    <el-switch v-model="scope.row.recommend" active-value="1" inactive-value="0" :active-text="scope.row.recommend === '1'?'推荐':'普通'" @change="switchchange(scope.$index,$event)"/>
                </template>
            </el-table-column>
            <el-table-column prop="create_user" label="上传人" width="200" />
            <el-table-column prop="create_time" label="登录时间" width="200">
              <template #default="scope">
              {{ dateFormat(scope.row.create_time) }}
            </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right" align="center">
              <template #default="scope">
                <div style="display: -webkit-flex;display: flex; justify-content: space-around;-webkit-justify-content: space-around; ">
                  <img v-if="scope.row.news_status =='01' || scope.row.news_status =='03'" src="@/assets/appmanage/release.png" alt="" title="发布" @click="releaseClick(scope.row,'02')" style="cursor: pointer;">
                  <img v-if="scope.row.news_status =='02'" src="@/assets/appmanage/return.png" alt="" title="撤销" @click="releaseClick(scope.row,'03')" style="cursor: pointer;">
                  <img src="@/assets/MenuIcon/lbcz_xg.png" alt="" title="修改" @click="editinfo(scope.row)" style="cursor: pointer;">
                  <img src="@/assets/MenuIcon/lbcz_sc.png" alt="" title="删除" @click="delinfo(scope.row)" style="cursor: pointer;">
                </div>
              </template>
            </el-table-column>
          </el-table>
          <Page class="mt-[20px]" :total="queryInfo.total" v-model:size="queryInfo.size" v-model:current="queryInfo.current"
          @pagination="getData" />
        </div>
    </div>
    <el-dialog v-model="dialogVisible" :close-on-click-modal="false" :title="dialogtitle" :before-close="handleClose" width="50%" draggable append-to-body>
        <el-form ref="form" :model="forms" :rules="rules" label-width="90px">
          <div class="flex" >
            <div style="width:calc(100% - 100px);margin-right:10px ;">
              <el-form-item label="资讯名称" prop="title" style="width: 100%">
                <el-input v-model="forms.title" autocomplete="off"  placeholder="请输入咨询名称" />
              </el-form-item>
              <el-form-item label="上传视频" style="width: 100%;display: flex;">
                <el-upload  accept=".mp4" ref="upload" class="upload-demo" action="" :on-change="handlefilechange" :on-remove="handlefileremove" :auto-upload="false" :file-list="fileList" style="width: calc(100% - 70px);position:relative">
                  <template #trigger>
                    <el-button type="primary">点击上传</el-button>
                  </template>
                </el-upload>
                <div v-if="forms.news_video" class="videostyle" @click.stop="lookmovie">查看视频</div>
              </el-form-item>
            </div>
            <div style="width:100px;">
              <el-upload class="avatar-uploader" accept=".png, .jpg, .jpeg" action="" :show-file-list="false" :auto-upload="false" @change="uploadChange" >
                <div style="width: 100px;height: 100px;position: relative;" v-if="forms.coverimg">
                  <img :src="forms.coverimg" class="avatar" />
                <div style="position: absolute;top: 0px;left: 0px;z-index: 1;width: 100px;height: 100px;background: rgba(0,0,0,0.3);color: cornflowerblue;">
                    <el-icon style="position: absolute;top: 40px;left: 40px;z-index: 1;font-size: 20px;"
                    @click.stop="delcoverimg"><Delete /></el-icon>
                </div>
                </div>
            <div v-else style="text-align: center;">
              <el-icon class="newavatar-uploader-icon"><Plus /></el-icon>
              <div class="newavatar-uploader-text">上传封面</div>
            </div>
            </el-upload>
            </div>
          </div>
            <el-form-item label="资讯类型" prop="type" style="width: 100%">
              <el-select v-model="forms.type" placeholder="请选择活动类型" >
               <el-option v-for="item in typeoptions" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
            <el-form-item label="资讯内容">
              <textarea v-model="content" :init="initlist" style="width: 100%;background: transparent;"></textarea>
            </el-form-item>
        </el-form>
       
        <span class="dialog-footer">
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="infosubmit(form)">确定</el-button>
        </span>
      </el-dialog>
      <el-dialog v-model="dialogVisibles" :close-on-click-modal="false" title="查看视频" :before-close="handleCloses" width="60%" draggable append-to-body>
        <video ref="videoRef" :src="url + '/app/app-news/viewAppNewsFile?fileName='+ forms.news_video" style="width:100%" height="400" autoplay controls></video>
        <span class="dialog-footer mt-[20px]">
            <el-button type="primary" @click="handleCloses">关闭</el-button>
        </span>
      </el-dialog>
</template>
<style scoped  lang="scss">
.activitymanage-box {
  height: calc(100vh - 130px);
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0px 0px 10px rgba(219, 225, 236, 1);
  padding: 20px;
  .activitymanage-box-top{
    width:100%;
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
  }
}
.dialog-footer {
  display: flex;
  display: -webkit-flex;
  justify-content: flex-end;
  -webkit-justify-content: flex-end;
}
:deep(.el-tree-node__content){
  height: 30px;
}
:deep(.el-input__inner){
  height: 32px;
  font-size:14px;
}
// :deep(.el-upload-list){
// display: none;
// }
.lefttitle {
  min-width: 150px;
  display: flex;
  align-items: center;
  padding: 10px 15px;
  font-family: 'Arial Negreta', 'Arial Normal', 'Arial';
  font-weight: 700;
  font-style: normal;
  font-size: 16px;
  color: #1B1B1B;
  background: rgba(246, 247, 250, 1);
  border-bottom: 1px var(--el-border-color) var(--el-border-style);
  margin-bottom: 10px;
  .line{
    border-width: 0px;
    width: 5px;
    height: 14px;
    margin-right: 7px;
    background: inherit;
    background-color: rgba(64, 158, 255, 1);
    border: none;
    border-radius: 0px;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
  }
}
.leftbox{
  width: 250px;
  height: calc(100vh - 200px);
  border: 1px solid #e1e1e1;
  border-radius: 4px;
}
.tox .tox-tbtn--bespoke+.tox-tbtn--bespoke{
  width:100% !important;
}
.videostyle{
  padding-top: 5px;
  background: url('../../assets/appmanage/movie.png') no-repeat;
  background-position: 0px 13px;
  padding-left: 18px;
  position: absolute;
  right: 0px;
  bottom: 6px;
}
.videostyle:hover{
  color: #4099ff;
  cursor: pointer;
}
</style>
