<template>
    <div class="page">

        <el-button class="backBtn" size="small" @click="$router.back()">返回上一级</el-button>
        <el-tabs v-model="tabs">
            <el-tab-pane label="设计问卷" name="1">
                <!-- 步骤1 填写问卷名称 -->
                <div style="width: 800px;margin: 100px auto;" v-show="step">
                    <el-form :model="titleForm" :rules="titleRules" ref="titleForm">
                        <el-form-item label="问卷名称：" prop="title" label-width="125px">
                            <el-input placeholder="请输入问卷名称" v-model="titleForm.title"></el-input>
                        </el-form-item>
                        <el-form-item label="问卷说明：" label-width="125px">
                            <el-input type="textarea" placeholder="请输入问卷说明（不超过1000个汉字）" maxlength="1000"
                                v-model="titleForm.remark"></el-input>
                        </el-form-item>
                        <div style="text-align: center;">
                            <el-button size="small" @click="$router.back()">取消</el-button>
                            <el-button type="primary" size="small" @click="createForm('titleForm')">立即{{ !editStyle ? '创建' :
                                '修改' }}</el-button>
                        </div>
                    </el-form>
                </div>
                <!-- 动态表单配置 -->
                <div v-show="!step">
                    <fc-designer style="height: 79vh;" ref="designer">
                        <template slot="handle">
                            <ElButton style="margin-left: 10px;" icon="el-icon-upload" type="primary" size="small"
                                @click="issueBtn" round>问卷配置发布
                            </ElButton>
                            <ElButton style="margin-left: 10px;" icon="el-icon-position" type="warning" size="small"
                                @click="outsideBtn" round>外部链接发布
                            </ElButton>
                            <ElButton icon="el-icon-view" type="success" size="small" @click="showDrawer" round>手机预览
                            </ElButton>
                        </template>
                    </fc-designer>
                </div>
                <!-- 手机模拟预览 -->
                <el-drawer :visible.sync="drawer" title="预览">
                    <div class="showPhone">
                        <div class="phone">
                            <div class="phoneContent">
                                <form-create :rule="Frule" :option="Fopthion" @submit="onSubmit">
                                </form-create>
                            </div>
                        </div>
                    </div>
                </el-drawer>
                <!-- 问卷发布弹出框 -->
                <el-dialog title="问卷发布" :visible.sync="issueDialog" width="30%" top="25vh">
                    <el-form :model="issueForm" :rules="issueRules" ref="issueForm">
                        <el-form-item label="链接地址：" label-width="125px" prop="webUrl" v-if="weblink">
                            <el-input v-model="issueForm.webUrl" placeholder="请输入链接地址"></el-input>
                        </el-form-item>
                        <el-form-item label="问卷封面：" label-width="125px">
                            <div style="display: flex;align-items: center;">
                                <img style="width:80px; height: 80px; margin-right: 10px;cursor: pointer;"
                                    v-for="(i, j) in coverImg" :key="j" :src="showImgUrl + '/' + i.url" alt=""
                                    :class="selImg == j ? 'selImg' : ''" @click="selImg = j">
                                <el-upload v-show="coverImg.length < 4" :action="ImgUrl + '/attendance/file/commonupload'"
                                    accept="image/jpeg,image/png,image/jpg" list-type="picture-card" class="upload"
                                    auto-upload="false" :show-file-list="false" :before-upload="beforeAvatarUploada"
                                    :on-success="handleUploadSuccess" :on-error="handleUploadError">
                                    <i class="el-icon-plus"></i>
                                </el-upload>
                            </div>

                        </el-form-item>
                        <el-form-item label="反馈期限：" label-width="125px" prop="time">
                            <el-date-picker v-model="issueForm.time" type="datetimerange" range-separator="至"
                                start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="邀请人员：" label-width="125px">
                            <el-button size="small" type="success" @click="treeDialog = 1">{{
                                checkedUser.length > 0 ? `已选择 ${checkedUser.length} 人` : '选择人员 + ' }}</el-button>
                        </el-form-item>
                        <div style="text-align: center;">
                            <el-button size="small" @click="issueDialog = false">取消</el-button>
                            <el-button type="primary" size="small" @click="issueFormBtn('issueForm')">发布</el-button>
                        </div>
                    </el-form>
                </el-dialog>
                <!-- 人员选择弹出框 -->
                <el-dialog title="人员选择" :visible.sync="treeDialog" width="40%">
                    <div class="treeDialog">
                        <el-tree class="treeCss" :data="treeData" node-key="id" :props="defaultProps"
                            @node-click="handleNodeClick"></el-tree>
                        <div class="treeCss" style="margin-left: 10px;">
                            <div style="margin-top: 3px;">
                                {{ userOptions.length > 0 ? '请选择人员' : '请选择部门' }}
                            </div>
                            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange"
                                v-if="userOptions.length > 0">全选</el-checkbox>
                            <el-checkbox-group v-model="checkedUser">
                                <el-checkbox v-for="i in userOptions" :label="i.staffId" :key="i">{{ i.staffName
                                }}</el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </div>
                    <div style="text-align: center;margin-top: 10px;">
                        <el-button size="small" @click="checkedUser = []">重置</el-button>
                        <el-button size="small" type="primary" @click="subUser">确定</el-button>
                    </div>
                </el-dialog>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>

<script>
import formCreate from "@form-create/element-ui";
function formType(val) {
    // (1.单项选择,2.多项选择,3.文本框,4.多项文本框,5.文字,6.上传附件)
    switch (val) {
        case "radio":
            return 1
            break;
        case 'checkbox':
            return 2
            break;
        case 'input':
            return 3
            break;
        case 'span':
            return 5
            break;
        case 'upload':
            return 6
            break;
        default:
            break;
    }
}
function formatNum(val) {
    if (val) return 1
    else return 0
}
export default {

    data() {
        return {
            step: 1,
            tabs: '1',
            titleForm: {
                title: '',
                remark: ''
            },
            titleRules: {
                title: [
                    { required: true, message: '请输入问卷名称', trigger: 'blur' },
                ]
            },
            feedbackId: '',
            drawer: 0,
            Frule: [],
            Fopthion: '',
            issueDialog: false,
            selImg: 0,
            issueForm: {
                id: '',
                title: '',
            },
            issueRules: {
                time: [
                    { required: true, message: '请输入选择反馈期限', trigger: 'blur' },
                ],
                webUrl: [
                    { required: true, message: '请输入链接地址', trigger: 'blur' },
                    { pattern: /^https?:\/\/((.)+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?.(\?)?)*)*$/i, message: '请输入正确的链接 例：https://www.baidu.com', trigger: 'change' }
                ]
            },
            treeData: [],
            defaultProps: {
                label: 'label',
                children: 'children'
            },
            treeDialog: 0,

            isIndeterminate: false,
            userOptions: [],
            checkedUser: [],
            checkAll: false,
            checkAllArr: [],
            editStyle: false,
            loadingstate: false,
            ImgUrl: process.env.VUE_APP_API_BASE_URL,
            showImgUrl: '',
            coverImg: [],

            weblink: 0,
            webUrl: '',
        }
    },
    watch: {
        issueDialog(val) { //监听关闭外联状态
            if (!val) {
                this.weblink = 0
            }
        }
    },
    created() {
        if (process.env.NODE_ENV == "development") {
            this.showImgUrl = process.env.VUE_APP_API_BASE_URL
        } else {
            this.showImgUrl = ''
        }
    },
    mounted() {
        console.log(process.env.VUE_APP_API_BASE_URL)
        this.getDeptData()
        let query = this.$route
        // console.log(query)
        if (query.query.id) {
            this.editStyle = true
            this.feedbackId = query.query.id
            let editFeedback = JSON.parse(localStorage.getItem("editFeedback"))
            console.log(editFeedback)
            this.titleForm.title = editFeedback.title
            this.titleForm.remark = editFeedback.remark
            this.Frule = formCreate.parseJson(editFeedback.formContent)
            this.Fopthion = formCreate.parseJson(editFeedback.ruleContent)
            console.log(this.Frule, '***********', this.Fopthion)
            this.$refs.designer.setRule(this.Frule)
            this.$refs.designer.setOption(this.Fopthion)
        }
        this.getFile()
    },
    methods: {
        outsideBtn() {
            this.weblink = 1
            this.issueDialog = 1
        },
        handleUploadSuccess(res) {
            console.log(res)
            this.coverImg.push(res)
            console.log(this.coverImg)

            this.$post('/feedback/file/save', {
                feedbackFileName: res.fileName,
                feedbackFilePath: res.url
            }).then(res => {
                console.log(res)
            })
        },
        handleUploadError() {
            this.$message({
                type: "error",
                message: "上传失败",
            });
        },
        // 文件格式验证
        beforeAvatarUploada(file) {
            this.loadingstate = true;
            let index = file.name.lastIndexOf(".");
            let extension = file.name.substr(index + 1);
            let extensionList = [
                "png",
                "PNG",
                "jpg",
                "JPG",
                "jpeg",
                "JPEG",
                "bmp",
            ];
            const isLt2M = file.size / 1024 / 1024 < 10;
            if (!isLt2M) {
                this.$message({
                    message: "封面不可超出10M",
                    type: "warning",
                    center: true,
                });
                return false;
            } else if (extensionList.indexOf(extension) < 0) {
                this.$message({
                    message: "当前文件格式不支持",
                    type: "error",
                    center: true,
                });
                return false;
            } else {
                console.log(file)
            }
        },
        //获取问卷封面
        getFile() {
            this.$post('/feedback/file/list', { page: 1, size: 3 }).then(res => {
                console.log(res)
                res.data.data.forEach(i => {
                    i.url = i.feedbackFilePath
                })
                console.log(res.data.data)
                this.coverImg = res.data.data
                console.log(this.coverImg)
            })
        },
        //提交选择的人员
        subUser() {
            console.log(this.checkedUser)
            if (this.checkedUser.length > 0) {
                this.treeDialog = 0
            } else {
                this.$message.warning('请选择人员')
            }
        },
        //人员全选
        handleCheckAllChange(val) {
            console.log(val, this.userOptions)
            if (val) {
                let arr = []
                this.userOptions.forEach(i => {
                    arr.push(i.staffId)
                })
                this.checkedUser = Array.from(new Set([...this.checkedUser, ...arr]))
                console.log(this.checkedUser)
                this.isIndeterminate = false;
            } else {
                let arr = []
                this.userOptions.forEach(i => {
                    arr.push(i.staffId)
                })
                let newSet = new Set(this.checkedUser)
                arr.forEach(i => {
                    newSet.delete(i)
                })
                this.checkedUser = [...newSet]
                console.log(this.checkedUser)
            }
        },
        handleNodeClick(data) {
            if (data.personList) {
                this.checkAll = false;
                this.userOptions = data.personList
                // console.log(this.userOptions)
            }
        },
        //获取部门数据
        getDeptData() {
            this.$post('/staff/list', { page: 1, size: -1 }).then(res => {
                let arr = res.dict.deptPerson[0].children
                this.treeData = arr
            })
        },
        //创建问卷
        createForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.step = 0;
                    this.formConfiguration()
                }
            });
        },
        //问卷发布
        issueBtn() {
            this.Frule = formCreate.parseJson(this.getFormJson())
            this.Fopthion = formCreate.parseJson(this.getFormOption())
            // console.log(this.Frule)
            //判断是否配置了表单
            if (this.Frule.length > 1) {
                this.issueDialog = true
            } else {
                this.$message({
                    message: '请配置问卷内容后发布',
                    type: 'warning'
                });
            }
        },
        //预览生成按钮的输出
        onSubmit(formData) {
            console.log(formData)
        },
        //展示移动端效果
        showDrawer() {
            this.drawer = 1
            this.Frule = formCreate.parseJson(this.getFormJson())
            this.Fopthion = formCreate.parseJson(this.getFormOption())
        },
        getFormJson() {
            //FcDesigner 生成的`JSON`
            const FcDesignerRule = this.$refs.designer.getRule();
            // console.log(FcDesignerRule)
            return JSON.stringify(FcDesignerRule)
        },
        getFormOption() {
            //FcDesigner 生成的`options`
            const FcDesignerOptions = this.$refs.designer.getOption();
            // console.log(FcDesignerOptions)
            return JSON.stringify(FcDesignerOptions)
        },
        issueFormBtn(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.checkedUser.length < 1) {
                        this.$message.warning('请选择人员后发布问卷')
                        return
                    }
                    console.log(this.issueForm)
                    this.Frule.forEach(i => {
                        i.remark = i.field
                        i.questionType = formType(i.type)
                        i.require = formatNum(i.$required)
                        i.content = i.title
                        if (formType(i.type) == 1 || formType(i.type) == 2) {
                            i.options.forEach(j => {
                                j.content = j.label
                                j.remark = j.value
                            })
                        }
                        if (formType(i.type) == 1 || formType(i.type) == 2) {
                            i.feedbackOptionList = i.options
                        }

                    })
                    let sub = {
                        weblink: this.weblink,
                        webUrl: this.issueForm.webUrl,
                        staffList: this.checkedUser,
                        id: this.feedbackId,
                        ...this.titleForm,
                        feedbackTimeStart: this.issueForm.time[0],
                        feedbackTimeEnd: this.issueForm.time[1],
                        inviteNum: '',
                        formContent: JSON.stringify(this.Frule),
                        ruleContent: JSON.stringify(this.Fopthion),
                        feedbackQuestionList: [
                            ...this.Frule
                        ],
                        feedbackFilePath: this.coverImg[this.selImg].url
                    }
                    console.log(sub)
                    this.$post('/feedback/save', sub).then(res => {
                        console.log(res)
                        if (res.code == 1) {
                            this.$message.success(res.msg);
                        }
                        setTimeout(() => {
                            this.$router.back()
                        }, 1000);
                    })
                }
            });

        },
        formConfiguration() {
            //配置表单基础样式以及按钮展示
            const option = {
                "form": {
                    "labelPosition": "top",
                    "size": "mini",
                    "labelWidth": "20%",
                    "hideRequiredAsterisk": false,
                    "showMessage": true,
                    "inlineMessage": false
                },
                "submitBtn": true,
                "resetBtn": false,
            }
            this.$refs.designer.setOption(option)
            //移除组件大类
            this.$refs.designer.removeMenu('layout',)
            //移除对应组件
            this.$refs.designer.removeMenuItem('el-transfer')
            this.$refs.designer.removeMenuItem('el-alert')
            this.$refs.designer.removeMenuItem("colorPicker")
            this.$refs.designer.removeMenuItem("cascader")
            this.$refs.designer.removeMenuItem("rate")
            this.$refs.designer.removeMenuItem("slider")
            this.$refs.designer.removeMenuItem("datePicker")
            this.$refs.designer.removeMenuItem("timePicker")
            this.$refs.designer.removeMenuItem("switch")
            this.$refs.designer.removeMenuItem("tree")
            this.$refs.designer.removeMenuItem("inputNumber")
            this.$refs.designer.removeMenuItem("select")
            this.$refs.designer.removeMenuItem("fc-editor")
            this.$refs.designer.removeMenuItem("el-button")
            this.$refs.designer.removeMenuItem("el-divider")
            if (!this.editStyle) {
                // 配置组件生成规则---直接配置显示在页面上
                const rule = [{
                    "type": "span",
                    "title": this.titleForm.title,
                    "native": false,
                    "children": [this.titleForm.remark],
                    "_fc_drag_tag": "span",
                    "hidden": false,
                    "display": true,
                }]
                this.$refs.designer.setRule(rule)
            }

        }
    }
}
</script>

<style lang="less" scoped>
.upload {
    width: 80px;
    line-height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    // border: 1px dashed #CCCCCC;
    // color: #CCCCCC;
    cursor: pointer;
}

// .upload:hover{
//     border: 1px dashed #1a7af8;
//     color: #1a7af8;
// }

/deep/.el-upload--picture-card {
    width: 80px;
    height: 80px;
    line-height: 80px;
}

.treeDialog {
    // border: 1px solid;

    display: flex;
    align-items: center;
    justify-content: space-between;

    .treeCss {
        width: 50%;
        height: 500px;
        overflow: auto;
    }

    /* 侧边滚动条 */
    .treeCss::-webkit-scrollbar {
        width: 3px;
    }

    /* 滚动条上的滚动滑块 */
    .treeCss::-webkit-scrollbar-thumb {
        background: #CCCCCC;
        border-radius: 4px;
    }

    /* 滚动条轨道 */
    .treeCss::-webkit-scrollbar-track {
        background: #EEEEEE;
        border-radius: 4px;
    }
}

.selImg {
    border: 2px solid #1a7af8;
}

/deep/.el-textarea__inner {
    height: 300px;
}

/deep/._fc-m-tools {
    flex-direction: row-reverse;
    justify-content: flex-start;
}

/deep/._fc-l-title {
    text-align: center;
    margin-bottom: 10px;
}

/deep/._fc-l-item {
    width: 100%;
    border: 1px solid #1a7af8;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0;
    height: 40px;
    margin-bottom: 10px;
    border-radius: 4px;

    ._fc-l-icon {
        width: 40%;
        text-align: right;
        color: #1a7af8;
    }


    ._fc-l-name {
        width: 50%;
        text-align: left;
        color: #1a7af8;
    }
}

/deep/._fc-l-item:hover ._fc-l-name {
    color: #FFF;
}

/deep/._fc-l-item:hover ._fc-l-icon {
    color: #FFF;
}

.showPhone {
    height: 100%;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;

    .phone {
        width: 378px;
        height: 770px;
        background: url('../../../assets/images/phone.png') no-repeat;
        position: relative;

        .phoneContent {
            // border: 1px solid;
            position: absolute;
            top: 95px;
            left: 25px;
            width: 86.5%;
            height: 75%;
            box-sizing: border-box;
            padding: 20px;
            overflow-y: scroll;
            overflow-x: hidden;
        }

        /* 侧边滚动条 */
        .phoneContent::-webkit-scrollbar {
            width: 3px;
        }

        /* 滚动条上的滚动滑块 */
        .phoneContent::-webkit-scrollbar-thumb {
            background: #CCCCCC;
            border-radius: 4px;
        }

        /* 滚动条轨道 */
        .phoneContent::-webkit-scrollbar-track {
            background: #EEEEEE;
            border-radius: 4px;
        }
    }
}

.backBtn {
    position: absolute;
    right: 20px;
    z-index: 99;
}

.tool {
    margin-top: 20px;
    text-align: center;
}

/* 侧边滚动条 */
/deep/.el-aside::-webkit-scrollbar {
    width: 3px;
}

/* 滚动条上的滚动滑块 */
/deep/.el-aside::-webkit-scrollbar-thumb {
    background: #CCCCCC;
    border-radius: 4px;
}

/* 滚动条轨道 */
/deep/.el-aside::-webkit-scrollbar-track {
    background: #EEEEEE;
    border-radius: 4px;
}

/* 侧边滚动条 */
/deep/.el-main::-webkit-scrollbar {
    width: 3px;
}

/* 滚动条上的滚动滑块 */
/deep/.el-main::-webkit-scrollbar-thumb {
    background: #CCCCCC;
    border-radius: 4px;
}

/* 滚动条轨道 */
/deep/.el-main::-webkit-scrollbar-track {
    background: #EEEEEE;
    border-radius: 4px;
}

/* 侧边滚动条 */
/deep/._fc-m-drag::-webkit-scrollbar {
    width: 3px;
}

/* 滚动条上的滚动滑块 */
/deep/._fc-m-drag::-webkit-scrollbar-thumb {
    background: #CCCCCC;
    border-radius: 4px;
}

/* 滚动条轨道 */
/deep/._fc-m-drag::-webkit-scrollbar-track {
    background: #EEEEEE;
    border-radius: 4px;
}
</style>