<!-- 新增爬虫 -->
<template>
    <el-dialog :title="dialogTitle" v-model="dialogVisible" :close-on-click-modal="false" width="80%">
        <template #header="{ titleId, titleClass }">
            <div class="edit-css-header">
                <div class="header-left">
                    <span :id="titleId" :class="titleClass">{{ dialogTitle }}</span>
                </div>
                <div class="mark-container">
                    <el-button-group class="mark-buttons">
                        <el-button type="primary" :icon="Link" @click="handleDataTag">标注</el-button>
                    </el-button-group>
                    <!-- <div class="rollback-reason-container" v-if="formData.reason">
                        <span class="rollback-reason-label">打回原因：</span>
                        <span class="rollback-reason-value">{{ formData.reason }}</span>
                    </div> -->
                    <el-tag type="danger" v-if="formData.reason">打回原因：{{ formData.reason }} </el-tag>
                </div>
            </div>
        </template>
        <div class="flex gap-2">
            <el-space class="edit-tag-list">
                <el-tag class="edit-tag" type="primary">{{ formData.site }} </el-tag>
                <el-tag class="edit-tag" type="success">{{ formData.channel }} </el-tag>
                <el-tag class="edit-tag" type="info">{{ formData.code }} </el-tag>
                <el-tag class="edit-tag" type="warning">{{ formData.href }} </el-tag>
                <el-tag class="edit-tag" type="danger">{{ formData.modifyuser }} </el-tag>
            </el-space>
        </div>
        <div class="space" />
        <el-form ref="form0" label-width="160px">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="列表页延迟时间(MS)">
                        <el-input v-model="formData.listDelayTime" placeholder="500"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="列表翻页延迟时间(MS)">
                        <el-input v-model="formData.listTurnDelayTime" placeholder="500"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="详情页延迟时间(MS)">
                        <el-input v-model="formData.contentDelayTime" placeholder="500"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="采集最大页数">
                        <el-input v-model="formData.maxPages" :placeholder="defaultFormValue.maxPages + ''"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        
        <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane label="列表页CSS选择器" name="first">
                <el-form ref="form1" :model="formData" label-width="160px">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="条目区域块">
                                <el-input v-model="formData.listBodyCss" @input="onCssFormChange" placeholder="div"></el-input>
                                <div class="form-item-sub-line">{{ fastKeyDownMap.listBodyCss }}</div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="条目">
                                <el-input v-model="formData.listItemCss" @input="onCssFormChange" placeholder="ul.list li" :style="{ background: cssInputBg.listItemCss.color }"></el-input>
                                <div class="form-item-sub-line">{{ fastKeyDownMap.listItemCss }}</div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="条目链接">
                                <el-input v-model="formData.listLinkCss" @input="onCssFormChange" placeholder="a" :style="{ background: cssInputBg.listLinkCss.color }"></el-input>
                                <div class="form-item-sub-line">{{ fastKeyDownMap.listLinkCss }}</div>
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="条目发布时间">
                                <el-input v-model="formData.listPublishTimeCss" @input="onCssFormChange" placeholder="span" :style="{ background: cssInputBg.listPublishTimeCss.color }"></el-input>
                                <div class="form-item-sub-line">{{ fastKeyDownMap.listPublishTimeCss }}</div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="翻页下一页">
                                <el-input v-model="formData.listNextPageCss" @input="onCssFormChange" placeholder="li.nextpage a" :style="{ background: cssInputBg.listNextPageCss.color }"></el-input>
                                <div class="form-item-sub-line">{{ fastKeyDownMap.listNextPageCss }}</div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-tab-pane>

            <el-tab-pane label="详情页CSS选择器" name="content">
                <el-form ref="form2" :model="formData" label-width="160px">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="详情页标题">
                                <el-input v-model="formData.titleCss" @input="onCssFormChange" placeholder="ul.list li" :style="{ background: cssInputBg.titleCss.color }"></el-input>
                                <div class="form-item-sub-line">{{ fastKeyDownMap.titleCss }}</div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="详情页发布时间">
                                <el-input v-model="formData.publishTimeCss" @input="onCssFormChange" placeholder="a" :style="{ background: cssInputBg.publishTimeCss.color }"></el-input>
                                <div class="form-item-sub-line">{{ fastKeyDownMap.publishTimeCss }}</div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="详情页发布单位">
                                <el-input v-model="formData.publishUnitCss" @input="onCssFormChange" placeholder="span" :style="{ background: cssInputBg.publishUnitCss.color }"></el-input>
                                <div class="form-item-sub-line">{{ fastKeyDownMap.publishUnitCss }}</div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="详情页正文">
                                <el-input v-model="formData.contentCss" @input="onCssFormChange" placeholder="li.nextpage a" :style="{ background: cssInputBg.contentCss.color }"></el-input>
                                <div class="form-item-sub-line">{{ fastKeyDownMap.contentCss }}</div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="详情页附件">
                                <el-input v-model="formData.attachCss" @input="onCssFormChange" placeholder="span" :style="{ background: cssInputBg.attachCss.color }"></el-input>
                                <div class="form-item-sub-line">{{ fastKeyDownMap.attachCss }}</div>
                            </el-form-item>
                        </el-col>

                    </el-row>
                </el-form>
            </el-tab-pane>
            <el-tab-pane label="列表页JS代码" name="list_item_js">
                <template #label><span class="custom-tabs-label">
                        <el-icon>
                            <ElementPlus />
                        </el-icon>
                        <span>列表页JS代码</span>
                    </span>
                </template>
                <el-divider>
                    手写列表页提取JS代码
                    <!-- <el-button type="primary" @click='editorHandle.ImportListCode'>导入模板</el-button> -->
                    <el-button type="primary" @click='editorHandle.createImportListCode'>生成JS代码</el-button>
                </el-divider>
                <el-row>
                    <el-input v-model="formData.listJs" class="codeEditor" :rows="6" type="textarea"
                        placeholder="Please input" />
                </el-row>
            </el-tab-pane>
            <el-tab-pane label="列表页翻页JS代码" name="list_trunpage_js">

                <template #label><span class="custom-tabs-label">
                        <el-icon>
                            <ElementPlus />
                        </el-icon>
                        <span>列表页翻页JS代码</span>
                    </span>
                </template>
                <el-divider>
                    手写列表页翻页JS代码
                    <!-- <el-button type="primary" @click='editorHandle.ImportListTrunPageCode'>导入模板</el-button> -->
                    <el-button type="primary" @click='editorHandle.createImportListTrunPageCode'>生成JS代码</el-button>
                </el-divider>
                <el-row>
                    <el-input v-model="formData.listTurnPageJs" class="codeEditor" :rows="6" type="textarea"
                        placeholder="Please input" />
                </el-row>
            </el-tab-pane>

            <el-tab-pane label="详情页JS代码" name="content_js">

                <template #label><span class="custom-tabs-label">
                        <el-icon>
                            <ElementPlus />
                        </el-icon>
                        <span>详情页JS代码</span>
                    </span>
                </template>
                <el-divider>
                    手写附件下载/上传JS代码
                    <!-- <el-button type="primary" @click='editorHandle.ImportContentCode'>导入模板</el-button> -->
                    <el-button type="primary" @click='editorHandle.createImportContentCode'>生成样例</el-button>
                </el-divider>
                <el-row><el-input v-model="formData.contentJs" class="codeEditor" :rows="6" type="textarea"
                        placeholder="Please input" />
                </el-row>
            </el-tab-pane>
        </el-tabs>
        <div slot="footer" class="dialog-footer" style="text-align:right">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" :disabled="savaButtonDisabled" @click="handleSave">保 存</el-button>
        </div>
    </el-dialog>
</template>
<script setup>
import { ref, defineEmits, computed } from 'vue';
import { TemplateJsCode } from './jscodetpl.js'
import { Link } from '@element-plus/icons-vue'
import { useStore } from 'vuex'
import { USER_ROLE_ADMIN, USER_ROLE_DEVELOPER, USER_ROLE_REVIEWER } from '../../data/user'
import { ServerActionCurrentOpenTab } from "../../../wailsjs/go/main/App"
const emit = defineEmits(['custom-event', 'data-tag', 'form-change']);
let originData = {}

const dialogTitle = ref('仅编辑 CSS选择器部分')

const store = useStore()

const defaultFormValue = {
    delayTime: 500,
    maxPages: 2,
}
//表单数据
const formData = ref({
    site: '',
    channel: '',
    href: '',
    code: '',
    modifyuser: '',

    // 审核不通过原因
    reason: '',
    // 爬虫状态
    state: 0,

    // list-css-tab
    listBodyCss: '',
    listItemCss: '',
    listLinkCss: '',
    listPublishTimeCss: '',
    listNextPageCss: '',
    listDelayTime: '',

    // content-css-tab
    titleCss: '',
    publishTimeCss: '',
    publishUnitCss: '',
    contentCss: '',
    attachCss: '',
    contentDelayTime: '',

    // list-js-tab
    listJs: '',

    // list-pageination-tab
    listTurnPageJs: '',
    listTurnDelayTime: '',

    // detail-js-tab
    contentJs: '',

    maxPages: '',
});

// 快捷键map
const fastKeyDownMap = {
    // list
    listBodyCss: 'ctrl+2',
    listItemCss: 'ctrl+3',
    listLinkCss: 'ctrl+4',
    listPublishTimeCss: 'ctrl+5',
    listNextPageCss: 'ctrl+6',
    // content
    titleCss: 'ctrl+alt+3',
    publishTimeCss: 'ctrl+alt+4',
    publishUnitCss: 'ctrl+alt+5',
    contentCss: 'ctrl+alt+6',
    attachCss: 'ctrl+alt+7',
}
// 背景色map
const cssInputBg = {
  listItemCss: { color: "#fff9c4", label: "列表条目", formLabel: '条目区域块CSS' },
  listLinkCss: { color: "#bbdefb", label: "列表标题", formLabel: '条目链接CSS' },
  listPublishTimeCss: { color: "#c8e6c9", label: "列表发布时间", formLabel: '条目发布时间CSS' },
  listNextPageCss: { color: "#dcedc8", label: "列表下一页", formLabel: '翻页下一页CSS' },
  titleCss: { color: "#e7f3fe", label: "文章标题", formLabel: '详情页标题CSS' },
  publishTimeCss: { color: "#ffe0b2", label: "文章发布时间", formLabel: '详情页发布时间CSS' },
  publishUnitCss: { color: "#ffe1e1", label: "文章发布单位", formLabel: '详情页发布单位CSS' },
  contentCss: { color: "#e0f7fa", label: "文章正文", formLabel: '详情页正文CSS' },
  attachCss: { color: "#fff1e5", label: "文章附件", formLabel: '详情页附件CSS' },
}

const activeName = ref("first")
const dialogVisible = ref(false)

// 用户身份标识
const userRole = computed(() => store.getters.userRole)
const isDeveloper = computed(() => [USER_ROLE_DEVELOPER].includes(userRole.value))

// 待完成和未通过的爬虫可以保存，其他都不可以提交(并禁用保存按钮)
const canSubmitStatusArr = [0, 2]
const canSubmit = computed(() => canSubmitStatusArr.includes(formData.value.state))
const savaButtonDisabled = computed(() => !canSubmit.value)

//编辑器事件管理
const editorHandle = {
    ImportListCode: () => {
        formData.value.listJs = TemplateJsCode.ListJsCode
    },
    ImportContentCode: () => {
        formData.value.contentJs = TemplateJsCode.ContentJsCode
    },
    ImportAttachCode: () => {
        formData.value.attachJs = TemplateJsCode.AttachJsCode
    },
    ImportListTrunPageCode:()=>{
        formData.value.listTurnPageJs=TemplateJsCode.ListTurnPageJsCode
    },
    createImportListCode() {
        // 数据替换
        const originString = TemplateJsCode.ListJsCode
        let replaceString = originString
        if (formData.value.listItemCss) {
            replaceString = replaceString.replaceAll('{{.ListItemCss}}', formData.value.listItemCss)
        } else {
            replaceString = replaceString.replaceAll('{{.ListItemCss}}', cssInputBg.listItemCss.formLabel)
        }
        if (formData.value.listLinkCss) {
            replaceString = replaceString.replaceAll('{{.ListLinkCss}}', formData.value.listLinkCss)
        } else {
            replaceString = replaceString.replaceAll('{{.ListLinkCss}}', cssInputBg.listLinkCss.formLabel)
        }
        if (formData.value.listPublishTimeCss) {
            replaceString = replaceString.replaceAll('{{.ListPubtimeCss}}', formData.value.listPublishTimeCss)
        } else {
            replaceString = replaceString.replaceAll('{{.ListPubtimeCss}}', cssInputBg.listPublishTimeCss.formLabel)
        }
        formData.value.listJs = replaceString
        return replaceString
    },
    createImportContentCode() {
        const originString = TemplateJsCode.ContentJsCode
        let replaceString = originString
        if (formData.value.titleCss) {
            replaceString = replaceString.replaceAll('{{.TitleCss}}', formData.value.titleCss)
        } else {
            replaceString = replaceString.replaceAll('{{.TitleCss}}', cssInputBg.titleCss.formLabel)
        }
        if (formData.value.publishUnitCss) {
            replaceString = replaceString.replaceAll('{{.PublishUnitCss}}', formData.value.publishUnitCss)
        } else {
            replaceString = replaceString.replaceAll('{{.PublishUnitCss}}', cssInputBg.publishUnitCss.formLabel)
        }
        if (formData.value.publishTimeCss) {
            replaceString = replaceString.replaceAll('{{.PublishTimeCss}}', formData.value.publishTimeCss)
        } else {
            replaceString = replaceString.replaceAll('{{.PublishTimeCss}}', cssInputBg.publishTimeCss.formLabel)
        }
        if (formData.value.contentCss) {
            replaceString = replaceString.replaceAll('{{.ContentCss}}', formData.value.contentCss)
        } else {
            replaceString = replaceString.replaceAll('{{.ContentCss}}', cssInputBg.contentCss.formLabel)
        }
        if (formData.value.attachCss) {
            replaceString = replaceString.replaceAll('{{.AttachCss}}', formData.value.attachCss)
        } else {
            replaceString = replaceString.replaceAll('{{.AttachCss}}', cssInputBg.attachCss.formLabel)
        }
        formData.value.contentJs = replaceString
    },
    createImportListTrunPageCode() {
        const originString = TemplateJsCode.ListTurnPageJsCode
        let replaceString = originString
        if (formData.value.listNextPageCss) {
            replaceString = replaceString.replaceAll('{{.ListNextPageCss}}', formData.value.listNextPageCss)
        } else {
            replaceString = replaceString.replaceAll('{{.ListNextPageCss}}', cssInputBg.listNextPageCss.formLabel)
        }
        formData.value.listTurnPageJs = replaceString
        return replaceString
    }
}

const setPageData = (row) => {
    if (!row) return
    formData.value = row
    // 保存一份原始数据
    originData = JSON.parse(JSON.stringify(row))
}
const refreshPageData = (key, value) => {
    if (!key) return
    formData.value[key] = value
}

const getPageData = () => {
    const formDataValue = formData.value
    const payload = {
      // list-css
      listBodyCss: formDataValue.listBodyCss || '',
      listItemCss: formDataValue.listItemCss || '',
      listLinkCss: formDataValue.listLinkCss || '',
      listPublishTimeCss: formDataValue.listPublishTimeCss || '',
      listNextPageCss: formDataValue.listNextPageCss || '',
      listDelayTime: Number(formData.value.listDelayTime || defaultFormValue.delayTime),
      // content-css
      titleCss: formDataValue.titleCss || '',
      publishTimeCss: formDataValue.publishTimeCss || '',
      publishUnitCss: formDataValue.publishUnitCss || '',
      contentCss: formDataValue.contentCss || '',
      attachCss: formDataValue.attachCss || '',
      contentDelayTime: Number(formDataValue.contentDelayTime || defaultFormValue.delayTime),
      // js-list
      listJs: formDataValue.listJs || '',
      // js_nextpage
      listTurnPageJs: formDataValue.listTurnPageJs || '',
      listTurnDelayTime: Number(formDataValue.listTurnDelayTime || defaultFormValue.delayTime),
      // js_content
      contentJs: formDataValue.contentJs || '',

      maxPages: Number(formDataValue.maxPages || defaultFormValue.maxPages)
    }

    return {
        _originData: originData,
        value: payload
    }
}

const handleSave = () => {
    // dialogVisible.value = false;
    const payload = getPageData()
    emit("custom-event", payload)
    // formData.value = {}
}

const handleDataTag = () => {
    emit('data-tag', originData)
}

// 根据编辑弹窗的内容，获取cssMark
const getMarkWithEditDialogInfo = info => {
    const { value, _originData } = info
    const baseInfo = {
        code: _originData.code,
        site: _originData.site,
        channel: _originData.channel,
        href: _originData.href,
        modifyuser: _originData.modifyuser,
    }
    return {
        ...value,
        ...baseInfo,
    }
}

const onEditFormChange = (info) => {
    const mark = getMarkWithEditDialogInfo(info)
    ServerActionCurrentOpenTab(mark)
}

const onCssFormChange = () => {
    const payload = getPageData()
    onEditFormChange(payload)
}

//这里是重点: 向外部组建暴露可供调用的方法
defineExpose({
    dialogVisible,
    formData,
    setPageData,
    getPageData,
    refreshPageData,
    emit
})
</script>
<style scoped lang="scss">
::v-deep {
    .el-form-item {
        margin-bottom: 10px;
    }
    .el-input__wrapper {
        background-color: transparent;
    }
}

.codeEditor {
    width: 100%;
    font-size: 12pt;
    font-weight: bold;
    line-height: 1.5em;
    padding: 10px;
}
.edit-tag-list {
    flex-wrap: wrap;
}
.edit-tag {
    margin-bottom: 4px;
}
.edit-css-header {
    display: flex;
}
.mark-container {
    display: flex;
    align-items: center;
    flex: 1;
    margin-left: 10px;
}
.mark-buttons {
    margin: 0 10px;
}
.form-item-sub-line {
    line-height: 24px;
    color: var(--el-color-primary);
}
.rollback-reason-container {
    color: var(--el-color-danger);
}
</style>