<script setup>
import {ref,reactive,computed,onUpdated,nextTick} from "vue"
import { ElMessage,ElMessageBox } from 'element-plus'
import $ from 'jquery'
import vueQr from "vue-qr/src/packages/vue-qr.vue";

import {formatter} from '@/hooks/mixins/index.js'
import { morningPaper } from "@/api/api.js";

//弹框的添加
const rule=reactive({
  ruleForm: {
    addBreed: "",
    addTetle: "",
    addEditor: "",
    addTime: "",
    ArticleId: null,
  }
})
const list=reactive({
  PageSize: 6, //每页条数
  CurrentIndex: 1, //当前页码值
  KeyWord: "", //关键字搜索
  Status: "", //发布状态 1已发布 0未发布
  ChartPermissionIds: "", //分类ID
})

const listData=ref([]) //表格数据
const varietyList=ref([]) //全部分类
const totals=ref(0) //条数
const options=[
  {
    value: "0",
    label: "未发布",
  },
  {
    value: "1",
    label: "已发布",
  },
] //发布的状态
const dialogVisible=ref(false) //添加弹框
const dialogVisibleEdit=ref(false) //编辑弹框
const froalaConfig={
  toolbarButtons: [
    "insertImage",
    "embedly",
    "textColor",
    "bold",
    "italic",
  ],
  height: 350,
  fontSizeDefaultSelection: "16",
  theme: "dark", //主题
  placeholderText: "请输入内容",
  language: "zh_cn", //国际化
  imageUploadURL: import.meta.env.VITE_APP_API_ROOT + "/report/uploadImg", //上传url
  videoUploadURL: import.meta.env.VITE_APP_API_ROOT + "/report/uploadImg", //上传url
  fileUploadURL: import.meta.env.VITE_APP_API_ROOT + "/report/uploadImg", //上传url 更多上传介绍 请访问https://www.froala.com/wysiwyg-editor/docs/options
  imageDefaultWidth: false,
  // imageEditButtons:['imageAlign', 'imageCaption', 'imageRemove', '|', 'imageLink', 'linkOpen', 'linkEdit', 'linkRemove', '-', 'imageDisplay', 'imageStyle', 'imageAlt', 'imageSize'],
  quickInsertButtons: ["image", "table", "ul", "ol", "hr"], //快速插入项
  toolbarVisibleWithoutSelection: true, //是否开启 不选中模式
  // disableRightClick:true,//是否屏蔽右击
  // colorsHEXInput:false,//关闭16进制色值
  toolbarSticky: false, //操作栏是否自动吸顶
  // zIndex:99999,
  saveInterval: 0,
  charCounterCount: false,
  reportloadding: false,
  lastsavetime: "",
  isAddEnter: false, //是否已经添加过
  timer: null,
  ischange: false,
  isPublishloading: false,
} //富文本
const linkUrl=ref("") //二维码的链接
const rules=ref({
  addBreed: [
    { required: true, message: "请选择品种", trigger: "change" },
  ],
  addTetle: [{ required: true, message: "请输入标题", trigger: "blur" }],
  addEditor: [
    { required: true, message: "请输入正文内容", trigger: "blur" },
  ],
  addTime: [
    {
      type: "string",
      required: false,
      message: "请选择日期",
      trigger: "change",
    },
  ],
}) //校验规则
const pickerOptions=ref({
  disabledDate(time) {
    return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
  },
}) //初始化时间
const editList=ref({})
const editTitle=ref(false)
const pvUvList=ref([]) //pvUv
const primaryBtn=ref(true)
const pageshow=ref(true)

const getTimer=computed(()=>{
  let date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  month = month < 10 ? "0" + month : month;
  let datee = date.getDate();
  datee = datee < 10 ? "0" + datee : datee;
  let day = date.getDay();
  let time = year + "-" + month + "-" + datee;
  function getTimerr() {
    let time = new Date();
    let hour = time.getHours();
    hour = hour < 10 ? "0" + hour : hour;
    let minute = time.getMinutes();
    minute = minute < 10 ? "0" + minute : minute;
    let second = time.getSeconds();
    second = second < 10 ? "0" + second : second;
    return hour + ":" + minute + ":" + second;
  }
  return time + " " + getTimerr();
})

//获取文章列表
const getList=()=>{
  morningPaper
    .getList(list)
    .then((res) => {
      if (!res.Success) return ElMessage.error(res.Msg);
      listData.value = res.Data.List;
      totals.value = res.Data.Paging.Totals || 0;
    })
    .catch((err) => {});
}
//获取个人分类
const getmyfllow=()=>{
  morningPaper.getmyfllow().then((res) => {
    if (!res.Success) return ElMessage.error(res.Msg);
    varietyList.value = res.Data.List;
  });
}
//客户检索按钮事件
const searching=()=>{
  getList();
}
//删除的事件
const removeItem=(item)=>{
  ElMessageBox.confirm("此操作将永久删除该文章, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
  .then(() => {
    morningPaper
      .articleDelete({
        ArticleId: item.ArticleId,
      })
      .then((res) => {
        if (!res.Success) return ElMessage.error(res.Msg);
        ElMessage.success("删除成功!");
        getList();
      });
  })
  .catch(() => {
    ElMessage({
      type: "info",
      message: "已取消删除",
    });
  });
}
//取消发布
const unpublish=(item)=>{
  ElMessageBox.confirm("此操作将取消发布此文章, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      morningPaper
        .articleUnpublish({ ArticleId: item.ArticleId })
        .then((res) => {
          if (!res.Success) return ElMessage.error(res.Msg);
          ElMessage.success("取消发布成功!");
          getList();
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
}
//发布文章的事件
const issueArticle=(item)=>{
  ElMessageBox.confirm("此操作将发布此文章, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      item.TimingPublishTime = "";
      morningPaper.articleFirstadd(item).then((res) => {
        if (!res.Success) return ElMessage.error(res.Msg);
        ElMessage.success("发布成功！");
        getList();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
}
//发布状态的事件和选择品种
const optionsChange=()=>{
  list.CurrentIndex = 1;
  getList();
}
//分页
const handleCurrentChange=(val)=>{
  list.CurrentIndex = val;
  getList();
  pageshow.value = false; //让分页隐藏
  nextTick(() => {
    //重新渲染分页
    pageshow.value = true;
  });
}

const ruleFormRef=ref(null)

//添加的确定事件
const submitForm=()=>{
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      morningPaper
        .articleFirstadd({
          Title: rule.ruleForm.addTetle,
          Body: rule.ruleForm.addEditor,
          ChartPermissionId: rule.ruleForm.addBreed,
          TimingPublishTime: rule.ruleForm.addTime,
          ArticleId: rule.ruleForm.ArticleId,
        })
        .then((res) => {
          if (res.Success) {
            ElMessage.success("发布成功!");
            getList();
            editTitle.value = false;
            dialogVisible.value = false;
            rule.ruleForm = {
              addBreed: "",
              addTetle: "",
              addEditor: "",
              addTime: getTimer.value,
            };
          } else {
          }
        });
    } else {
      return false;
    }
  });
}
//添加保存的事件
const saveForm=()=>{
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      morningPaper
        .articlePreservation({
          Title: rule.ruleForm.addTetle,
          Body: rule.ruleForm.addEditor,
          ChartPermissionId: rule.ruleForm.addBreed,
          TimingPublishTime: rule.ruleForm.addTime,
          ArticleId: rule.ruleForm.ArticleId,
        })
        .then((res) => {
          if (!res.Success) return ElMessage.error(res.Msg);
          ElMessage.success("保存成功!");
          getList();
          editTitle.value = false;
        });
      dialogVisible.value = false;
      rule.ruleForm = {
        addBreed: "",
        addTetle: "",
        addEditor: "",
        addTime: getTimer.value,
      };
    } else {
      return false;
    }
  });
}
// 添加弹框X号关闭的事件
const handleClose=()=>{
  ruleFormRef.value.resetFields();
  dialogVisible.value = false;
  editTitle.value = false;
}
// 编辑弹框X号关闭的事件
const handleClosedeit=()=>{
  dialogVisibleEdit.value = false;
}
//编辑的事件
const particularsClicks=(item)=>{
  morningPaper
    .articleDetail({
      ArticleId: item.ArticleId,
    })
    .then((res) => {
      if (!res.Success) return ElMessage.error(res.Msg);
      linkUrl.value = `https://ficc.hzinsights.com/manage/articleList?Code=${res.Data.Code}`;
      editList.value = res.Data;
    });
  dialogVisibleEdit.value = true;
}

//编辑的点击事件
const editClicks=(item)=>{
  rule.ruleForm = {
    addBreed: item.ChartPermissionId,
    addTetle: item.Title,
    addEditor: item.Body,
    addTime: getTimer.value + "",
    ArticleId: item.ArticleId,
  };
  dialogVisible.value = true;
  editTitle.value = true;
}
//pvuv
const getPVAndUv=()=>{
  morningPaper.getPVAndUv().then((res) => {
    pvUvList.value = res.Data[0];
  });
}

onUpdated(()=>{
  $("#leftfroala").find("p").css({ fontSize: "16px" });
  $("#leftfroala").find("p strong span").css({ fontSize: "16px" });
  $("#leftfroala")
    .find(".fr-placeholder")
    .css({ fontSize: "16px", lineHeight: "25.6px" });
})

rule.ruleForm.addTime = getTimer.value + "";

getList();
getmyfllow();
getPVAndUv();
  


</script>

<template>
  <div class="container-everyday">
    <el-card class="box-card">
      <el-button
        type="primary"
        style="margin-right: 25px"
        @click="dialogVisible = true"
        >添加</el-button
      >
      <el-select
        v-model="list.Status"
        clearable
        placeholder="全部状态"
        style="margin-right: 25px; max-width: 160px"
        @change="optionsChange"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :value="item.value"
          :label="item.label"
        >
        </el-option>
      </el-select>
      <el-select
        style="max-width: 160px"
        v-model="list.ChartPermissionIds"
        clearable
        placeholder="全部品种"
        @focus="getmyfllow"
        @change="optionsChange"
      >
        <el-option
          v-for="item in varietyList"
          :key="item.ChartPermissionId"
          :value="item.ChartPermissionId"
          :label="item.PermissionName"
        >
        </el-option>
      </el-select>
      <div class="pvuv">
        <span>PV:</span>
        <span>{{ pvUvList.Pv }}</span>
      </div>
      <div class="pvuv">
        <span>UV:</span>
        <span>{{ pvUvList.Uv }}</span>
      </div>
      <div class="potential_top" style="width: 281px">
        <el-input
          clearable
          v-model.trim="list.KeyWord"
          style="max-width: 281px"
          placeholder="搜索标题/内容"
          @input="searching"
        >
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        <!-- <el-button type="primary" @click="searching">客户检索</el-button> -->
      </div>
    </el-card>
    <el-card class="bottom-card">
      <el-table border :data="listData" style="width: 100%">
        <el-table-column prop="Title" label="标题" align="center" width="700">
          <template #default="scope">
            <el-tag>{{ scope.row.ChartPermissionName }}</el-tag>
            <el-button link type="primary" @click="particularsClicks(scope.row)">{{
              scope.row.Title
            }}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="LastUpdateTime" label="更新时间" align="center" :formatter="formatter">
        </el-table-column>
        <el-table-column label="发布状态" align="center">
          <template #default="scope">
            <span v-if="scope.row.PublishStatus == 0" style="color: #ff4444"
              >未发布</span
            >
            <span v-else style="color: #51cc87">已发布</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <div v-if="scope.row.PublishStatus == 1">
              <el-button
                link
                @click="unpublish(scope.row)"
                style="color: #ff4444"
                >取消发布</el-button
              >
              <el-button
                link
                @click="removeItem(scope.row)"
                style="color: #ff4444"
                >删除</el-button
              >
            </div>
            <div v-else>
              <el-button link @click="issueArticle(scope.row)" type="primary"
                >发布</el-button
              >
              <el-button link @click="editClicks(scope.row)" type="primary"
                >编辑</el-button
              >
              <el-button
                link
                @click="removeItem(scope.row)"
                style="color: #ff4444"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="pageshow"
        background
        :current-page="list.CurrentIndex"
        @current-change="handleCurrentChange"
        layout="prev, pager, next"
        :total="totals"
      >
      </el-pagination>
    </el-card>
    <!-- 添加的弹框 -->
    <el-dialog
      v-dialogDrag
      :title="editTitle ? '编辑' : '添加'"
      v-model="dialogVisible"
      width="1092px"
      :before-close="handleClose"
      :modal-append-to-body="false"
      :center="true"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="rule.ruleForm" :rules="rules" ref="ruleFormRef">
          <el-form-item prop="addBreed" style="display:inline-block;">
          <el-select
            style="width: 400px"
            placeholder="添加品种"
            v-model="rule.ruleForm.addBreed"
          >
            <el-option
              v-for="item in varietyList"
              :key="item.ChartPermissionId"
              :value="item.ChartPermissionId"
              :label="item.ChartPermissionName"
            >
            </el-option>
          </el-select>
            
        </el-form-item>
        <el-form-item prop="addTime" style="display:inline-block;margin-left: 136px;">
        <div>
            <span style="margin-right: 20px">发布时间</span>
            <el-date-picker
              v-model="rule.ruleForm.addTime"
              style="width: 420px"
              type="date"
              placeholder="选择日期"
              :picker-options="pickerOptions"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
            >
            </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item prop="addTetle">
          <el-input
            v-model="rule.ruleForm.addTetle"
            placeholder="请输入标题"
            style="width: 100%; margin: 10px 0 10px"
          ></el-input>
        </el-form-item>

        <el-form-item prop="addEditor">
          <div id="leftfroala" style="width: 100%;">
            <froala
              v-model:value="rule.ruleForm.addEditor"
              id="froala-editor"
              ref="froalaEditor"
              :tag="'textarea'"
              :config="froalaConfig"
            ></froala>
          </div>
        </el-form-item>
     
      </el-form>
      <template #footer>
        <span  class="dialog-footer">
          <el-button @click="saveForm">保存</el-button>
          <el-button type="primary" @click="submitForm">发布</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 详情的弹框 -->
    <el-dialog
      v-dialogDrag
      width="1092px"
      class="edit-dialog"
      title="详情"
      v-model="dialogVisibleEdit"
      :modal-append-to-body="false"
      :center="true"
      :before-close="handleClosedeit"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div>
        <div class="edit-dialog-box">
        <div style="float:left;">  <span>品种:</span> <span>{{ editList.ChartPermissionName }}</span></div>
          <div class="teim-box" style="float: right;">
          <span style="margin-right: 20px">发布时间</span>
          <el-date-picker
            v-model="editList.ActualPublishTime"
            style="width: 420px"
            type="date"
            placeholder="选择日期"
            :picker-options="pickerOptions"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          >
          </el-date-picker>
        </div>
        </div>
        <el-input
          v-model="editList.Title"
          style="width: 100%; margin: 20px 0 10px"
        ></el-input>
        <div v-html="editList.Body" class="details"></div>
      
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisibleEdit = false">关闭</el-button>
          <el-popover placement="bottom" trigger="click">
            <div class="wxImg">
              <img
                src="~@/assets/img/wxfx.png"
                style="width: 15px; height: 15px"
              />
              <span>微信扫一扫</span>
              <vue-qr
                :text="linkUrl"
                :margin="0"
                colorDark="#333"
                colorLight="#fff"
                :dotScale="1"
                :size="100"
              ></vue-qr>
            </div>
            <template #reference >
              <el-button ref="reference" type="primary">分享</el-button>
            </template>
          </el-popover>
        </span>
      </template>

    </el-dialog>

    <!-- 二维码 -->
  </div>
</template>

<style  lang="scss">
.container-everyday {
  padding: 0;
  margin: 0;
  .box-card {
    padding: 0;
    margin: 0;
    .potential_top {
      float: right;
    }
    .pvuv {
      display: inline-table;
      max-width: 152px;
      min-width: 100px;
      height: 40px;
      margin-left: 25px;
      line-height: 40px;
      background: #f0f2f5;
      text-align: center;
      color: #666666;
    }
  }
  .el-pagination {
    margin-top: 90px;
    display: flex;
    justify-content: flex-end;
  }
  .bottom-card {
    position: relative;
    .el-tag {
      position: absolute;
      left: 20px;
    }
  }
  .el-dialog__body {
    padding-top: 15px !important;
  }
  .el-dialog__footer {
    text-align: center !important;
    .el-button {
      margin-right: 30px;
    }
  }


  .details {
    border: 1px solid #edeff4;
    width: 100%;
    height: 400px !important;
    margin: 20px 0;
    overflow: auto;
    img {
      max-width: 100%;
      max-height: 800px;
    }
  }
  .fr-second-toolbar {
    display: none;
  }
}
.edit-dialog-box {
  height: 30px;
  line-height: 30px;
}
.edit-dialog .el-dialog__header {
  border-bottom: 1px solid #edeff4;
}

.edit-dialog .el-dialog__footer {
  height: 80px;
  line-height: 60px;
  border-top: 1px solid #edeff4;
}
.el-popover {
  min-width: 100px;
  max-width: 100px;
  background: #ffffff;
  border: 1px solid #dfdfdf;
  opacity: 1;
  // bottom:0px
  .wxImg {
    // padding-bottom: 5px;
    text-align: center;
    img {
      vertical-align: middle;
      margin-right: 8px;
      margin-bottom: 3px;
    }
    span {
      display: inline-block;
      text-align: right;
      margin-bottom: 3px;
    }
  }
}
</style>
