const _Http = getApp().globalData.http,
    MFT = require("../../utils/matchingFeilType"),
    CF = require("../../utils/checkFile"),
    deleteMark = require("../../utils/deleteMark");
Page({
    /**
     * 页面的初始数据
     */
    data: {
        "content": {
            "title": "",
            "sat_sharematerial_classid": '9999' + wx.getStorageSync('userMsg').userid,
            "notes": "",
            "tag": [],
            "type": 1, //1图片2视频3图文
            "canfiledownload": 1,
            "content": "",
            "sat_sharematerialid": 0
        },
        detailsData: {},
        editRichText: false, //编辑富文本
        richTextFile: [],
        items: [],
        activeName: "",
        activeId: "",
        selectShow: false,
        loading: false,
        uploadType: "image",
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let type = 1;
        switch (options.type) {
            case 'video':
                type = 2;
                break;
            case 'richtext':
                type = 3;
                break;
        }
        if (options.item) {
            this.setData({
                items: JSON.parse(options.item),
                "content.type": type,
                uploadType: options.type
            })
        } else {
            this.selectMenu();
        };
        _Http.basic({
            "classname": "webmanage.saletool.sharematerial.sharematerial",
            "method": "insertOrUpdate",
            content: this.data.content
        }).then(res => {
            console.log("新增", res)
            this.setData({
                detailsData: res.data,
                "content.sat_sharematerialid": res.data.sat_sharematerialid
            })
        });
    },
    submit() {
        let content = this.data.content;
        if (content.title == '' || content.sat_sharematerial_classid == '9999' + wx.getStorageSync('userMsg').userid) return wx.showToast({
            title: '请检查素材标题或所属分类',
            icon: "none"
        });
        if (this.data.uploadType == 'image' || this.data.uploadType == 'video') {
            if (this.data.detailsData.attinfos.length == 0) return wx.showToast({
                title: '您还未上传素材附件',
                icon: "none"
            });
        };
        if (this.data.uploadType == 'richtext' && this.data.content.content.length < 8) return wx.showToast({
            title: '您还未编辑或保存图文内容',
            icon: "none"
        });
        if (this.data.loading || this.data.detailsData.status == "审核") return wx.showToast({
            title: '正在提交中',
            icon: "none"
        });
        this.setData({
            loading: true
        })
        _Http.basic({
            "classname": "webmanage.saletool.sharematerial.sharematerial",
            "method": "insertOrUpdate",
            content: content
        }).then(res => {
            this.setData({
                loading: false
            })
            if (res.msg != '成功') return wx.showToast({
                title: res.msg,
                icon: "none"
            });
            this.setData({
                detailsData: res.data
            })

            wx.showToast({
                title: "保存成功",
            });
            this.setData({
                "detailsData.status": "审核"
            })
            setTimeout(() => {
                let pages = getCurrentPages();
                let prevPage = pages[pages.length - 2];
                prevPage.getList(true);
                wx.navigateBack({
                    delta: 0,
                })
            }, 300)
        })
    },
    openSelect() {
        this.setData({
            selectShow: true
        })
    },
    onClose() {
        this.setData({
            selectShow: false
        })
    },
    /* 查询分类 */
    selectMenu(index = 0, res) {
        if (index == 5) return wx.showToast({
            title: res.msg,
            icon: "none"
        });
        _Http.basic({
            "classname": "saletool.sharematerial.sharematerial",
            "method": "select",
            "content": {
                "nocache": true,
                "parentid": 0
            }
        }).then(res => {
            if (res.msg != '成功') return this.selectMenu(index + 1, res);
            let str = JSON.stringify(res.data).replace(/classname/g, 'text').replace(/sat_sharematerial_classid/g, 'id');
            this.setData({
                items: JSON.parse(str)
            });
        });
    },
    /* 切换分类 */
    onClickItem({
        detail = {}
    }) {
        this.setData({
            "content.sat_sharematerial_classid": detail.id,
            activeName: detail.text
        });
        this.onClose();
    },
    onClickNav({
        detail = {}
    }) {
        this.setData({
            mainActiveIndex: detail.index || 0,
        });
    },
    /* 上传文件 */
    getFile({
        detail
    }) {
        _Http.basic({
            "classname": "system.attachment.Attachment",
            "method": "createFileLink",
            "content": {
                "ownertable": "SAT_SHAREMATERIAL",
                "ownerid": this.data.detailsData.sat_sharematerialid,
                "usetype": "default",
                "attachmentids": detail
            }
        }).then(res => {
            console.log("上传成功", res)
            if (res.msg != '成功') return wx.showToast({
                title: res.msg,
                icon: "none"
            });
            this.setData({
                "detailsData.attinfos": this.data.detailsData.attinfos.concat(MFT.fileList(res.data))
            })
        })
    },
    titleInput({
        detail
    }) {
        this.setData({
            "content.title": deleteMark.queryStr(detail.value).trim()
        })
    },
    openFile(e) {
        const {
            item
        } = e.currentTarget.dataset;
        CF.checkFile(item);
    },
    /* 打开编辑富文本 */
    openEditRichText() {
        this.setData({
            editRichText: !this.data.editRichText
        })
    },
    /* 得到编辑好的富文本内容 */
    getRichText({
        detail
    }) {
        this.setData({
            "content.content": detail
        })
    },
    deleteFile(e) {
        const {
            item,
            index
        } = e.currentTarget.dataset;
        const that = this;
        wx.showModal({
            title: '提示',
            content: "是否确认删除该文件？",
            success: async s => {
                if (!s.confirm) return;
                let res = await that.handleDelete([item.linksid]);
                if (res.msg != '成功') wx.showToast({
                    title: res.msg,
                });
                let attinfos = that.data.detailsData.attinfos;
                attinfos.splice(index, 1);
                that.setData({
                    "detailsData.attinfos": attinfos
                });
            }
        })

    },
    handleDelete(linksids) {
        return _Http.basic({
            "classname": "system.attachment.Attachment",
            "method": "deleteFileLink",
            "content": {
                linksids: linksids
            }
        }).then(res => {
            console.log('删除附件', res)
            return res;
        })
    },
    /* 监听页面卸载 */
    onUnload() {
        console.log(this.data.detailsData.sat_sharematerial_classid)
        if (this.data.detailsData.sat_sharematerial_classid != '9999' + wx.getStorageSync('userMsg').userid) return;
        _Http.basic({
            "classname": "webmanage.saletool.sharematerial.sharematerial",
            "method": "delete",
            "content": {
                "sat_sharematerialid": [this.data.detailsData.sat_sharematerialid]
            }
        }).then(res => {
            console.log("删除", res)
        });
        let attinfos = this.data.detailsData.attinfos;
        if (attinfos.length) {
            let linksids = [];
            for (let i = 0; i < attinfos.length; i++) {
                linksids.push(attinfos[i].linksid)
            };
            this.handleDelete(linksids)
        }
    },
    onShareAppMessage(res) { }
})