import {
    ApiModel
} from "../../utils/api";
const _Http = new ApiModel();
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        /* 图片列表 */
        fileList: {
            type: Array
        },
        /* 父页面传递图片 */
        attinfos: {
            type: Object
        },
        /* 上传类型 Logo-品牌logo userImage-用户头像  productImage-产品图片 SupplyAndDemand-供需*/
        upType: {
            type: String
        },
        /* 上传数量 */
        maxCount: {
            type: Number,
            value: 1
        },
        /* 未上传图片提示 */
        logoTips: {
            type: Boolean,
            value: false
        },
        /* 提示文本 */
        Tips: {
            type: String
        },
        /* 显示隐藏 */
        UploadShow: {
            type: Boolean,
            value: false
        },
        /* 文本行高 */
        lineHeight: {
            type: String,
            value: "100rpx"
        },
        /* 返回图片数据函数 */
        imageChange: {
            type: Function
        },
        /* 产品ID */
        tagents_productid: {
            type: String
        },
        /* 图片尺寸 */
        previewSize: {
            type: String,
            value: "80px"
        },
        /* 是否禁用 */
        fisadministrator: {
            type: Boolean,
            value: false
        },
        tsupplyanddemand: {
            type: Number
        }
    },

    /**
     * 组件的初始数据
     */
    data: {

    },

    /**
     * 组件的方法列表
     */
    methods: {
        /* 文件校验 */
        beforeRead(event) {
            console.log("文件校验")
            const {
                file,
                callback
            } = event.detail;
            /* 校验文件大小 */
            if (file.size > 10485760) {
                wx.showToast({
                    title: '文件不可超过10Mb',
                    icon: "none",
                    duration: 3000
                })
                return callback(false)
            }
            /* 校验文件格式 */
            const suffix = ['jpg', 'jpeg', 'png', 'gif', 'pdf'],
                index = file.url.lastIndexOf("."),
                ext = file.url.substr(index + 1);
            if (!suffix.some((value) => value == ext)) {
                wx.showToast({
                    title: '错误文件格式',
                    icon: "none",
                    duration: 3000
                })
                return callback(false)
            }
            callback(true)
        },
        /* 上传图片 */
        afterRead(event) {
            // 初始化数据
            var that = this;
            const {
                file
            } = event.detail;
            //获取文件后缀
            var index = file.url.lastIndexOf(".");
            var ext = file.url.substr(index + 1);
            //文件名称
            const timestamp = Date.parse(new Date());;
            let data = {};
            //不同类型图片数据
            if (this.data.upType == 'Logo') {
                //logo上传
                data = {
                    "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') {
                //头像上传
                data = {
                    "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') {
                //产品图片上传
                data = {
                    "accesstoken": wx.getStorageSync('userData').token,
                    "classname": "system.system.docManage",
                    "method": "getFileName",
                    "content": {
                        "filename": timestamp,
                        "filetype": ext,
                        "ownertable": "tagents_product",
                        "ownerid": this.data.tagents_productid,
                        "ftype": "default"
                    }
                }
            } else if (this.data.upType == "SupplyAndDemand") {
                //供需附件上传
                data = {
                    "accesstoken": wx.getStorageSync('userData').token,
                    "classname": "system.system.docManage",
                    "method": "getFileName",
                    "content": {
                        "filename": timestamp,
                        "filetype": ext,
                        "ownertable": "tsupplyanddemand",
                        "ownerid": this.data.tsupplyanddemand,
                        "ftype": "default"
                    }
                }
            }
            //发送请求
            wx.getFileSystemManager().readFile({
                filePath: file.url,
                success: result => {
                    //返回临时文件路径
                    const fileData = result.data
                    _Http.basic(data).then(res => {
                        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
                            }
                            fileList.push(arr)
                        };
                        if (that.data.upType != "userImage") {
                            //普通返回
                            that.setData({
                                fileList
                            });
                            that.triggerEvent("imageChange", {
                                fileList
                            })
                        } else {
                            // 需要返回到父组件中 userImage
                            if (that.data.attinfos != null) {
                                that.dleeteDealWith();
                            }
                            that.triggerEvent("imageChange", {
                                fileList
                            })
                        }
                    }).catch(err => {
                        console.log(err)
                    })
                }
            })
        },
        /* 删除文件 */
        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);
                    }
                }
            })
        },
        /* 处理删除 */
        dleeteDealWith(index) {
            const that = this;
            let ownertable = '';
            if (that.data.upType == 'Logo') {
                //品牌logo
                ownertable = "tagents"
            } else if (that.data.upType == 'userImage') {
                //用户头像
                ownertable = "tenterprise_users"
            } else if (that.data.upType == "SupplyAndDemand") {
                ownertable = "tsupplyanddemand"
            };
            let content = {}
            if (that.data.upType != "userImage") {
                //图片在本页面
                content = {
                    "ownertable": ownertable,
                    "ownerid": that.data.fileList[index].ownerid,
                    "tattachmentid": that.data.fileList[index].tattachmentid
                }
            } else {
                //图片在父组件
                content = {
                    "ownertable": ownertable,
                    "ownerid": that.data.attinfos.ownerid,
                    "tattachmentid": that.data.attinfos.tattachmentid
                }
            }
            _Http.basic({
                "accesstoken": wx.getStorageSync('userData').token,
                "classname": "system.system.docManage",
                "method": "deleteDoc",
                "content": content
            }).then(s => {
                if (s.msg != '成功') return;
                if (that.data.upType != "userImage") {
                    let fileList = that.data.fileList;
                    fileList.splice(index - 1, 1);
                    // 需要返回到父组件中 userImage
                    that.triggerEvent("imageChange", {
                        fileList
                    })
                    that.setData({
                        fileList
                    })
                } else {
                    console.log("删除成功")
                }
                console.log("删除成功")
            })
        },
        /* 验证是否上传附件 */
        VerifyThere() {
            if (this.data.fileList.length < 1) {
                return false
            }
            return true
        }
    }
})