<template>
    <div class="wrapper editwrap">
      <el-dialog
            :visible.sync="dialogVisible"
            :title="title"
            :show-close="false"
            :close-on-click-modal="false"
      >
        <el-row>
          <el-col :span="24">
            <el-form ref="editForm" :model="editForm" :rules="rules" label-width="100px">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="editForm.title"></el-input>
                </el-form-item>
                <el-form-item label="类别" prop="fileType">
                    <el-select v-model="editForm.fileType" placeholder="请选择" @change="seletChange" filterable>
                        <el-option
                                v-for="item in knowledgeTypeArr"
                                :key="item.dictId"
                                :label="item.name"
                                :value="item.dictId.toString()"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="适用领域" prop="applyArea">
                    <el-input v-model="editForm.applyArea"></el-input>
                </el-form-item>
                <el-form-item label="内容备注" prop="remarks">
                    <textarea id="editorA" v-model="editForm.remarks"></textarea>
                </el-form-item>
                <div v-if="title != '详情'">
                  <el-form-item label="源文件">
                    <el-upload
                            ref="uploaderB"
                            class="uploader"
                            :limit="1"
                            :action="actionUrl"
                            :on-success="(a,b,c) => onSuccess(a,b,c,'fileUrl')"
                            :on-error="onError"
                            :on-remove="handleRemove"
                            :before-remove="(a,b,c) => beforeRemove(a,b,c,'fileUrl')"
                            :on-exceed="onExceed"
                            :before-upload="beforeUpload"
                            :multiple="false"
                            list-type="picture"
                            :file-list="fileList"
                    >
                        <i class="el-icon-plus"></i>
                        <div slot="tip" class="el-upload__tip" >只能上传doc/docx/pdf/xls/xlsx格式文件，且不超过一个</div>
                    </el-upload>
                  </el-form-item>
                </div>
                <div v-else>
                  <el-form-item label="源文件">
                    <span
                          class="dbtn sd qiCr"
                          @click="checkFile(editForm.fileUrl)"
                          v-if="editForm.fileUrl != ''"
                    >
                      <i class="el-icon el-icon-view"></i>
                      {{editForm.fileOriginalName}}
                    </span>
                  </el-form-item>
                </div>
            </el-form>

          </el-col>
        </el-row>
        <span slot="footer" class="dialog-footer">
            <el-button type="primary" size="small" @click="confirmFun('editForm')" v-if="title != '详情'">提交</el-button>
            <el-button @click="$emit('dialogFun')" size="small">取消</el-button>
        </span>
      </el-dialog>
    </div>
</template>
<style lang="scss">
    @import "@/utils/default.scss";
</style>
<script lang="ts">
    import { Component, Vue, Provide, Prop, Watch } from "vue-property-decorator";
    import METHOD from "@/utils/methods";
    let uploadfile = require("@/assets/uploadfile.png");

    @Component({
        components: {  }
    })

    export default class KnowledgeInfoEdit extends Vue {
        @Prop(Boolean) dialogVisible!: Boolean;
        @Prop(String) title!: String;
        @Prop(Object) editForm;
        @Provide() knowledgeTypeArr: any = [];

        //上传
        @Provide() actionUrl: any = "";
        @Provide() fileUrl: any = [];
        @Provide() fileList: any = [];

        @Provide() editorA: any;
        @Provide() rules: any = {
            title: [{ required: true, trigger: "blur", message: "该项为必填项！" }],
            // remarks: [{ required: true, trigger: "blur", message: "该项为必填项！" }]
        };
        @Watch("fileUrl") change(val: any) {
            if (val.length > 0) {
                this.editForm.fileUrl = val[0].response.data.viewPath;
                this.editForm.fileOriginalName = val[0].response.data.originalName;

                this.fileList = [];
                this.fileList.push({
                    name: this.editForm.fileOriginalName,
                    url: uploadfile,
                });
            } else {
                this.editForm.fileUrl = "";
                this.editForm.fileOriginalName = "";
            }
        }

        //取消事件要在父级取消是所以用到 $emit
        confirmFun(formName: string) {
            let that = this;
            that.editForm.remarks = that.editorA.getHTML();
            console.log(that.editForm);
            (that as any).$refs[formName].validate((valid: boolean) => {
                if (that.editorA.getText() == false) {
                    that.$message.error("没有内容！");
                    return;
                }
                if (valid) {
                    (that as any).$axios
                        .post("/knowledgeInfo/addOrEditKnowledgeInfo", that.editForm)
                        .then(() => {
                            (that as any).$message({
                                message: "操作成功！",
                                type: "success"
                            });
                            (that as any).$emit("dialogFun");
                            that.$emit("refreshTableData"); //刷新表格
                        });
                } else {
                    return false;
                }
            });
        }
        //风险类型
        getKnowledgeType() {
            let that = this;
            (that as any).$axios
                .get(
                    `/dict/getSysDictByDictTypeCode/knowledge_type`
                )
                .then((res: any) => {
                    that.knowledgeTypeArr = res;
                });
        }
        seletChange(dictId: any) {
            let that = this,
                arr;
            arr = that.knowledgeTypeArr.filter((ele: any) => dictId == ele.dictId);
            that.editForm.fileType = arr[0].name;
        }
        checkFile(url: any) {
            window.open("http://" + METHOD.GlobalUrl + "/ioc" + url)
        }
        //detail
        getDetailData() {
            let that = this;
            (that as any).$axios
                .get(`/knowledgeInfo/getKnowledgeInfoById/${that.editForm.id}`)
                .then((res: any) => {
                    that.editForm = res;
                    that.$nextTick(() => {
                        that.editorA.setValue(that.editForm.remarks);
                    });
                });
        }
        /*
        上传
         */
        onSuccess(res: any, file: any, fileList: any, key: string) {
            this.$data[key] = fileList;
        }
        onError(err: any, file: any, fileList: any) {
            this.$message.error("上传失败!");
        }
        handleRemove(file: any, fileList: any, key: string) {
            this.$data[key] = fileList;
            this.editForm.fileUrl = "";
            this.editForm.fileOriginalName = "";
        }
        onExceed(file: any, fileList: any) {
            this.$message.warning("只允许上传一个文件，如需更改请先删除！");
        }
        beforeRemove(file: any, fileList: any) {
            if (file && file.status==="success") {
                let that = this,
                    param;
                param = file.response
                    ? file.response.data.savePath.replace(/\\/g, "%")
                    : file.url.replace(/\\/g, "%").slice(9);
                METHOD.axiosGet(this, `/file/deleteFile?savePath=${param}`, function (
                    res: any
                ) {
                    if (res.code == 0) that.$message.success("删除成功");
                    else return false;
                });
            }
        }
        beforeUpload(file: any){
            console.log(file)
            var testmsg=file.name.substring(file.name.lastIndexOf('.')+1)
            const extension = testmsg === 'xls'
            const extension2 = testmsg === 'xlsx'
            const extension3 = testmsg === 'doc'
            const extension4 = testmsg === 'docx'
            const extension5 = testmsg === 'pdf'
            if(!extension && !extension2 && !extension3 && !extension4 && !extension5) {
                this.$message({
                    message: '上传文件只能是doc、docx、pdf、xls、xlsx格式!',
                    type: 'warning'
                });
            }
            return extension || extension2 || extension3 || extension4 || extension5
        }
        //创建编辑器
        creatEditor() {
            this.editorA = new ice.editor("editorA");
            //自定义编辑器工具栏菜单（默认展示所有功能）
            this.editorA.menu = [
                "fontSize",
                "foreColor",
                "bold",
                "italic",
                "underline",
                "strikeThrough",
                "line",
                "justifyLeft",
                "justifyCenter",
                "justifyRight",
                "line",
                "table",
                "insertImage",
                'insertOrderedList',
                'insertUnorderedList',
                'indent'
            ];
            this.editorA.height = "200px";
            this.editorA.create();
        }
        created() {
            let that = this;
            that.getKnowledgeType();

            if(that.editForm.id){//编辑
                that.getDetailData();
            }
            if (that.editForm.fileOriginalName) {
                that.fileList.push({
                    name: that.editForm.fileOriginalName,
                    url: uploadfile,
                });
            }
            that.$nextTick(() => {
                that.creatEditor();
            })
            that.actionUrl = "http://" + METHOD.GlobalUrl + "/ioc/file/uploadFile";
        }
        mounted() {}
    }
</script>
