
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import moment from 'moment';
import _ from 'lodash'
import * as reportEnInterface from '@/api/modules/reportEnApi';
import * as dayApi from '@/api/modules/daynewsApi';

let dataloading = ref(false)
let newsList = ref([])
let page_no = ref(1)
let pageSize = ref(10)
let haveMore = ref(true)
let updateTime = ref('')
let classifyArr = ref([])
const formRules = reactive({
    classify: [{ required: true, message:"分类不能为空",trigger:'blur' }],
    title: [{ required: true, message:"报告标题不能为空",trigger:'blur' }],
    abstract: [{ required: true, message:"报告摘要不能为空",trigger:'blur' }],
    overview:[{ required: true, message:"报告overview不能为空",trigger:'blur' }]
})
let configForm = reactive({
        show: false,
        classify: [],
        title: 'China Macro and Commodity',
        abstract: 'China Macro and Commodity',
        overview:'',
        author: '',
        frequency: ''
      })
let editForm = reactive({
    show:false,
})
function editNews(item){
    editForm.show = true
    Object.assign(editForm,item)
}
function handleEdit(){
    if(!editForm.ContentEn){
        return ElMessage.warning('英文翻译内容不可为空')
    }
    dayApi.editMsg({
        MsgId:editForm.MsgId,
        ContentEn:editForm.ContentEn
      }).then(res=>{
        if(res.Ret !== 200) return
        ElMessage.success('编辑成功')
        page_no.value = 1;
        getList();
        editForm.show = false
      })
}
function getList(){
    dataloading.value = true;
    dayApi.getList({
        PageSize: pageSize.value,
        CurrentIndex: page_no.value
    }).then(res => {
        dataloading.value = false;
        if(res.Ret !== 200) return

        const { List,Paging,LastUpdateTime } = res.Data;
        List.forEach(_ => {
            _.showEn = false;
        })

        newsList.value = page_no.value === 1 ? List : newsList.value.concat(List);
        haveMore.value = page_no.value <= Paging.Pages;
        updateTime.value = moment(LastUpdateTime).format('YYYY.MM.DD ddd HH:mm:ss')
    })
}
function getClassify() {
    reportEnInterface.classifyList().then((res) => {
        if(res.Ret!==200) return 
        classifyArr.value  = formatClassifyArr({Child:res.Data.List||[]})
    });
}
function formatClassifyArr(tree){
    function dfs(node,level){
        node.value = JSON.stringify({id:node.Id,name:node.ClassifyName})
        if(!node.Child&&level<3){
            node.disabled = true
        }
        if(Array.isArray(node.Child)){
            for(let n of node.Child){
                dfs(n,level+1)
            }
            if(!node.Child.length){
                node.disabled = true
            }
        }
    }
    dfs(tree,0)
    return tree.Child
}
/* 生成报告 */
function createReport() {
    if(!newsList.value.length) return ElMessage.warning('暂无内容')
    const { classify,title,abstract,author,frequency,overview } = configForm;
    if(!classify || !title || !abstract||!overview) ElMessage.warning('请先设置默认值')

    dayApi.translateReport(/* params */).then(res => {
        if(res.Ret !== 200) return
        ElMessage.success('生成成功')

        page_no.value = 1;
        getList();
    })
}
/* 刷新 */
function refreshNews() {
    dayApi.refreshList().then(res => {
        if(res.Ret !== 200) return
        ElMessage.success(res.Msg)
        page_no.value = 1;
        getList();
    })
}
/* 获取默认值配置 */
function getConfigHandle() {
    dayApi.getConfig().then(res => {
        if(res.Ret !== 200) return
        const { 
          Abstract,
          Title,
          ClassifyIdFirst,
          ClassifyIdSecond,
          ClassifyIdThird,
          ClassifyNameFirst,
          ClassifyNameSecond,
          ClassifyNameThird,
          Author,
          Frequency,
          Overview
        } = res.Data;

        configForm.classify = [
            JSON.stringify({id:ClassifyIdFirst||0,name:ClassifyNameFirst||''}),
            JSON.stringify({id:ClassifyIdSecond||0,name:ClassifyNameSecond||''}),
            JSON.stringify({id:ClassifyIdThird||0,name:ClassifyNameThird||''})
        ]
        
        configForm.title = Title;
        configForm.abstract = Abstract;
        configForm.author = Author;
        configForm.frequency = Frequency;
        configForm.overview = Overview
    })
}
/* 设置默认值 */
function setConfigHandle() {
    configForm.show = true;
    getConfigHandle()
}
/* 保存默认值 */
const formRef = ref(null)
function handleSaveConfig(){
    formRef.value?.validate(valid=>{
        if(valid){
            saveConfig()
        }
    })
}
function saveConfig(){
    const { classify,title,abstract,author,frequency,overview } = configForm;
    const params = {
        ClassifyIdFirst: Number(JSON.parse(classify[0]).id),
        ClassifyNameFirst: JSON.parse(classify[0]).name,
        ClassifyIdSecond: Number(JSON.parse(classify[1]).id),
        ClassifyNameSecond: JSON.parse(classify[1]).name,
        ClassifyIdThird:Number(JSON.parse(classify[2]).id),
        ClassifyNameThird:JSON.parse(classify[2]).name,
        Title:title,
        Abstract: abstract,
        Author: author,
        Frequency: frequency,
        Overview:overview
      }
    dayApi.setConfig(params).then(res=>{
        if(res.Ret===200){
            ElMessage.success('保存配置成功')
            configForm.show = false;
        }
      })
    configForm.show = false;
}
/* 翻译 */
function translateHandle() {
    dayApi.translateMsg().then(res => {
        if(res.Ret !== 200) return
        ElMessage.success('翻译成功')
        page_no.value = 1;
        getList();
    })
}
/* 删除 */
function delNews({MsgId},index) {
    this.$confirm('删除后不可恢复,确认删除吗?','提示',{type:'warning'}).then(() => {
        dayApi.delMsg({MsgId}).then(res => {
            if(res.Ret !== 200) return
            ElMessage.success('删除成功')
            newsList.value.splice(index,1)
        })
    }).catch(() => {});
}
function cancelDialog() {
    formRef.value?.resetFields();
    configForm.show = false;
}
let scrollHandle = _.throttle(function(e) {
      const height = e.target.clientHeight;
      const s_height = e.target.scrollTop;
      const t_height = e.target.scrollHeight;

      if((height+s_height >= t_height-50) && haveMore.value) {
        console.log('触底')
        page_no.value++;
        getList()
      }
},300)
function transformTimeType(date){
    return date.replaceAll('-','/').substr(0,16)
}
onMounted(()=>{
    getConfigHandle();
    getClassify();
    getList();
})
</script>
<template>
    <div 
      class="day-news-container"
      @scroll="scrollHandle"
    >
      <div class="top">
        <el-button type="primary" @click="createReport">生成报告</el-button>
        <el-button type="primary" @click="refreshNews">一键刷新</el-button>
        <el-button type="primary" @click="translateHandle" v-if="newsList.length">一键翻译</el-button>
        <el-button type="primary" plain @click="setConfigHandle">设置默认值</el-button>
      </div>
      <h3 class="update-time">{{updateTime}}</h3>
      <template v-if="newsList.length">
        <div class="list-item" v-for="(item,index) in newsList" :key="item.MsgId">
          <div class="item-cont">
            <p class="news">
              <span style="font-weight: bold;margin-right: 10px;" v-if="item.MsgTime">
                {{transformTimeType(item.MsgTime)}}
              </span>
              {{item.Content}} 
            </p>
            <p class="news-en" :style="item.showEn ? 'display:block' : 'display:none'">
              <span style="font-weight: bold;margin-right: 10px;" v-if="item.MsgTime">
                {{transformTimeType(item.MsgTime)}}
              </span>
              {{item.ContentEn}}
            </p>
          </div>
  
          <div class="item-bot">
            <div>
              <template v-if="item.ContentEn">
                <span class="editsty" v-if="item.showEn" @click="item.showEn=!item.showEn">收起 <i class="el-icon-arrow-up"/> </span>
                <span class="editsty" v-else @click="item.showEn=!item.showEn"> 展开英文<i class="el-icon-arrow-down"/> </span>
              </template>
              <span class="editsty" @click="translateHandle(item)" v-if="!item.ContentEn">一键翻译</span>
            </div>
            <div>
              <!-- <span style="margin-right: 40px;color: #666">发件人：{{item.FromName}}</span> -->
              <span style="margin-right: 20px;color: #409eff;cursor: pointer;" @click="editNews(item)">编辑</span>
              <span class="deletesty" @click="delNews(item,index)">删除此条</span>
            </div>
          </div>
        </div>
      </template>
  
      <div class="no-data" v-else>
        <img src="~@/assets/img/data_m/nodata-big.png" alt="" style="margin:auto">
        <p>暂无数据</p>
      </div>
  
       <!-- 设置默认弹窗 -->
      <el-dialog 
        title="设置默认值" 
        v-model="configForm.show"
        :close-on-click-modal="false"
        :modal-append-to-body="false"
        width="650px"
        class="set-config-dialog"
      >
        <div style="padding-left: 50px">
          <el-form 
            :model="configForm" 
            :rules="formRules" 
            ref="formRef" 
            label-position="left"
            hide-required-asterisk
            label-width="80px">
            <el-form-item prop="classify" label="报告分类">
              <el-cascader
                ref="cascaderRef"
                :options="classifyArr"
                v-model="configForm.classify"
                :props="{
                  label:'ClassifyName',
                  children:'Child'
                }"
                placeholder="类型筛选"
                style="width: 70%"
              />
            </el-form-item>
            <el-form-item prop="title" label="报告标题">
              <el-input
                type="textarea"
                :rows="3"
                placeholder="请输入内容"
                v-model="configForm.title"
                style="width: 70%"
              />
            </el-form-item>
            <el-form-item label="报告摘要" prop="abstract">
              <el-input
                type="textarea"
                :rows="5"
                placeholder="请输入内容"
                maxlength="100"
                show-word-limit
                v-model="configForm.abstract"
                style="width: 70%"
              />
            </el-form-item>
            <el-form-item label="overview" prop="overview">
              <el-input
                type="textarea"
                :rows="5"
                placeholder="请输入内容"
                show-word-limit
                v-model="configForm.overview"
                style="width: 70%"
              />
            </el-form-item>
          </el-form>
        </div>
        <div style="margin:30px 0;text-align:center">
          <el-button
          @click="cancelDialog"
          style="width: 132px; height: 40px"
          >取消</el-button>
          <el-button
            @click="handleSaveConfig"
            type="primary"
            style="width: 132px; height: 40px"
            >保存</el-button>
        </div>
      </el-dialog>
  
      <!-- 编辑弹窗 -->
      <el-dialog
        title="编辑" 
        v-model="editForm.show" 
        width="650px"
        class="set-config-dialog"
      >
        <div class="edit-wrap">
          <div v-if="editForm.MsgTime" style="font-size:14px;color:#333">{{editForm.MsgTime.substr(10)}}</div>
          <el-input
            type="textarea"
            :rows="5"
            placeholder="请输入内容"
            disabled
            style="margin:10px 0"
            v-model="editForm.Content">
          </el-input>
          <div style="color:#333;margin-bottom:10px" >英文翻译</div>
          <el-input
            type="textarea"
            :rows="5"
            placeholder="请输入内容"
            v-model="editForm.ContentEn">
          </el-input>
          <div style="margin:30px 0;text-align:center">
            <el-button type="primary" plain @click="editForm.show=false">取消</el-button>
            <el-button type="primary" @click="handleEdit">确定</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </template>
  
<style lang="scss" scoped>
  *{ box-sizing: border-box; }
  .day-news-container {
    height: calc(100vh - 120px);
    overflow-y: auto;
    border: 1px solid #ececec;
    border-radius: 4px;
    background: #fff;
    box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
    padding: 20px;
  
    .update-time {
      font-size: 30px;
      margin-top: 30px;
    }
  
    .no-data {
      text-align: center;
      padding: 50px 0;
      color: #666;
    }
  
    .list-item {
      padding: 20px 0;
      border-bottom: 1px solid #D2D2D2;
      .item-cont {
        font-size: 16px;
        .news {
          margin-bottom: 10px;
        }
        .news-en {
          color: #888;
        }
      }
      .item-bot {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 20px;
      }
    }
  }
  :deep(.set-config-dialog) {
    .el-cascader{
        .el-input{
            width: 100% !important;
        }
    
    }
}
</style>