import { ref } from 'vue'
import { router } from '@/router'
import {Base64} from 'js-base64'
import apiReport from '@/api/report'
import {getSystemInfo} from '@/api/common'
import { showToast,showDialog } from 'vant'
import _ from 'lodash'
import {reportManageBtn,useAuthBtn} from '@/hooks/useAuthBtn'
import {usePublicSettingStore} from '@/store/modules/publicSetting'

const publicSettingStore = usePublicSettingStore()
const { checkAuthBtn } = useAuthBtn()


/* 报告操作 */
export function useReportHandles() {
	
	// 水印
	const waterMarkStr=ref('')
	function getSystemInfoFun() {
			getSystemInfo().then(res=>{
					if(res.Ret===200){
						const systemUserInfo=res.Data
						// 设置水印文案
						let waterMarkString=''
						if(systemUserInfo){
							waterMarkString=`${systemUserInfo.RealName}${systemUserInfo.Mobile?systemUserInfo.Mobile:systemUserInfo.Email}`
							waterMarkString=encodeURIComponent(waterMarkString)
							waterMarkStr.value=Base64.encode(waterMarkString)
						}
					}
			})
	}
	getSystemInfoFun()


  // 刷新所有图表和表格
  const handleRefresh = _.debounce (async function({id,chapterId}) {
    let code_arr = [];
    let sheet_code_arr = []
    $('iframe').each((k,i) => {
        try {
            let href = $(i).attr('src');
            if(href.includes('chartshow')){
                code_arr.push(getUrlParams(href,'code'));
            }
            if(href.includes('sheetshow')){
                sheet_code_arr.push(getUrlParams(href,'code'))
            }
        } catch (err) {
        }
    });

    if(!code_arr.length&&!sheet_code_arr.length) return showToast('请插入图表');

    if(id&&code_arr.length) {
        let res = await apiReport.getChartRefreshStatus({
            Source: 'report',
            PrimaryId:id,
            SubId: chapterId
        });
        
        if(!res.Data.RefreshResult) return showToast('图表正在刷新中，请勿重复操作')

        const { Ret,Msg } = await apiReport.reportChartRefresh({
            ChartInfoCode: code_arr,
            Source: 'report',
            PrimaryId: id,
            SubId: chapterId
        })
        
        if(Ret === 200) {
            $('iframe').each((k,i) => {
                let href = $(i).attr('src');
                if(href.includes('chartshow')){
                    $(i).attr('src',$(i).attr('src'))
                }
            });
            showToast(Msg);
        }
    }
    if(id&&sheet_code_arr.length){
        //获取刷新结果
        let res = await apiReport.getSheetRefreshResult({
            Source: 'report',
            PrimaryId: id,
            SubId: chapterId
        });
        if(!res.Data.RefreshResult) return showToast('表格正在刷新中，请勿重复操作')
        const { Ret,Msg } = await apiReport.reportSheetRefresh({
            ExcelCodes: sheet_code_arr,
            Source: 'report',
            PrimaryId: id,
            SubId: chapterId
        })
        
        if(Ret === 200) {
            $('iframe').each((k,i) => {
                let href = $(i).attr('src');
                if(href.includes('sheetshow')){
                    $(i).attr('src',$(i).attr('src'))
                }
            });
            showToast(Msg);
        }
    }

  },1000)


  /* 提交报告进入审批流 */
  function handleSubmitReport({id}) {
    showDialog({
        title: '提示',
        message: '是否确认提交该报告进入审批流程?',
        showCancelButton:true
    }).then(()=>{
        apiReport.reportCnSubmit({
            ReportId: id
        }).then(res=>{
            if(res.Ret!==200) return 
            showToast('提交成功')
            router.back()
        })
    }).catch(()=>{})
  }


	const isPost = checkAuthBtn(reportManageBtn.reportManage_sendMsg)
	//发布 定时 提交
	async function handlePublishReportHook(tp,reportInfo) {

		if(tp==='dsfb'){
				showDSFBTime.value=true
		return
		}else if(tp==='submit'){
				handleSubmitReport({id:Number(reportInfo.Id)})
				return
		}

		let sendMsg = reportInfo.MsgIsSend;
		if(sendMsg===1){
				reportPublish({
						sendMsg: false,
						reportInfo
				})
		}else {

				showDialog({
						title: '发布提示',
						showCancelButton: true,
						message: isPost?'发布后，是否推送模板消息？':'是否立即发布报告？',
						confirmButtonText: isPost?'推送':'发布',
						cancelButtonText: isPost?'不推送':'取消',
						closeOnClickOverlay: true    
				}).then(() => {
						reportPublish({
								sendMsg: isPost?true:false,
								reportInfo
						})
				})
				.catch(() => {
						if(isPost) reportPublish({
								sendMsg: false,
								reportInfo
						});
				});

		}
	}

	/* 发布报告 */
	async function reportPublish({sendMsg,reportInfo}){
			const res=await apiReport.reportPublish({ReportIds:String(reportInfo.Id),ReportUrl:generatePdfLinks(reportInfo)})
			if(res.Ret===200){
					sendMsg && apiReport.reportMessageSend({ReportId: Number(reportInfo.Id)})

					showToast('发布成功')
					setTimeout(() => {
							router.back()
					},1000)
			}
	}


	//定时发布
	const showDSFBTime = ref(false)
	function handleDSPublish(time,reportInfo) {
		if(reportInfo.MsgIsSend===1){//已经推送过了
			apiReport.reportPublishTimeSet({
					ReportId:reportInfo.Id,
					PrePublishTime:time,
					PreMsgSend:0,
					ReportUrl:generatePdfLinks(reportInfo)
			}).then(res=>{
					if(res.Ret===200){
							showToast('定时发布成功！')
							setTimeout(() => {
									router.back()
							}, 1000);
					}
			})
			return
		}

		showDialog({
				title: '提示',
				message:isPost?'是否发布定时报告，并推送模板消息？':'是否发布定时报告',
				confirmButtonText:isPost?'推送':'确定',
				cancelButtonText:isPost?'不推送':'取消',
				showCancelButton:true
		}).then(()=>{
				if(!isPost){
						apiReport.reportPublishTimeSet({
								ReportId:reportInfo.Id,
								PrePublishTime:time,
								PreMsgSend:0,
								ReportUrl:generatePdfLinks(reportInfo)
						}).then(res=>{
								if(res.Ret===200){
										showToast('定时发布成功！')
										setTimeout(() => {
												router.back()
										}, 1000);
								}
						})
						return
				}
				//推送
				apiReport.reportPublishTimeSet({
						ReportId:reportInfo.Id,
						PrePublishTime:time,
						PreMsgSend:1,
						ReportUrl:generatePdfLinks(reportInfo)
				}).then(res=>{
						if(res.Ret===200){
								showToast('定时发布成功！')
								setTimeout(() => {
										router.back()
								}, 1000);
						}
				})
		}).catch(()=>{
				if(!isPost) return
				//不推送
				apiReport.reportPublishTimeSet({
						ReportId:reportInfo.Id,
						PrePublishTime:time,
						PreMsgSend:0,
						ReportUrl:generatePdfLinks(reportInfo)
				}).then(res=>{
						if(res.Ret===200){
								showToast('定时发布成功！')
								setTimeout(() => {
										router.back()
								}, 1000);
						}
				})
		})
	}

	function generatePdfLinks(reportInfo){
			let code = reportInfo.ReportCode

			return `${publicSettingStore.publicSetting.ReportViewUrl}/reportshare_pdf?code=${code}&flag=${waterMarkStr.value}`
	}
  

  return {
    handleRefresh,
		handleDSPublish,
		showDSFBTime,
		handlePublishReportHook
  }
}


/* 章节报告操作 */
export function useChapterRepoprtHandles() {

	//提交章节
	async function handlePublishChapterApi(chapterId) {
		const res = await apiReport.chapterReportPublish({
			ReportChapterId: chapterId
		});

		if (res.Ret !== 200) return
		showToast('提交成功')
		router.back()
	}

	return {
		handlePublishChapterApi
	}
}


/* 获取地址栏参数值 */
function getUrlParams(str=window.location.href,key) {
  let obj = {};
	str.split('?')[1].split('&').map(i => obj[(i.split('=')[0])] = i.split('=')[1]);

  return obj[key]
}