<template>
  <div id="reportlist">
    <el-card class="box-card">
      <div class="header">
        <el-form :inline="true" :model="searchform" @submit.native.prevent>
          <el-form-item label="">
            <el-button
              v-permission="permissionBtn.enReportManageBtn.enReport_reportAdd"
              type="primary"
              size="medium"
              @click="$router.push({ path: '/reportEnEditor' })"
              >添加研报</el-button
            >
          </el-form-item>
          <el-form-item label="">
            <el-button 
              v-permission="permissionBtn.enReportManageBtn.enReport_syncPolicy"
              type="primary" 
              :loading="isPull" 
              @click="handlePullReport"
            >同步策略报告</el-button>
          </el-form-item>
          <el-form-item label="">
            <el-date-picker
              v-model="searchform.dateValue"
              type="daterange"
              unlink-panels
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="起始日期"
              end-placeholder="结束日期"
              size="medium"
              style="width: 280px"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="">
            <el-select
              v-model="searchform.frequency"
              placeholder="更新频度筛选"
              size="medium"
              clearable
              style="width: 140px"
            >
              <el-option v-for="item in frequencyArr" :key="item" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-cascader
              :options="optionsArr"
              v-model="searchform.classifynameArr"
              clearable
              placeholder="类型筛选"
              size="medium"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="">
            <el-select
              v-model.number="searchform.EmailState"
              placeholder="状态筛选"
              size="medium"
              clearable
              style="width: 140px"
            >
              <el-option label="未群发邮件" :value="1"></el-option>
              <el-option label="已群发邮件" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input
              placeholder="标题 / 作者"
              v-model="searchform.key_word"
              clearable
              size="medium"
            >
              <i class="el-icon-search" slot="prefix"></i>
            </el-input>
          </el-form-item>
        </el-form>
      </div>

      <!--  -->
      <el-table
				border
				:data="tableData"
				v-loading="listLoading"
				element-loading-text="加载中..."
				style="margin-top: 20px"
			>
				<el-table-column
					v-for="item in tableColums"
					:key="item.label"
					:label="item.label"
					:width="item.widthsty"
					:min-width="item.minwidthsty"
					:sortable="item.sortable"
					align="center"
					:prop="item.key"
				>
          <template #header>
            <span v-if="item.key==='Pv'">
              PV
              <el-tooltip class="item" effect="dark" content="pv：报告被打开的次数，每次打开都计算一次" placement="top-start">
                <i class="el-icon-warning"/>
              </el-tooltip>
            </span>
            <span v-else>{{ item.label }}</span>
          </template>	
					<template slot-scope="{row}">
							<span v-if="item.key==='Title'" @click="lookreportdtl(row)">
								<span style="cursor:pointer; color:#4099ef;">{{row.Title}}</span>
							  <span style="cursor:pointer; color:#4099ef;" v-if="row.CreateTime">({{row.CreateTime.substring(5,7)}}{{row.CreateTime.substring(8,10)}})</span>
							</span>
              <span v-else-if="item.key==='ClassifyNameFirst'">
                {{row.ClassifyNameFirst}} 
                <span v-if="row.ClassifyNameSecond">/ {{row.ClassifyNameSecond}}</span>
              </span>
              <span v-else-if="item.key==='State'" :style="row.State===2 && 'color:#46C371;'">
                {{row.State===2 ? '已发布' : '未发布'}}
              </span>
              <span v-else-if="item.key==='Stage'">第{{row.Stage}}期</span>
              <span v-else-if="item.key==='Pv'" style="cursor:pointer; color:#4099ef;" >
                <span @click="reportHandle(row,'PV')" v-if="row.PvEmail">{{row.PvEmail}}</span>
                <span v-if="row.PvEmail&&row.Pv" style="color:#333">/</span>
                <span v-if="row.Pv" style="color:#333">{{row.Pv}}</span>
              </span>

              <span v-else-if="item.key==='handle'">
                <template v-if="row.State===1">
                    <span class="editsty" v-permission="permissionBtn.enReportManageBtn.enReport_publish"
                        @click="reportHandle(row,'publish')" v-if="row.CanEdit">发布</span>
                    <span v-permission="permissionBtn.enReportManageBtn.enReport_reportEdit"
                        class="editsty" @click="reportHandle(row,'edit')" v-if="row.CanEdit">编辑</span>
                  <!-- <span class="editsty" @click="reportHandle(row,'editing')" v-else>{{row.Editor||''}}编辑中...</span> -->
                  <span v-permission="permissionBtn.enReportManageBtn.enReport_reportEdit"
                    class="editsty" @click="reportHandle(row,'edit')" v-else>{{row.Editor||''}}编辑中...</span>
                  <span v-permission="permissionBtn.enReportManageBtn.enReport_reportDel"
                    class="deletesty" @click="reportHandle(row,'del')" v-if="row.CanEdit">删除</span>
                </template>
                <template v-else>
                    <span v-permission="permissionBtn.enReportManageBtn.enReport_cancelPublish"
                        @click="reportHandle(row,'cancelPublish')" class="deletesty">取消发布</span>
                    <span v-permission="permissionBtn.enReportManageBtn.enReport_sendEmail"
                        class="editsty copylink" @click="reportHandle(row,'sendEmail')" v-if="row.EmailState===0&&row.EmailAuth">群发邮件</span>

                  <span
                    v-permission="permissionBtn.enReportManageBtn.enReport_sendEmail"
                    class="editsty copylink" 
                    v-if="row.EmailState===1&&row.EmailAuth" 
                    @click="reportHandle(row,'view-log')"
                    style="position: relative;"
                  >
                    群发日志 
                    <span class="warn-tag" v-if="row.EmailHasFail"></span>
                  </span>
								</template>
              </span>

							<span v-else>{{ row[item.key] || '' }}</span>
						</template>
				</el-table-column>
				<div slot="empty" style="padding: 100px 0">
           <tableNoData text="暂无数据" size="mini"/>
				</div>
			</el-table>

      <el-col :span="24" class="toolbar">
        <m-page
					:page_no="page_no"
					:pageSize="15"
					:total="total"
					@handleCurrentChange="pageChange"
				/>
      </el-col>
    </el-card>

    <!-- 群发邮件弹窗 -->
    <el-dialog 
      v-dialogDrag 
      :append-to-body="true" 
      :visible.sync="popData.show" 
      width="900px" 
      title="群发邮件"
    >
      <div class="send-email-wrap">
        <el-form ref="form" :model="popData" label-width="100px">
          <el-form-item label="收件人：">
            <div>
              <!-- <el-radio v-model="popData.radio" label="1">默认全部</el-radio> -->
              <el-cascader
                v-if="popData.show"
                v-model="popData.varietyVal"
                :options="popData.varietyOpt"
                collapse-tags
                clearable
                :props="{
                  multiple:true,
                  value:'EnPermissionId',
                  label:'EnPermissionName',
                  children:'Child'
                }"
                placeholder="请选择品种权限"
              />
              <el-checkbox v-model="popData.checkUser" style="margin-left:20px">指定人员</el-checkbox>
            </div>
            <div v-if="popData.checkUser" class="user-box">
              <el-select
                v-model="popData.value"
                multiple
                filterable
                collapse-tags
                placeholder="请选择客户"
                value-key="Id"
              >
                <el-option
                  v-for="item in popData.options"
                  :key="item.Id"
                  :label="item.Name"
                  :value="item"
                  :disabled="item.Enabled===0">
                  <span>{{item.Name}} &lt;{{item.Email}}&gt;</span>
                </el-option>
              </el-select>
              <div style="margin-top:10px" class="box">
                <el-tooltip 
                  effect="dark" 
                  :content="item.Email" 
                  placement="top"
                  v-for="(item,index) in popData.value"
                  :key="item.Id"
                  >
                <el-tag
                  closable
                  style="margin:0 10px 10px 0"
                  @close="handleDelSelectCustom(item,index)">
                  {{item.Name}}
                </el-tag>
                </el-tooltip>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="邮件主题：">
            <div>
              <el-input 
                placeholder="请输入邮件主题" 
                v-model="popData.theme" 
                type="textarea" 
                maxlength="100"
                show-word-limit
                :autosize="{ minRows: 3, maxRows: 4}"
              ></el-input>
            </div>
          </el-form-item>
          <div style="text-align:center;margin-bottom:30px;margin-top:40px">
            <el-button type="primary" plain style="margin-right:10px" @click="popData.show=false">取消</el-button>
            <el-button type="primary" @click="handleConfirmSendEmail">确定</el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>

    <!-- pv统计 -->
    <el-dialog 
      v-dialogDrag 
      :append-to-body="true" 
      :visible.sync="PVData.show" 
      width="900px" 
      title="点击量详情"
    >
      <div class="pv-static-wrap" style="padding-bottom:70px">
        <el-table :data="PVData.list" border height="600">
          <el-table-column align="center" prop="Name" label="客户名称"></el-table-column>
          <el-table-column align="center" prop="Email" label="邮箱地址"></el-table-column>
          <el-table-column align="center" prop="RecentClickTime" label="最近点击时间"></el-table-column>
          <el-table-column align="center" prop="ClickNum" label="点击量"></el-table-column>   
        </el-table>
        <el-pagination 
          layout="total,prev,pager,next,jumper" 
          background 
          :current-page="PVData.page" 
          @current-change="handlePVPageChange" 
          :page-size="PVData.pageSize" 
          :total="PVData.total" 
          style="float:right;margin-top:20px">
        </el-pagination>
      </div>
    </el-dialog>

    <!-- 编辑策略报告 -->
    <el-dialog 
      v-dialogDrag 
      :append-to-body="true" 
      :visible.sync="showEdit" 
      width="700px" 
      title="编辑"
    >
      <strategyReportEdit v-if="showEdit" :id="editId" @close="showEdit=false,editId=0" @refresh="getTableData"/>
    </el-dialog>
  </div>
</template>

<script>
import * as reportEnInterface from '@/api/modules/reportEnApi';
import {strategyReportInterence,reportVarietyENInterence} from '@/api/api.js'
import mPage from '@/components/mPage.vue';
import strategyReportEdit from '../components/strategyReportEdit.vue'
export default {
  watch: {
    searchform: {
      handler() {
        this.page_no = 1;
        this.getTableData()
      },
      deep: true
    },
    'popData.show'(n){
      if(!n){
        this.popData.checkUser=false
        this.popData.options=[]
        this.popData.value=[]
        this.popData.varietyOpt=[]
        this.popData.varietyVal=[]
      }
    }
  },
  components: {mPage,strategyReportEdit},
  data() {
    return {
      searchform: {
        dateValue:[],
        frequency:'',
        classifynameArr:'',
        state:'',
        key_word:'',
        EmailState:''
      },
      optionsArr:[],
      frequencyArr: [ '年度','半年度','季度','月度','双周度','周度','日度','不定时' ],

      listLoading: false,
      tableData: [],
      page_no: 1,
      total: 0,
      tableColums:[
        {
					label: '报告标题',
					key: 'Title',
          minwidthsty: 150
				},
        {
					label: '摘要',
					key: 'Abstract',
          minwidthsty: 150
				},
        {
					label: '报告类型',
					key: 'ClassifyNameFirst',
          minwidthsty: 120
				},
        {
					label: '创建人',
					key: 'AdminRealName',
          minwidthsty: 100
				},
        {
					label: '发布状态',
					key: 'State',
				},
        {
					label: '发布时间',
					key: 'PublishTime',
          minwidthsty: 120
				},
        {
					label: '更新时间',
					key: 'ModifyTime',
          minwidthsty: 120
				},
        {
					label: '期数',
					key: 'Stage',
					widthsty: 100
				},
        {
					label: '频度',
					key: 'Frequency',
				},
        {
					label: 'PV / UV',
					key: 'Pv',
				},
        {
					label: '操作',
					key: 'handle',
          widthsty: 150
				},
      ],

      popData:{
        show:false,
        radio:'1',
        checkUser:false,//是否选择指定人员
        options: [],
        value: [],
        theme:'',
        reportId:0,
        varietyOpt:[],
        varietyVal:[],
      },

      PVData:{
        show:false,
        list:[],
        page:1,
        pageSize:15,
        total:0,
        reportId:0
      },

      showEdit:false,//显示编辑策略报告弹窗
      editId:0,//编辑策略报告id

      isPull:false,//是否正在同步获取报告
    };
  },
  mounted() {
    this.getclassifylist();
    this.getTableData()
  },

  methods: {
    //获取分类列表
    getclassifylist(){
			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,index)=>{
						let newitem={label:item.ClassifyName,value:item.ClassifyName};
						if( item.Child ){
							let childnode=[];
							item.Child.forEach((itemchild,i)=>{
								childnode.push({label:itemchild.ClassifyName,value:itemchild.ClassifyName});
							});
							newitem.children=childnode;
						}
						this.optionsArr.push(newitem);
					});
				}
			});
		},

    /* 表格数据 */
    getTableData() {
      let params = {
				CurrentIndex:this.page_no,
        PageSize:15,
        Frequency:this.searchform.frequency,
        ClassifyNameFirst:this.searchform.classifynameArr?this.searchform.classifynameArr[0]:'',
        ClassifyNameSecond:this.searchform.classifynameArr&&this.searchform.classifynameArr.length>1?this.searchform.classifynameArr[1]:'',
        State:this.searchform.state?this.searchform.state:null,
        KeyWord:this.searchform.key_word,
        StartDate: this.searchform.dateValue ? this.searchform.dateValue[0] : '',
        EndDate: this.searchform.dateValue ? this.searchform.dateValue[1] : '',
        EmailState:this.searchform.EmailState
			};
			this.listLoading = true;
			reportEnInterface.reportList(params).then(res => {
        if( res.Ret!==200 )return

        const { Data } = res;
        Data.List && Data.List.forEach(_ => {
          _.ModifyTime = _.ModifyTime ? this.$moment(_.ModifyTime).format('YYYY-MM-DD HH:mm:ss') : ''
          _.PublishTime = _.PublishTime ? this.$moment(_.PublishTime).format('YYYY-MM-DD HH:mm:ss') : ''
        })
        this.tableData = Data.List || [];
        this.total=parseInt(Data.Paging.Totals);
        this.listLoading = false;
			});
    },

    /* 报告操作 */
    reportHandle(row,key) {
      const handleMap = {
        publish: this.publishReport,
        edit: this.editReport,
        del: this.delReport,
        cancelPublish: this.cancelReport,
        copylink: this.copyReportlink,
        sendEmail:this.sendEmail,
        PV:this.showPVDetail,
        'view-log': this.goSendlog
      }

      // if(key==='editing'){
      //   this.$message.warning('该研报正在编辑，不可重复编辑')
      //   return
      // }

      handleMap[key](row);
    },

    /* 发布报告 */
    publishReport({Id}) {
      reportEnInterface.reportPublish({ReportIds:String(Id)}).then(res=>{
				if(res.Ret!==200) return

        this.$message.success('发布成功');
        this.getTableData();
			})
    },

    /* 编辑报告 */
    editReport(item) {
      //编辑前mark一下
      reportEnInterface.markReport({Status:1,ReportId:item.Id}).then(res=>{
        // if(res.Ret!==200) return 
        if(res.Ret===200){
          if(res.Data.Status==1){
            this.$message.warning(res.Data.Msg || '该研报正在编辑，不可重复编辑')
            item.CanEdit=false;
            item.Editor=res.Data.Editor || ''
            return
          }else if(res.Data.Status==0){
            item.CanEdit=true;
            item.Editor=res.Data.Editor || ''
				  }
			  }else{
          this.$message.error(res.ErrMsg || '未知错误，请稍后重试')
          return
        }
        if(item.FromReportId>0){
          //策略同步来的报告
          this.showEdit=true
          this.editId=item.Id
          return
        }
        this.$router.push({
          path: '/reportEnEditor',
          query:{
            id:item.Id
          }
        })
      })
    },

    /* 删除报告 */
    delReport({Id}) {
      this.$confirm('确认删除吗?','提示',{
				type:'warning'
			}).then(() => {
				reportEnInterface.reportDel({ReportIds: Id}).then(res =>{
					if( res.Ret!==200 ) return
          this.$message.success( res.Msg );
          this.getTableData();
				});
			}).catch(() => {});
    },

    /* 取消发布 */
    cancelReport({Id}) {
      reportEnInterface.reportCancelPublish({ReportIds: Id}).then(res =>{
				if( res.Ret!==200 ) return

        this.$message.success( res.Msg );
        this.getTableData();
			});
    },

    /* 复制链接 */
    copyReportlink() {
      let clipboard = new this.Clipboard('.copylink')
				clipboard.on('success', e => {
					this.$message.success('复制链接成功')
					e.clearSelection() // 释放内存
					clipboard.destroy()
				})
				// // 浏览器不支持
				clipboard.on('error', e => {
					this.$message.warning('浏览器暂不支持')
					// 释放内存
					clipboard.destroy()
				})
    },

    /* 查看详情 */
    lookreportdtl({Id,ReportCode}) {
        //如果没有预览权限，就不跳转
      if(!this.permissionBtn.checkPermissionBtn(this.permissionBtn.enReportManageBtn.enReport_reportView)) return
      let {href} = this.$router.resolve({name:'预览报告',query:{id:Id,code:ReportCode,fromPage:'en'}});
			window.open(href,'_blank');
    },

    pageChange(page_no) {
      this.page_no = page_no;
      this.getTableData();
    },

    sendEmail(e){
      this.popData.reportId=e.Id
      this.popData.theme=e.Abstract
      this.getAllCustomEmail()
      this.getReportVarietyOpts()
      this.popData.show=true
    },

    // 获取该报告对应的品种权限数据
    getReportVarietyOpts(){
      reportVarietyENInterence.varietyList({
        ReportId:this.popData.reportId
      }).then(res=>{
        if(res.Ret===200){
          const arr=res.Data||[]
          this.popData.varietyOpt=arr.filter(e=>{
            e.Child&&e.Child.forEach(_e=>delete _e.Child)
            return e.Child&&e.Child.length>0
          })
          // 设置全部选中
          this.popData.varietyOpt.forEach(e=>{
            e.Child.forEach(_e=>{
              this.popData.varietyVal.push([e.EnPermissionId,_e.EnPermissionId])
            })
          })
        }
      })
    },

    /* 查看群发日志 */
    goSendlog({Id}) {
      this.$router.push({
        path: '/sendlog',
        query: { id: Id }
      })
    },

    // 获取所有邮件客户
    async getAllCustomEmail(){
      const res=await reportEnInterface.customEmailList({
        CurrentIndex:1,
        PageSize:10000,
        ListParam:4,
        SortType:1,
        SortParam:3
      })
      if(res.Ret===200){
        const arr=res.Data.List||[]
        this.popData.options=arr
      }
    },

    handleDelSelectCustom(item,index){
      this.popData.value.splice(index,1)
    },

    showPVDetail(item){
      this.PVData.reportId=item.Id
      this.getPVDetail()
      this.PVData.show=true
    },

    async getPVDetail(){
      const res=await reportEnInterface.PVDetailList({
        CurrentIndex:this.PVData.page,
        PageSize:this.PVData.pageSize,
        ReportId:this.PVData.reportId
      })
      if(res.Ret===200){
        this.PVData.list=res.Data.List||[]
        this.PVData.total=res.Data.Paging.Totals
      }
    },
    handlePVPageChange(e){
      this.PVData.page=e
      this.getPVDetail()
    },

    handleConfirmSendEmail(){
      let ids=[]
      this.popData.value.forEach(item=>{
        ids.push(item.Id)
      })
      if(this.popData.checkUser&&ids.length===0){//指定人员
        this.$message.warning('请选择需要发送邮件的人员')
        return
      }
      if(!this.popData.checkUser){
        ids=[]
      }

      if(!this.popData.theme){
        this.$message.warning('请填写邮件主题')
        return
      }
      if(this.popData.theme.length>100){
        this.$message.warning('邮件主题请控制在100个字符以内')
        return
      }
      const arr=[]
      this.popData.varietyVal&&this.popData.varietyVal.forEach(_e => {
        arr.push(_e[1])
      });
      reportEnInterface.sendCustomEmail({
        ReportId:this.popData.reportId,
        EmailIds:ids.join(','),
        Theme:this.popData.theme,
        EnPermissions:arr
      }).then(res=>{
        if(res.Ret===200){
          this.$message.success('发送成功')
          this.popData.show=false
          this.getTableData();
        }
      })
    },

    //获取报告
    async handlePullReport(){
      this.isPull=true
      const res=await strategyReportInterence.getStrategyReport({})
      setTimeout(() => {
        this.isPull=false
      }, 500);
      if(res.Ret===200){
        this.$message.success('同步成功')
        this.getTableData();
      }
    },
  },
};
</script>

<style lang="scss">
.download-audio-wrap {
  .el-checkbox__label {
    white-space: normal;
  }
}
.send-email-wrap{
  .el-input{
    width: 100%;
  }
}
</style>
<style scoped lang="scss">
#reportlist {
  overflow: hidden;
  .header .el-form-item {
    margin-bottom: 0;
  }
  .opt-btns {
    span,
    a {
      display: inline-block;
      margin: 0 3px;
    }
  }
  .warn-tag { 
    width: 6px;
    height:6px;
    border-radius: 50%;
    background: #f00;
    display: inline-block;
    position: absolute;
    right: -10px;
    top: 30%;
  }
}
.send-email-wrap{
  .user-box{
    border: 1px dashed #DCDFE6;
    border-radius: 4px;
    padding: 20px;
    margin-top: 20px;
    .box{
      max-height: 200px;
      overflow-y: auto;
    }
  }
}
</style>
