// pages/index/components/listDetails/Details.js
const app = getApp()
const $request = require('../../utils/request.js');
const $util = require('../../utils/util.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        currentIndex: 1,
        pageLoading: true,
        tags: [],
        min: 0,
        max: 300,
        // 用户有无点击过tag
        isClickTag: false,
        // 选中tag
        selectedTag: [],
        detailValue: "",
        saveLoading: false,
        businessCommunicationDemandId: null,
        // 手动点击过选中标签
        setTags: false,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {
        
        const eventChannel = this.getOpenerEventChannel()
        if (eventChannel.on) {
            // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
            eventChannel.on('acceptDataFromOpenerPage', data => {
                let listDetail = data.listDetail;
                this.setData({
                    detailValue: listDetail.info,
                    selectedTag: listDetail.type,
                    businessCommunicationDemandId: listDetail.businessCommunicationDemandId,
                    setTags:true,
                })
            })
        }
        this.getTags();
    },
    onShow(){
        this.setData({
            currentIndex: 1
        })
    },
    // 输入框输入
    textareaInput(e) {
        let value = e.detail.value;
        let len = e.detail.cursor;;
        this.setData({
            min: len
        });
        this.setData({
            detailValue: value
        })
    },
    // 拾取焦点触发
    textareaBlur() {
        // let tags = this.data.tags;
        let { detailValue, tags, setTags} = this.data;
        let value = this.trimRight(detailValue);
        // 如果手动选择过tag不再处理
        if (setTags || !value) {
            return
        }
        let selectedTag = [];
        tags.forEach((el,inx)=>{
            el.isActive = '';
            el.needKeyword = el.keyword ? el.keyword.split(',') : [];
            el.needKeyword.forEach(subel => {
                if(value.indexOf(subel) != -1 && selectedTag.length < 4){
                    if(selectedTag.indexOf(el.typeName) == -1){
                        selectedTag.push(el.typeName);
                        el.isActive = 'active' + selectedTag.indexOf(el.typeName);
                    }
                }
            })
        })
        if(selectedTag.length < 1){
            selectedTag.push(tags[tags.length - 1].typeName);
            tags[tags.length - 1].isActive = 'active' + 0;
        }
        this.setData({
            selectedTag,
            tags,
        })
    },
    // tag选择切换
    tagSelectedChange(e) {
        let typename = e.currentTarget.dataset.typename;
        let selectedTag = this.data.selectedTag;
        // 1 如果选中的数组里没有当前type
        if (selectedTag.indexOf(typename) == -1) {
            // 2 如果选中的数组的长度小于3 直接push
            if (selectedTag.length < 3) {
                selectedTag.push(typename)
            }
        }
        // 3 如果选中的数组里有它，直接删除
        else {
            selectedTag.forEach((el, inx) => {
                if (el == typename) {
                    selectedTag.splice(inx, 1);
                }
            })
        }
        
        let tags = this.data.tags;
        tags.forEach(el => {
            el.isActive = '';
            if (selectedTag.indexOf(el.typeName) != -1) {
                el.isActive = 'active' + selectedTag.indexOf(el.typeName);
            }
        })
        this.setData({
            selectedTag,
            tags,
            setTags: true
        })
        // console.log(this.data.selectedTag,'selectedTag');
        // console.log(this.data.tags,'tags');
    },
    // 发布需求
    releaseDemands() {
        this.setData({
            saveLoading: true
        })
        let { selectedTag, detailValue, businessCommunicationDemandId } = this.data;
        let param = {
            customerId: app.globalData.customerId,
            info: this.trimRight(detailValue),
            type: selectedTag.join(','),
            businessCommunicationDemandId,
        };
        $request.post('/businessCommunicationDemand/saveDemand.action', param).then(res => {
            this.setData({
                saveLoading: false
            })
            let that = this;
            if (res.status == 0) {
                if (!businessCommunicationDemandId) {
                    wx.showModal({
                        title: '发布成功',
                        content: "请关注平台公众号，如有咨询，可及时接收消息通知！",
                        confirmText: "去关注",
                        cancelText: "关闭",
                        success(res1) {
                            if (res1.confirm) {
                                that.clearData();
                                wx.navigateTo({
                                    url: "/pages/outLink/outLink?followApplets=true", //跳转页面的路径，可带参数 ？隔开，不同参数用 & 分隔；相对路径，不需要.wxml后缀
                                    success: function () { }, //成功后的回调；
                                    fail: function () { }, //失败后的回调；
                                    complete: function () { } //结束后的回调(成功，失败都会执行)
                                })
                            } else if (res1.cancel) {
                                let listDetail = res.data;
                                that.clearData();
                                wx.reLaunch({
                                    url: '/pages/index/components/listDetails/Details?businessCommunicationDemandId=' + listDetail.businessCommunicationDemandId,
                                })
                            }
                        }
                    })
                } else {
                    wx.showLoading({
                        title: '修改成功',
                        mask: true
                    })
                    setTimeout(() => {
                        wx.hideLoading()
                        let pages = getCurrentPages();
                        let Page = pages[pages.length - 1];//当前页
                        let prevPage = pages[pages.length - 2];  //上一个页面
                        let info = prevPage.data //取上页data里的数据也可以修改
                        let tempListData = info.listData;
                        tempListData.forEach(el => {
                            if (el.businessCommunicationDemandId == businessCommunicationDemandId) {
                                el.info = Page.data.detailValue
                            }
                        })
                        prevPage.setData({ listData: tempListData })//设置数据
                        wx.navigateBack()
                    }, 1000);
                }

            } else if (res.status == 501) {
                wx.showModal({
                    title: '发布失败',
                    content: res.msg,
                    showCancel: false,
                })
            }
        }).catch(err => {
            console.log(err);
            this.setData({
                saveLoading: false
            })
        })
    },
    clearData() {
        let tags = this.data.tags;
        tags.forEach(el => {
            el.isActive = '';
        })
        this.setData({
            selectedTag: [],
            detailValue: "",
            tags
        })
    },
    trimRight(s) {
        if (s == null) return "";
        var whitespace = new String(" \t\n\r");
        var str = new String(s);
        if (whitespace.indexOf(str.charAt(str.length - 1)) != -1) {
            var i = str.length - 1;
            while (i >= 0 && whitespace.indexOf(str.charAt(i)) != -1) {
                i--;
            }
            str = str.substring(0, i + 1);
        }
        return str;
    },
    // 获取tag
    getTags() {
        this.setData({
            pageLoading: true,
        })
        $request.get('/businessCommunicationType/getAllType.action').then(res => {
            this.setData({
                pageLoading: false,
            })
            if (res.status == 0) {
                let datas = res.data;
                let selectedTag = this.data.selectedTag;
                datas.forEach(el => {
                    el.isActive = "";
                    if (selectedTag.indexOf(el.typeName) != -1) {
                        el.isActive = 'active' + selectedTag.indexOf(el.typeName);
                    }
                })
                this.setData({
                    tags: datas,
                })
            }
        }).catch(error => {
            console.log(error, 'error appletLogin')
        })
    },
})