<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">{{item.MsgTime.substr(10)}}</span>
            {{item.Content}} 
          </p>
          <p class="news-en" :style="item.showEn ? 'display:block' : 'display:none'">{{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>

     <!-- 设置默认弹窗 -->
    <m-dialog 
      title="设置默认值" 
      :show.sync="configForm.show" 
      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
              :options="classifyArr"
              v-model="configForm.classify"
              placeholder="类型筛选"
              size="medium"
              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 slot="footer" style="margin-top: 20px;">
        <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>
    </m-dialog>

    <!-- 编辑弹窗 -->
    <m-dialog 
      title="编辑" 
      :show.sync="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>
    </m-dialog>

  </div>
</template>

<script>
import mDialog from '@/components/mDialog.vue'
import * as reportEnInterface from '@/api/modules/reportEnApi';
import * as dayApi from '@/api/modules/daynewsApi';
export default {
  components: { mDialog },
  data() {
    return {
      dataloading: false,
      newsList: [],
      page_no: 1,
      pageSize: 10,
      haveMore: true,
      updateTime: '',

      classifyArr: [],
      formRules: {
        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' }]
      },
      configForm: {
        show: false,
        classify: [],
        title: 'China Macro and Commodity',
        abstract: 'China Macro and Commodity',
        overview:'',
        author: '',
        frequency: ''
      },

      editForm:{
        show:false
      }
    }
  },
  methods: {
    editNews(item){
      this.editForm={
        show:true,
        ...item
      }
    },
    handleEdit(){
      if(!this.editForm.ContentEn){
        this.$message.warning('英文翻译内容不可为空')
        return
      }
      dayApi.editMsg({
        MsgId:this.editForm.MsgId,
        ContentEn:this.editForm.ContentEn
      }).then(res=>{
        if(res.Ret !== 200) return
        this.$message.success('编辑成功')
        this.page_no = 1;
        this.getList();
        this.editForm={
          show:false,
        }
      })
    },

    getList() {
      this.dataloading = true;
      dayApi.getList({
        PageSize: this.pageSize,
        CurrentIndex: this.page_no
      }).then(res => {
        this.dataloading = false;
        if(res.Ret !== 200) return

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

        this.newsList = this.page_no === 1 ? List : this.newsList.concat(List);
        this.haveMore = this.page_no <= Paging.Pages;
        this.updateTime = this.$moment(LastUpdateTime).format('YYYY.MM.DD ddd HH:mm:ss')
      })
    },

    getClassify() {
      let params={CurrentIndex:0,PageSize:1000,KeyWord:''};
			reportEnInterface.classifyList(params).then((res) => {
				if( res.Ret==200&&Array.isArray(res.Data.List) ){
					res.Data.List.forEach(item=>{
						let newitem={label:item.ClassifyName,value: JSON.stringify({
              name: item.ClassifyName,
              id: item.Id
            })};
						if( item.Child ){
							let childnode=[];
							item.Child.forEach(itemchild=>{
								childnode.push({label:itemchild.ClassifyName,value:JSON.stringify({
                  name: itemchild.ClassifyName,
                  id: itemchild.Id
                })});
							});
							newitem.children=childnode;
						}
						this.classifyArr.push(newitem);
					});

          // this.configForm.classify =  [this.classifyArr[0].value,this.classifyArr[0].children[0].value]
				}
			});
    },

    /* 生成报告 */
    createReport() {
      if(!this.newsList.length) return this.$message.warning('暂无内容')
      const { classify,title,abstract,author,frequency,overview } = this.configForm;
      if(!classify || !title || !abstract||!overview) this.$message.warning('请先设置默认值')
      
/*       const params = {
        ClassifyIdFirst: Number(JSON.parse(classify[0]).id),
        ClassifyNameFirst: JSON.parse(classify[0]).name,
        ClassifyIdSecond: classify.length>1 ? Number(JSON.parse(classify[1]).id) : 0,
        ClassifyNameSecond: classify.length>1 ? JSON.parse(classify[1]).name : '',
        Title:title,
        Abstract: abstract,
        Author: author,
        Frequency: frequency,
        Overview:overview
      } */

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

        this.page_no = 1;
        this.getList();
      })
    },

    /* 刷新 */
    refreshNews() {
      dayApi.refreshList().then(res => {
        if(res.Ret !== 200) return
        this.$message.success(res.Msg)
        this.page_no = 1;
        this.getList();
      })
    },

    /* 获取默认值配置 */
    getConfigHandle() {
      dayApi.getConfig().then(res => {
        if(res.Ret !== 200) return

        const { 
          Abstract,
          Title,
          ClassifyIdFirst,
          ClassifyIdSecond,
          ClassifyNameFirst,
          ClassifyNameSecond,
          Author,
          Frequency,
          Overview
        } = res.Data;
        let val_first = ClassifyIdFirst ? JSON.stringify({name: ClassifyNameFirst,id: ClassifyIdFirst}) : '';
        let val_second = ClassifyIdSecond ? JSON.stringify({name: ClassifyNameSecond,id: ClassifyIdSecond}) : '';
        this.configForm.classify =  val_second ? [val_first,val_second] : val_first ? [val_first] : []
        this.configForm.title = Title;
        this.configForm.abstract = Abstract;
        this.configForm.author = Author;
        this.configForm.frequency = Frequency;
        this.configForm.overview = Overview
      })
    },
    
    /* 设置默认值 */
    setConfigHandle() {
      this.configForm.show = true;
      this.getConfigHandle()
    },
    /* 保存默认值 */
    handleSaveConfig(){
      this.$refs.formRef.validate(valid=>{
          if(valid){
            this.saveConfig()
          }
      })
    },
    saveConfig(){
      const { classify,title,abstract,author,frequency,overview } = this.configForm;
      const params = {
        ClassifyIdFirst: Number(JSON.parse(classify[0]).id),
        ClassifyNameFirst: JSON.parse(classify[0]).name,
        ClassifyIdSecond: classify.length>1 ? Number(JSON.parse(classify[1]).id) : 0,
        ClassifyNameSecond: classify.length>1 ? JSON.parse(classify[1]).name : '',
        Title:title,
        Abstract: abstract,
        Author: author,
        Frequency: frequency,
        Overview:overview
      }
      dayApi.setConfig(params).then(res=>{
        if(res.Ret===200){
          this.$message.success('保存配置成功')
          this.configForm.show = false;
        }
      })
      this.configForm.show = false;
    },
    /* 翻译 */
    translateHandle() {
      dayApi.translateMsg().then(res => {
        if(res.Ret !== 200) return
        this.$message.success('翻译成功')
        this.page_no = 1;
        this.getList();
      })
    },

    /* 删除 */
    delNews({MsgId},index) {
      this.$confirm('删除后不可恢复,确认删除吗?','提示',{type:'warning'}).then(() => {
				dayApi.delMsg({MsgId}).then(res => {
          if(res.Ret !== 200) return
          this.$message.success('删除成功')
          this.newsList.splice(index,1)
        })
			}).catch(() => {});
    },

    cancelDialog() {
      this.$refs.formRef.resetFields();
      this.configForm.show = false;
    },
    
    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) && this.haveMore) {
        console.log('触底')
        this.page_no++;
        this.getList()
      }
    },300)
  },

  mounted() {
    this.getConfigHandle();
    this.getClassify();
    this.getList();
  },
}
</script>

<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;
    }
  }
}
</style>

<style lang="scss">
.set-config-dialog {
  .el-cascader .el-input {
    width: 100% !important;
  }
}
</style>