import {
    ApiModel
} from "../../utils/api";
const _Http = new ApiModel();
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        /* 附件类型 */
        filesType: {
            type: String,
            value: "image"
        },
        /* 图片列表 */
        fileList: {
            type: Array
        },
        /* 上传类型 Logo-品牌logo userImage-用户头像  productImage-产品图片 SupplyAndDemand-供需 LogoCover-产品展示图  annunciate-公告类型*/
        upType: {
            type: String
        },
        /* 上传数量 */
        maxCount: {
            type: Number,
            value: 1
        },
        /* 未上传图片提示 */
        logoTips: {
            type: Boolean,
            value: false
        },
        /* 提示文本 */
        Tips: {
            type: String
        },
        /* 显示隐藏 */
        UploadShow: {
            type: Number,
            value: 2 // 1 是登录样式  2 是产品上传图片样式
        },
        /* 文本行高 */
        lineHeight: {
            type: String,
            value: "100rpx"
        },
        /* 返回图片数据函数 */
        imageChange: {
            type: Function
        },
        /* 图片尺寸 */
        previewSize: {
            type: String,
            value: "80px"
        },
        /* 是否禁用 */
        fisadministrator: {
            type: Boolean,
            value: false
        },
        /* 供需产品id */
        tsupplyanddemand: {
            type: Number
        }
    },
    /* 生命周期 */
    lifetimes: {
        attached: function () {
            // 图片临时 id = 数字类型的 userid + 去掉前五位的时间戳
            const forTheTimeId = parseInt(wx.getStorageSync('userData').userid + (Date.parse(new Date()).toString().slice(5)));
            this.setData({
                forTheTimeId
            })
        },
        detached: function () {
            // 在组件实例被从页面节点树移除时执行
            if (this.data.ExitTheDelete) return;
            const data = this.data.fileList.filter((value) => value.ownerid == 0);
            for (let i = 0; i < data.length; i++) {
                _Http.basic({
                    "accesstoken": wx.getStorageSync('userData').token,
                    "classname": "system.system.docManage",
                    "method": "deleteDoc",
                    "content": {
                        "ownertable": data[i].ownertable,
                        "ownerid": data[i].ownerid,
                        "tattachmentid": data[i].tattachmentid
                    }
                }).then((res) => {
                    if (res.msg != "成功") return;
                    console.log("附件删除成功")
                })
            };
        },
    },

    /**
     * 组件的初始数据
     */
    data: {
        ExitTheDelete: false,
    },

    /**
     * 组件的方法列表
     */
    methods: {
        /* 文件校验 */
        beforeRead(event) {
            const {
                file,
                callback
            } = event.detail;
            for (let i = 0; i < file.length; i++) {
                /* 校验文件大小 */
                if (file[i].size > 10485760) {
                    wx.showToast({
                        title: '文件体积大于10Mb',
                        icon: "none",
                        duration: 3000
                    })
                    return callback(false)
                }
                /* 校验文件格式 */
                if (this.data.filesType == 'image') {
                    const suffix = ['jpg', 'jpeg', 'png', 'gif', 'pdf'],
                        index = file[i].url.lastIndexOf("."),
                        ext = file[i].url.substr(index + 1);
                    if (!suffix.some((value) => value == ext)) {
                        wx.showToast({
                            title: '错误文件格式',
                            icon: "none",
                            duration: 3000
                        })
                        return callback(false)
                    }
                }
                callback(true)
            }
        },
        /* 上传图片 */
        afterRead(event) {
            for (let i = 0; i < event.detail.file.length; i++) {
                // 初始化数据
                let that = this,
                    data = this.requestType(event.detail.file[i]);
                //发送请求
                wx.getFileSystemManager().readFile({
                    filePath: event.detail.file[i].url,
                    success: result => {
                        //返回临时文件路径
                        const fileData = result.data
                        _Http.basic(data).then(res => {
                            console.log(res)
                            if (res.msg != "成功") return wx.showToast({
                                title: res.data,
                                icon: "none"
                            })
                            that.uploadFile(res, fileData)
                        }).catch(err => {})
                    },
                    fail: console.error
                })
            }
        },
        /* 上传成功反馈 */
        uploadFile(res, data) {
            var that = this
            wx.request({
                url: res.data.obsuploadurl,
                method: "PUT",
                data: data,
                header: {
                    'content-type': 'application/octet-stream' // 默认值
                },
                success() {
                    _Http.basic({
                        "accesstoken": wx.getStorageSync('userData').token,
                        "classname": "system.system.docManage",
                        "method": "uploadSuccess",
                        "content": {
                            "obsfilename": res.data.obsfilename
                        }
                    }).then(res => {
                        console.log(res)
                        if (res.msg != "成功") return;
                        let fileList = that.data.fileList;
                        for (let i = 0; i < res.data.length; i++) {
                            let arr = {
                                url: res.data[i].fobsurl,
                                ownerid: res.data[i].ownerid,
                                tattachmentid: res.data[i].tattachmentid,
                                ownertable: res.data[i].ownertable,
                                fdocument: res.data[i].fdocument,
                            }
                            fileList.push(arr)
                        };
                        // 用户头像 先删除 在修改
                        if (that.data.upType == "userImage" && fileList.length >= 2) {
                            that.dleeteDealWith(0);
                        }
                        that.setData({
                            fileList
                        });
                        /* 返回数据 */
                        that.triggerEvent("imageChange", {
                            fileList
                        })
                    }).catch(err => {
                        console.log(err)
                    })
                }
            })
        },
        /* 请求类型 */
        requestType(file) {
            //获取文件后缀
            var index = file.url.lastIndexOf(".");
            var ext = file.url.substr(index + 1);
            //文件名称
            const timestamp = Date.parse(new Date());;
            //不同类型图片数据
            if (this.data.upType == 'Logo') {
                //logo上传
                return {
                    "accesstoken": wx.getStorageSync('userData').token,
                    "classname": "system.system.docManage",
                    "method": "getFileName",
                    "content": {
                        "filename": timestamp,
                        "filetype": ext,
                        "ownertable": "tagents",
                        "ownerid": wx.getStorageSync('userData').tagentsid,
                        "ftype": "brandlogo"
                    }
                }
            } else if (this.data.upType == 'userImage') {
                //头像上传
                return {
                    "accesstoken": wx.getStorageSync('userData').token,
                    "classname": "system.system.docManage",
                    "method": "getFileName",
                    "content": {
                        "filename": timestamp,
                        "filetype": ext,
                        "ownertable": "tenterprise_users",
                        "ownerid": wx.getStorageSync('userData').userid,
                        "ftype": "headportrait"
                    }
                }
            } else if (this.data.upType == 'productImage') {
                //产品图片上传
                return {
                    "accesstoken": wx.getStorageSync('userData').token,
                    "classname": "system.system.docManage",
                    "method": "getFileName",
                    "content": {
                        "filename": timestamp,
                        "filetype": ext,
                        "ownertable": this.data.forTheTimeId,
                        "ownerid": 0,
                        "ftype": "default"
                    }
                }
            } else if (this.data.upType == "SupplyAndDemand") {
                //供需附件上传
                return {
                    "accesstoken": wx.getStorageSync('userData').token,
                    "classname": "system.system.docManage",
                    "method": "getFileName",
                    "content": {
                        "filename": timestamp,
                        "filetype": ext,
                        "ownertable": this.data.forTheTimeId,
                        "ownerid": 0,
                        "ftype": "default"
                    }
                }
            } else if (this.data.upType == 'LogoCover') {
                //品牌展示图上传
                return {
                    "accesstoken": wx.getStorageSync('userData').token,
                    "classname": "system.system.docManage",
                    "method": "getFileName",
                    "content": {
                        "filename": timestamp,
                        "filetype": ext,
                        "ownertable": "tagents",
                        "ownerid": wx.getStorageSync('userData').tagentsid,
                        "ftype": "brandcover"
                    }
                }
            } else if (this.data.upType == 'annunciate') {
                let type = (this.data.filesType == 'file') ? "default" : "cover";
                console.log(type)
                //通告封面上传
                return {
                    "accesstoken": wx.getStorageSync('userData').token,
                    "classname": "system.system.docManage",
                    "method": "getFileName",
                    "content": {
                        "filename": timestamp,
                        "filetype": ext,
                        "ownertable": this.data.forTheTimeId,
                        "ownerid": 0,
                        "ftype": type
                    }
                }
            }
        },
        /* 删除文件 */
        imagesDelete(e) {
            if (this.data.fisadministrator && this.data.upType != 'SupplyAndDemand') return;
            const that = this;
            wx.showModal({
                title: '提示',
                content: '删除后不可恢复，是否继续',
                success: function (res) {
                    if (res.confirm) {
                        const {
                            index
                        } = e.detail;
                        that.dleeteDealWith(index);
                    }
                }
            })
        },
        /* 保存退出，修改附件位置 */
        saveTheChanges(obj) {
            const data = this.data.fileList.filter((value) => value.ownerid == 0);
            this.setData({
                ExitTheDelete: true
            })
            for (let i = 0; i < data.length; i++) {
                obj.tattachmentid = data[i].tattachmentid;
                _Http.basic({
                    "accesstoken": wx.getStorageSync('userData').token,
                    "classname": "system.system.docManage",
                    "method": "changeFilesData",
                    "content": {
                        "files": [{
                            "tattachmentid": data[i].tattachmentid,
                            "fdocument": data[i].fdocument,
                            "ownertable": obj.ownertable,
                            "ownerid": obj.ownerid
                        }]
                    }
                }).then(res => {
                    console.log("修改附件", res)
                })
            }
        },
        /* 处理删除 */
        dleeteDealWith(index) {
            const that = this;
            const type = that.data.fileList[index];
            _Http.basic({
                "accesstoken": wx.getStorageSync('userData').token,
                "classname": "system.system.docManage",
                "method": "deleteDoc",
                "content": {
                    "ownertable": type.ownertable,
                    "ownerid": type.ownerid,
                    "tattachmentid": type.tattachmentid
                }
            }).then(s => {
                console.log(s)
                if (s.msg != '成功') return wx.showToast({
                    title: "删除失败,请稍后再试！",
                    icon: "none"
                })
                let fileList = that.data.fileList;
                fileList.splice(index, 1);
                that.triggerEvent("imageChange", {
                    fileList
                })
                that.setData({
                    fileList
                })
                console.log("删除成功")
            })
        },
        /* 验证是否上传附件 */
        VerifyThere() {
            if (this.data.fileList.length < 1) {
                return false
            }
            return true
        }
    }
})