import * as sheetInterface from '@/api/modules/sheetApi.js';
import { dataBaseInterface } from '@/api/api.js';
import futuresInterface from '@/api/modules/futuresBaseApi';
import chartRelevanceApi from '@/api/modules/chartRelevanceApi';
import { fittingEquationInterface,statisticFeatureInterface } from '@/api/modules/chartRelevanceApi';
export default {
  data() {
    let that = this;
    return {
      editor: null,
      froalaConfig: {
				toolbarButtons: [
					'insertImage',
					'insertVideo',
					'insertLink',
					'embedly',
					'insertFile',
					'textColor',
					'bold',
					'italic',
					'underline',
					'strikeThrough',
					'subscript',
					'superscript',
					'fontFamily',
					'fontSize',
					'color',
					'inlineClass',
					'inlineStyle',
					'paragraphStyle',
					'lineHeight',
					'paragraphFormat',
					'align',
					'formatOL',
					'formatUL',
					'outdent',
					'indent',
					'quote',
					'insertTable',
					'emoticons',
					'fontAwesome',
					'specialCharacters',
					'insertHR',
					'selectAll',
					'clearFormatting',
					'html',
					'undo',
					'redo',
				],
				height: 800,
				fontSize: [
					'12',
					'14',
					'16',
					'18',
					'20',
					'24',
					'28',
					'32',
					'36',
					'40',
				],
				fontSizeDefaultSelection: '16',
				theme: 'dark', //主题
				placeholderText: '请输入内容',
				language: 'zh_cn', //国际化
				imageUploadURL: process.env.API_ROOT + '/report/uploadImg', //上传url
				videoUploadURL: process.env.API_ROOT + '/report/uploadImg', //上传url
				fileUploadURL: process.env.API_ROOT + '/report/uploadImg', //上传url 更多上传介绍 请访问https://www.froala.com/wysiwyg-editor/docs/options
				imageDefaultWidth: false,
				quickInsertButtons: ['image', 'table', 'ul', 'ol', 'hr'], //快速插入项
				toolbarVisibleWithoutSelection: true, //是否开启 不选中模式
				// disableRightClick:true,//是否屏蔽右击
				// colorsHEXInput:false,//关闭16进制色值
				toolbarSticky: false, //操作栏是否自动吸顶
				// zIndex:99999,
				saveInterval: 0,
				/* 				saveParam: 'content',
			saveURL: process.env.API_ROOT+'/report/saveReportContent',
			saveMethod: 'POST',
			saveParams: {}, */
				events: {
					// 'froalaEditor.initialized':function(){
					//   console.log('initialized', this);
					// },
					//this.editor 定义在vue data 中
					initialized: function () {
						// this.editor = editor;
						that.editor = this;
						// that.editor.html.set(that.value);
						// that.setHtml()
					},
					keyup: function (e, editor) {
						//添加事件，在每次按键按下时，都记录一下最后停留位置
						that.$nextTick(function () {
							getSelection().rangeCount&&(that.lastEditRange = getSelection().getRangeAt(0));
						});
					},
					click: function (e, editor) {
						//添加事件，在每次鼠标点击时，都记录一下最后停留位置
						that.$nextTick(function () {
							getSelection().rangeCount&&(that.lastEditRange = getSelection().getRangeAt(0));
						});
					},
					//内容改变事件
					contentChanged: function () {
						that.ischange = true;
						that.lastEditRange = getSelection().rangeCount?getSelection().getRangeAt(0):0;
					},
					//粘贴图片上传事件
					'image.beforePasteUpload':function(img){
						//console.log('image.beforePasteUpload',img)
						//暂停自动保存
						that.autoSaveFlag = false
						
					},
					//点击toolbar上传图片事件
					'image.beforeUpload':function(imgs){
						//console.log('image.beforeUpload',imgs)
						//暂停自动保存
						that.autoSaveFlag = false
						
					},
					'image.inserted':function($img,response){
						//console.log('img-inserted',$img)
						//开启自动保存
						that.autoSaveFlag = true
					},
					//如果上传图片出错,重置autoSaveFlag
					'image.error':function(error,response){
						that.autoSaveFlag = true
					}
				},
				charCounterCount: false,
				reportloadding: false,
				lastsavetime: '',
				isAddEnter: false, //是否已经添加过
				timer: null,
				ischange: false,
				isPublishloading: false,
			},
      panelTabs:['基础信息','图表插入','MyETA批量插入','表格插入','沙盘插入'],

      sheetSearchObj: {

      },
      sheetSearchList:[],

      setEnName:false,
      // 传入的formItem所需内容
      formItemArray:{},
			
			search_page: 1,
			search_page_sizes: 20,
			search_have_more: true,

			chart_source: 1,//图表来源 1 eta 2 商品价格

			//截面散点设置英文props
			enChartInfo: {},
			enEdblist:[],
			
			isShowMe: false,
			autoSaveFlag:true,//是否开启自动保存
    }
  },

  methods: {
    insertHtml(item,type='chart') {
			//设置编辑器获取焦点
			this.editor.events.focus();
			// 获取选定对象
			const selection = getSelection();
			// 判断是否有最后光标对象存在
			if (this.lastEditRange) {
				// 存在最后光标对象，选定对象清除所有光标并添加最后光标还原之前的状态
				selection.removeAllRanges();
				selection.addRange(this.lastEditRange);

			}

      const insertMap = {
        'image': this.insertImage,
        'chart': this.insertChart,
        'sheet': this.insertSheet
      }
      insertMap[type](item);
			this.lastEditRange = selection.getRangeAt(0);
		},

    /* 插入图片 */
    insertImage(item) {
      this.$nextTick(() => {
        this.editor.html.insert(
        `<img style='width:100%' src='${item.PicUrl}' />`)
      })
			
    },

    /* 插入图表 */
    insertChart(item) {
			if(item.Disabled) return this.$message.warning('内部图表，不允许插入报告') 
			
      const LINK_CHART_URL = process.env.NODE_ENV === "production" ? 'https://chartlib.hzinsights.com/chartshow' : 'https://charttest.hzinsights.com/chartshow';
			let fromPage = this.$route.path === '/reportEnEditor' ? 'en' :'';
			this.$nextTick(() => {
					this.editor.html.insert(
					`<p style='text-align:left; margin-top:10px;'>
						<iframe src='${LINK_CHART_URL}?code=${item.UniqueCode}&fromPage=${fromPage}' width='100%' height='350' style='border-width:0px; min-height:350px;'></iframe>
					</p>`)
			})
    },

    /* 插入表格 */
    insertSheet(item) {
      const LINK_URL = process.env.NODE_ENV === "production" ? 'https://chartlib.hzinsights.com/sheetshow' : 'https://charttest.hzinsights.com/sheetshow';
      this.$nextTick(() => {
          this.editor.html.insert(
          `<p style='text-align:left; margin-top:10px;'>
            <iframe 
              src='${LINK_URL}?code=${item.UniqueCode}' 
              width='100%' 
              class='iframe${item.UniqueCode}' 
              style='border-width:0px;'
              />
              </p>`)
      })
    },

    /* 适配iframe高度 */
    reInitIframe(e) {
      const { height,code } = e.data;
      let iframeDom = document.getElementsByClassName(`iframe${code}`)
      iframeDom.forEach(ele => {
        ele.height = `${height+45}px`;
      });

    },

    /* 搜索表格 */
    getSheetList() {
      sheetInterface
        .sheetList({
          Keyword: this.sheetSearchObj.Keyword,
          CurrentIndex: 1,
          PageSize: 10000
        })
        .then((res) => {
          if (res.Ret !== 200) return
          this.sheetSearchList = res.Data.List || [];
        });
    },

		/* 设置英文配置 */
		async setEnHandle({UniqueCode}) {
			this.formItemArray={ chartInfo: [],chartsList: [] }

			const { Ret,Data } = await dataBaseInterface.getChartByCode({UniqueCode});
			
			if (Ret !== 200) return;
			let chartInfo = Data.ChartInfo;
			let tableData =  [2,5].includes(chartInfo.Source) ? [Data.EdbInfoList[0]] : Data.EdbInfoList;

			this.enChartInfo = chartInfo;
			this.enEdblist = tableData;

      this.formItemArray.chartInfo.push({
        label:'图表名称',
        value:chartInfo.ChartName,
        key:'ChartName',
        id:chartInfo.ChartInfoId,
        notEdit:true
      },
      {
        label:'英文图表名称',
        value:chartInfo.ChartNameEn,
        key:'ChartNameEn',
        id:chartInfo.ChartInfoId,
        placeholder:'请输入英文图表名称'
      })
	  	if(![3,6,7,8,9].includes(chartInfo.Source)){
				this.formItemArray.chartsList = tableData.map(item => {
					return item.Unit 
						? [
								{
									label:'指标名称',
									value:item.EdbName,
									key:'EdbName',
									id:item.EdbInfoId,
									notEdit:true
								},
								{
									label:'单位',
									value:item.Unit,
									key:'Unit',
									id:item.EdbInfoId,
									notEdit:true
								},
								{
									label:'英文指标名称',
									value:item.EdbNameEn,
									key:'EdbNameEn',
									id:item.EdbInfoId,
									placeholder:'请输入英文指标名称'
								},
								{
									label:'英文单位',
									value:item.UnitEn,
									key:'UnitEn',
									id:item.EdbInfoId,
									placeholder:'请输入英文单位'
								}
							]
						: [
								{
									label:'指标名称',
									value:item.EdbName,
									key:'EdbName',
									id:item.EdbInfoId,
									notEdit:true
								},
								{
									label:'英文指标名称',
									value:item.EdbNameEn,
									key:'EdbNameEn',
									id:item.EdbInfoId,
									placeholder:'请输入英文指标名称'
								}
							]
				}) 
			}

			//价格曲线
      if(chartInfo.Source===2) {
        this.formItemArray.chartInfo.push({
          label:'期货名称',
          value:Data.EdbInfoList[1].EdbName,
          key:'FutureGoodName',
          id:chartInfo.ChartInfoId,
          notEdit:true
        },
        {
          label:'英文期货名称',
          value:Data.EdbInfoList[1].EdbNameEn,
          key:'FutureGoodNameEn',
          id:chartInfo.ChartInfoId,
          placeholder:'请输入英文期货名称'
        })
      }

      //利润曲线
      if(chartInfo.Source===5) {
        this.formItemArray.chartInfo.push({
          label:'盘面利润名称',
          value:Data.DataResp.ProfitName,
          key:'ProfitName',
          id:chartInfo.ChartInfoId,
          notEdit:true
        },
        {
          label:'英文盘面利润名称',
          value:Data.DataResp.ProfitNameEn,
          key:'ProfitNameEn',
          id:chartInfo.ChartInfoId,
          placeholder:'请输入英文盘面利润名称'
        })
      }
      this.setEnName = true
		},

		// 更新英文信息
		async updateEnName(enNameData){

			let res=null
			if(this.chart_source === 1){
				res=await dataBaseInterface.chartInfoEditEn(enNameData)
			}else if([2,5].includes(this.chart_source)){
				res=await futuresInterface.editChartEn({
						ChartInfoId: enNameData.ChartInfoId,
						ChartNameEn: enNameData.ChartNameEn,
						UnitEn: enNameData.ChartEdbInfoList[0].UnitEn || '',
						EdbNameEn: enNameData.ChartEdbInfoList[0].EdbNameEn || '',
						FutureGoodNameEn: enNameData.FutureGoodNameEn || '',
            ProfitNameEn: enNameData.ProfitNameEn || ''
					})
			}else if(this.chart_source === 3){
				res=await chartRelevanceApi.editChartEn({
					ChartInfoId: enNameData.ChartInfoId,
					ChartNameEn: enNameData.ChartNameEn,
				})
			}else if(this.chart_source===6){//拟合方程
        res=await fittingEquationInterface.editChartEn({
          ChartInfoId: enNameData.ChartInfoId,
          ChartNameEn: enNameData.ChartNameEn
        })
			}else if(this.chart_source===7){//统计特征
        res=await statisticFeatureInterface.editChartEn({
          ChartInfoId: enNameData.ChartInfoId,
          ChartNameEn: enNameData.ChartNameEn
        })
      }
			
			if(res.Ret !==200) return

			this.$message({
				message:res.Msg,
				type:"success"
			})
			this.setEnName = false
		},

		/* 搜索图表分页 */
		async getreportlist(word) {
				let params = {
					Keyword: word || '',
					CurrentIndex: this.search_page,
					PageSize: this.search_page_sizes,
					IsShowMe: this.isShowMe
				}
				let res=null
				if(this.chart_source===1){
					res=await dataBaseInterface.chartSearchByEs(params)
				}else if(this.chart_source===2){
					res=await futuresInterface.searchChart(params)
				}else if(this.chart_source===3){
					res=await chartRelevanceApi.searchChart(params)
				}else if(this.chart_source===6){
					res=await fittingEquationInterface.searchChart(params)
				}else if(this.chart_source===7){
					res=await statisticFeatureInterface.searchChart(params)
				}

				if (res.Ret !== 200) return;
				res.Data.List = res.Data.List || [];
				this.newreportlist = this.search_page === 1 ? res.Data.List : [...this.newreportlist,...res.Data.List];
				this.search_have_more = this.search_page < res.Data.Paging.Pages;
		},

		loadReportHandle() {
			if(!this.search_have_more) return
			this.search_page++;
			this.getreportlist(this.key_word);
		},
  },
}