<template>
    <view class="container">
        <view class="type-box display-flex" v-if="!success">
            <view
                :class="'type-item ' + (actived == index ? 'type-active' : '')"
                :data-item="item"
                :data-index="index"
                @tap="handleUpdatType"
                v-for="(item, index) in troubleList"
                :key="index"
            >
                {{ item }}
            </view>
        </view>
        <view class="submit" v-if="!success" hover-class="none" :hover-stop-propagation="false">
            <textarea class="bgf textarea br8 f14" :value="textVal" @input="getVal" maxlength="150" placeholder="我们想听到您的心声..." placeholder-class="f14 cccc"></textarea>
            <!-- <view class="" style="margin-top: 16px;">
      <image src="https://matripe-cms.oss-cn-beijing.aliyuncs.com/dailibaoming/my_uploadphotos.svg" 
             mode="widthFix" 
             style="width: 72px;height: 72px;" 
             bind:tap="handleUpdateImage"
      />
    </view>
    <view style="margin-top: 8px;font-size: 12px;color: #999999;">
      上传照片截图，最多传4张（选填）
    </view> -->
            <view class="weui-cell__bd1 mt20">
                <view class="weui-uploader__bd">
                    <view class="weui-uploader__files" id="uploaderFiles">
                        <block v-for="(item, index) in files" :key="index">
                            <view class="weui-uploader__file pr" @tap="previewImage" :id="item">
                                <image
                                    src="http://matripe.oss-cn-beijing.aliyuncs.com/nezha/del.svg"
                                    :data-id="item.id"
                                    :data-url="item.url"
                                    @click.stop="delImgs"
                                    class="delImg"
                                    style="width: 20px; height: 20px"
                                ></image>
                                <image @click.stop="showImgs" :mark:url="item.url" class="weui-uploader__img" :src="item.url" mode="aspectFill" />
                            </view>
                        </block>
                    </view>
                    <view class="weui-uploader__input-box" v-if="files.length < 4" @tap="chooseMedia">
                        <image src="https://matripe-cms.oss-cn-beijing.aliyuncs.com/dailibaoming/my_uploadphotos.svg" mode="widthFix" style="width: 72px; height: 72px" />
                        <!-- <view class="weui-uploader__input" bindtap="chooseMedia"></view> -->
                    </view>
                </view>
            </view>

            <view class="clb"></view>
            <view style="margin-top: 8px; font-size: 12px; color: #999999">上传照片截图，最多传4张（选填）</view>
            <button class="normalBtn loginOut f16" hover-class="thover" @tap="submit" style="margin-top: 90px" :loading="loading">提交</button>
        </view>
        <view class="success" v-else hover-class="none" :hover-stop-propagation="false">
            <view class="tc" style="padding-top: 100px">
                <i class="iconfont icon-tijiaochenggong lh1" style="color: #07c160; font-size: 70px"></i>
                <view class="successText mt20 f22 fw500 lh1">已提交</view>
                <view class="f14 c9 mt16" hover-class="none" :hover-stop-propagation="false">感谢您的宝贵意见，我们会第一时间处理哈~</view>
                <button class="normalBtn loginOut f16" hover-class="thover" @tap="goback" style="margin-top: 50px" :loading="loading">返回</button>
                <!-- <view class="tac mt16 f14" style="color:#576B95" bindtap="goList" hover-class="thover" hover-stop-propagation="false">查看记录</view> -->
            </view>
        </view>
    </view>
</template>

<script>
// pages/opinion/index.js
const app = getApp();
export default {
    data() {
        return {
            files: [],
            newAddImg: [],
            textVal: '',
            loading: false,
            subLoad: false,
            success: false,
            troubleList: ['投诉', '建议', '故障', '其他'],
            actived: 0,
            count: 4,
            urls: ''
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad(options) {},
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {},
    methods: {
        chooseMedia() {
            var that = this;
            console.log(that.count);
            uni.chooseMedia({
                count: that.count,
                mediaType: ['image'],
                sizeType: ['original', 'compressed'],
                sourceType: ['album', 'camera'],
                success(res) {
                    // tempFilePath可以作为 img 标签的 src 属性显示图片
                    uni.showLoading({
                        title: '上传中...'
                    });
                    console.log(res);
                    const tempFilePaths = res.tempFiles;
                    tempFilePaths.forEach((item, index) => {
                        uni.uploadFile({
                            url: app.globalData.ip + '/imgs/uploadImage',
                            method: 'post',
                            // data:currData,
                            // name: "uploadFile",
                            filePath: tempFilePaths[index].tempFilePath,
                            name: 'uploadFile',
                            header: app.globalData.headers,
                            success: function (res) {
                                console.log(that.files);
                                console.log(JSON.parse(res.data).data);
                                that.files.push({
                                    url: JSON.parse(res.data).data,
                                    id: -999
                                });
                                that.newAddImg.push(JSON.parse(res.data).data);
                                that.setData({
                                    files: that.files,
                                    newAddImg: that.newAddImg,
                                    count: 4 - that.files.length
                                });
                                // currData.data = JSON.parse(res.data);

                                that.pushImg();
                                // console.log(that.data.files);

                                // that.updateImgs(currData.type,currData.fkId,currData.data.data);
                            },
                            fail: function (res) {
                                console.log(res);
                            }
                        });
                        uni.hideLoading();
                    });
                }
            });
        },

        delImgs(e) {
            var that = this;
            var url = e.currentTarget.dataset.url;
            var id = e.currentTarget.dataset.id;
            console.log(that.files);
            uni.showModal({
                title: '提示',
                content: '确定要删除该图片？',
                confirmColor: '#00BEBE',
                success(res) {
                    if (res.confirm) {
                        that.files.forEach((item, index) => {
                            if (item.url == url) {
                                that.files.splice(index, 1);
                                that.newAddImg.splice(index, 1);
                            }
                        });
                        that.pushImg();
                        that.setData({
                            files: that.files,
                            newAddImg: that.newAddImg,
                            count: 4 - that.files.length
                        });
                    } else if (res.cancel) {
                        console.log('用户点击取消');
                    }
                }
            });
        },

        pushImg() {
            var that = this;
            console.log(that.files);
            that.urls = [];
            // that.data.files.forEach(item=>{
            //   that.data.urls.push(item.url)
            // })

            let curr = [];
            that.files.forEach((item) => {
                curr.push({
                    url: item.url,
                    id: item.id
                });
            });
            that.setData({
                urls: curr
            });
        },

        showImgs(e) {
            var that = this;
            console.log(that.urls);
            let curr = [];
            that.urls.forEach((item) => {
                curr.push(item.url);
            });
            uni.previewImage({
                current: e.mark.url,
                // 当前显示图片的 http 链接
                urls: curr // 需要预览的图片 http 链接列表
            });
        },

        handleUpdatType(e) {
            console.log(e);
            this.setData({
                actived: e.target.dataset.index
            });
        },

        handleUpdateImage() {
            uni.chooseMedia({
                count: 1,
                mediaType: ['image'],
                sourceType: ['album', 'camera'],
                maxDuration: 30,
                camera: 'back',
                success(res) {
                    console.log('获取上传数据：', res);
                    // 调用上传接口
                }
            });
        },

        /**
         * 意见提交事件
         *
         *
         */
        submit() {
            const that = this;
            if (that.subLoad) {
                return;
            }
            that.subLoad = true;
            console.log(that.newAddImg);
            // return
            // that.setData({
            //   success: true,
            //   loading: false,
            //   subLoad:false
            // });

            if (that.textVal.trim() != '') {
                console.log(312313123);
                that.setData({
                    loading: true
                });
                uni.request({
                    url: app.globalData.ip + '/daotian/feedback/add',
                    method: 'post',
                    header: app.globalData.headers,
                    data: {
                        content: that.textVal,
                        classify: Number(that.actived + 1),
                        imgs: that.newAddImg.toString(),
                        appId: app.globalData.appId
                    },
                    success: function (res) {
                        console.log(res);
                        if (res.data.status == 200) {
                            that.setData({
                                success: true
                            });
                        } else {
                            uni.showToast({
                                title: res.data.msg,
                                icon: 'none'
                            });
                        }
                        that.setData({
                            loading: false
                        });
                        that.subLoad = false;
                    },
                    fail: function (res) {
                        that.setData({
                            loading: false
                        });
                    }
                });
            } else {
                uni.showToast({
                    title: '请输入内容再提交',
                    icon: 'none'
                });
            }
        },

        getVal(e) {
            console.log(e);
            this.setData({
                textVal: e.detail.value
            });
            console.log(this.textVal);
        },

        goback() {
            // wx.navigateBack({
            //   delta: 1,
            // });
            uni.switchTab({
                url: '../../mine/index'
            });
        },

        goList() {
            uni.navigateTo({
                url: '/pages/opinionList/index'
            });
        },

        previewImage() {
            console.log('占位：函数 previewImage 未声明');
        }
    }
};
</script>
<style>
@import './index.css';
</style>
