let util = require('../../../../utils/util')
let apiArr = require('../../../../api/water_filter')
let apiArr2 = require('../../../../api/partner')
const app = getApp({ allowDefault: true })

// packages/WaterPurifier/pages/upKeep/upKeep.js
const __staticUrl = require('../../../../config/env.js').static_url
Page({

    /**
     * 页面的初始数据
     */
    data: {
        s: app.system.statusBarHeight, // 状态栏高度
        n: (app.menu.top - app.system.statusBarHeight) * 2 + app.menu.height, // 导航栏高度
        t: app.menu.top, // 胶囊局顶部距离
        h: app.menu.height, // 胶囊高度
        stateType: {
            1: '待分配',
            2: '维修中',
            3: '维修成功',
            4: '已撤销',
        },
        option1: [
            { text: '全部', value: 0 },
            { text: '待分配', value: 1 },
            { text: '维修中', value: 2 },
            { text: '维修成功', value: 3 },
            { text: '已撤销', value: 4 },
        ],
        value1: 0,
        show: false,
        MasterList: [],
        orderList: [],
        page_num: 1,
        page_size: 10,
        total: '',
        flag: false,
        sendOrders: {},
        searchText: "",
    },
    back(){
        wx.reLaunch({
          url: '/packages/partner/pages/partner',
        })
    },
    ipt1(e) {
        let that = this
        console.log(e);
        that.setData({
            searchText: e.detail.value,
        })
    },
    onClose() {
        let that = this
        that.setData({
            show: false
        })
    },
    dispatch(e) {
        let that = this
        that.setData({
            show: true,
            sendOrders: e.currentTarget.dataset.item
        })
    },

    addOrder() {
        wx.navigateTo({
            url: '/packages/partner/pages/addNewOrder/addNewOrder',
        })
    },

    desc(e) {
        let that = this
        wx.navigateTo({
            url: `/packages/partner/pages/OrderMsgInfo/OrderMsgInfo?id=${e.currentTarget.dataset.id}&type=1`,
        })
    },

    headerDropdownClick(e) {
        this.setData({
            value1: e.detail,
            orderList: [],
            page_num: 1,
        })
        this.getOrderList();
    },

    // 撤回工单
    headerRecallClick(e) {
        const _this = this;
        const { item } = e.currentTarget.dataset;
        console.log('eitmeitmeitmeitme', item)
        wx.showLoading({
            title: '加载中...',
            mask: true
        })

        util.postUrl4(apiArr.RecallRepair, {
            status: 4,
            repair_id: item.repair_id,
        }, res => {
            wx.hideLoading()
            if (res.error) {
                wx.showToast({
                    title: '撤回工单失败',
                    icon: 'none',
                })
                return;
            }
            wx.showToast({
                title: res.msg,
                icon: 'none',
                success() {
                    setTimeout(() => {
                        _this.setData({
                            orderList: [],
                            page_num: 1,
                            flag: false
                        })
                        _this.getOrderList();
                    }, 2000)
                }
            })
        })
    },
    search() {
        let that = this
        that.setData({
            orderList: []
        })
        this.getOrderList();
    },
    getOrderList(name) {
        let that = this
        //设置加载状态
        wx.showLoading({
            title: '加载中...',
            mask: true
        });

        let admin = wx.getStorageSync('admin')
        let param = {
            status: that.data.value1,
            page_num: that.data.page_num,
            page_size: that.data.page_size,
            dealer_id: admin.shop_id,
            search: that.data.searchText,
        };
        if (name) {
            param = {
                ...param,
                customer_name: name
            }
        };

        util.postUrl4(apiArr2.getOrderPairList, param, res => {
            console.log('rererererererere', res);
            wx.hideLoading()
            let flag = false
            if (res.rows.length == that.data.page_size) {
                flag = true
            } else {
                flag = false
            }
            that.setData({
                orderList: that.data.orderList.concat(res.rows || []),
                page_num: that.data.page_num + 1,
                flag
            })
            console.log(that.data.flag);
        })
    },

    headerInputClick(e) {
        const that = this;
        that.setData({
            orderList: [],
            page_num: 1,
            flag: false
        }, () => {
            this.getOrderList(e.detail.value);
        })
    },

    //师傅列表
    getMasterList() {
        let that = this
        wx.showLoading({
            title: '加载中...',
            mask: true
        })

        util.postUrl4(apiArr.MasterList, {
            page_num: 1,
            page_size: 100,
            dealer_id: wx.getStorageSync('dealer_id')
        }, res => {
            wx.hideLoading()
            res.rows.forEach(item => {
                item.avatar = util.img_url + item.avatar
            })

            that.setData({
                MasterList: res.rows
            })
        })
    },
    //选择师傅
    selectMaster(e) {
        console.log(e);
        let that = this
        let MasterList = that.data.MasterList
        MasterList.forEach(item => {
            item.checked = false
        })
        MasterList[e.currentTarget.dataset.index].checked = true
        that.setData({
            MasterList
        })
    },
    //确定
    sure() {
        let that = this
        const { sendOrders, MasterList } = this.data;
        const checkedMaster = MasterList.filter((item) => item.checked)[0];
        console.log('sendOrders', sendOrders);
        console.log('checkedMaster', checkedMaster);
        that.setData({
            show: false
        })
        util.postUrl4(apiArr2.assignRepairMaster, {
            master_id: checkedMaster.info_id,
            repair_id: sendOrders.repair_id,
        }, res => {
            if (res.error) {
                wx.showToast({
                    title: '派单失败',
                    icon: 'none',
                })
                return;
            }
            wx.showToast({
                title: res.msg,
                icon: 'none',
                success() {
                    setTimeout(() => {
                        that.setData({
                            flag: false,
                            page_num: 1,
                            orderList: []
                        })
                        that.getOrderList()
                    }, 1500)
                }
            })
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let that = this
        // that.getFootNav()
        // that.getOrderList()
        that.getMasterList()
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.setData({
            page_num: 1,
            orderList: [],
        })
        this.getOrderList()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        let that = this
        that.setData({
            page_num: 1,
            orderList: [],
            flag: false
        })
        that.getOrderList()
        wx.stopPullDownRefresh();
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        let that = this
        console.log(123, that.data.flag);
        if (that.data.flag) {
            this.getOrderList()
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
        return {
            title: '人人爱净水',  // 分享卡片标题（必填）
            path: '/pages/water_filter/water_filter',  // 用户点击后跳转的路径（可选，默认当前页）
            imageUrl: (__staticUrl + '/share.png')  // 自定义图片（可选，比例建议 5:4）
        }
    },
    onShareTimeline() {
        return {
            title: '人人爱净水', // 自定义标题
            query: '', // 自定义页面路径中的参数
            imageUrl: (__staticUrl + '/share.png') // 自定义分享图片路径
        }
    },
})