import {
    allInstanceList,
    readDeployNotes,
    findCommentByProcInsId
} from '../../../api/flowable'
import {
    createQr,
    editApplyChecked,
    addApplyDetailCheck,
    findApplyDetailAllCheck
} from '../../../api/projectApply'
import {
    findProjectApplyData
} from '../../../api/publics'
import config from '../../../config'
const app = getApp()
Page({
    /**
     * 页面的初始数据
     */
    data: {
        options: {},
        active: 100,
        stepList: [],
        activeName: "",
        flowRecordList: [],
        infoData: {},
        fileNames: [],
        minImageList: [],
        imgTypes: ["png", "jpg", "jpeg"],
        stopBtnShow: false,
        popupShow: false,
        actIdx: 0,
        popupId: null,
        popupUnit: "吨",
        popupNumber: "",
        popupPrices: "",
        baseUrl: config.baseUrl,
        popupViewShow: false,
        checkDirection: "vertical",
        checkStepList:[],
        isCheckRole: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let roles = app.globalData.userData.roles;
        if(roles!=null && roles.length>0){
            roles.forEach(role =>{
                if(role.roleId==88){
                    this.setData({
                        isCheckRole: true,
                    })
                }
            });
        }
        allInstanceList({
            'businessKey': options.businessKey
        }).then(res => {
            this.setData({
                options: res.rows[0]
            })
            this.findFlowNodes();
            this.findCommentByProcInsId();
        });
        this.findApplyDataInfo(options.businessKey);
    },

    //查询工作流节点
    findFlowNodes() {
        readDeployNotes(this.data.options.deployId).then(res => {
            let list = [{
                text: '开始'
            }];
            res.data.forEach((item, idx) => {
                list.push({
                    text: item.name,
                    desc: ''
                });
            });
            list.push({
                text: '结束'
            });
            this.setData({
                stepList: list
            })
        });
    },

    //查询审批日志
    findCommentByProcInsId() {
        findCommentByProcInsId({
            procInsId: this.data.options.procInsId
        }).then(res => {
            this.setData({
                flowRecordList: res.data
            })
            let list = [];
            res.data.forEach((item, idx) => {
                if (item.deleteReason) {
                    item.deleteReason = this.getDeleteReason(item.deleteReason);
                }
                if (item.duration) {
                    item.duration = app.getDurationDate(item.duration);
                }
                list.push(item);
            })
            this.setData({
                flowRecordList: list
            })
        });
    },

    //查询审批表单参数
    findApplyDataInfo(businessKey) {
        findProjectApplyData(businessKey).then(res => {
            let imgList = [];
            let fileNames = [];
            if (res.data.applyFiles) {
                res.data.applyFiles.split(',').forEach(files => {
                    let fileType = files.split(".")[files.split(".").length - 1].toLowerCase();
                    if (this.data.imgTypes.indexOf(fileType) == -1) {
                        let it = files.split('/');
                        fileNames.push({
                            name: it[it.length - 1],
                            path: files
                        });
                    } else {
                        imgList.push({
                            murl: config.baseUrl + files + '.min.jpg',
                            path: files
                        });
                    }
                });
            }
            this.setData({
                infoData: res.data,
                fileNames: fileNames,
                minImageList: imgList
            })
        })
    },

    // 手风琴
    onChange(event) {
        this.setData({
            activeName: event.detail,
        });
    },

    /**
     * 获取驳回节点
     * @param {*} val 
     */
    getDeleteReason(val) {
        val = val.replace("Change activity to ", "");
        let flowRecordList = this.data.flowRecordList;
        for (let i = 0; i < flowRecordList.length; i++) {
            if (flowRecordList[i].taskDefKey == val) {
                return "驳回至" + flowRecordList[i].taskName;
            }
        }
    },

    /**
     * 下载并打开文档
     * @param {*} e 
     */
    downFile: function (e) {
        let {
            path
        } = e.currentTarget.dataset.set
        wx.downloadFile({
            // 示例 url,并非真实存在
            url: config.baseUrl + '/common/download/resource?resource=' + path,
            success: function (res) {
                const filePath = res.tempFilePath
                let fpt = filePath.split(".");
                wx.openDocument({
                    filePath: filePath,
                    fileType: fpt[fpt.length - 1],
                    success: function (res) {
                        console.log('打开文档成功')
                    },
                    fail: function (res) {
                        console.log(res)
                    }
                })
            }
        })
    },

    //选择退回节点
    onSelectTargetKey(e) {
        this.setData({
            targetKey: e.detail.id,
            backName: e.detail.name
        })
    },

    returnToPage: function () {
        /*关闭当前页面,跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面*/
        wx.redirectTo({
            url: '../list/index',
        })
    },

    createQrSub(){
        createQr(this.data.options.businessKey).then(res =>{
            if(res.code==200){
                this.setData({
                    "infoData.qrPath": res.data.qrPath
                })
            }
        });
    },

    /**
     * 左侧抽屉显示
     */
    showPopup(e) {
        let index = e.currentTarget.dataset.index
        this.setData({
            actIdx: index,
            popupId: this.data.infoData.proProjectApplyDetailList[index].id,
            popupUnit: this.data.infoData.proProjectApplyDetailList[index].assetsUnit,
            popupShow: true
        });
    },

    /**
     * 左侧抽屉隐藏
     */
    onClosePopup() {
        this.setData({
            popupShow: false
        });
    },

    /**
     * 左侧抽屉显示
     */
    showViewPopup(e) {
        let index = e.currentTarget.dataset.index
        let unit = this.data.infoData.proProjectApplyDetailList[index].assetsUnit;
        let detailId = this.data.infoData.proProjectApplyDetailList[index].id;
        findApplyDetailAllCheck(detailId).then(res =>{
            let list = [];
            res.data.forEach(item =>{
                let desc = "【"+item.createBy+"】 验收"+item.checkValue+" "+unit+",单价 "+item.checkPrice;
                list.push({text: item.createTime, desc: desc })
            });
            this.setData({
                popupViewShow: true,
                checkStepList: list,
            });
        })
        
    },

    /**
     * 左侧抽屉隐藏
     */
    onCloseViewPopup() {
        this.setData({
            popupViewShow: false
        });
    },

    //展示图片
    showImg:function(e){
        let paths = e.target.dataset.set;
        let path = [];
        paths.split(',').forEach(url => {
            path.push(config.baseUrl + url);
        });
        wx.previewImage({
            urls: path,
            current: path[0]
        })
    },
    
    /**
     * 添加验收信息
     */
    onAddChecked() {
        let {
            popupId,
            popupNumber,
            popupPrices
        } = this.data;
        if (!popupId) {
            app.toast("数据异常,请刷新页面重试!")
            return false;
        }
        if (!popupNumber) {
            app.toast("请填写验收数量!")
            return false;
        }
        if (!popupPrices) {
            app.toast("请填写验收单价!")
            return false;
        }
        addApplyDetailCheck({'detailId':popupId,'checkValue':popupNumber,'checkPrice':popupPrices}).then(res =>{
            if(res.code==200){
                // let da = this.data.infoData;
                // da.proProjectApplyDetailList[this.data.actIdx].isChecked==1;
                // da.proProjectApplyDetailList[this.data.actIdx].checkedTotalValue = parseFloat(da.proProjectApplyDetailList[this.data.actIdx].checkedTotalValue)+parseFloat(popupNumber);
                // this.setData({
                //     popupShow: false,
                //     infoData:da,
                //     popupNumber:"",
                //     popupPrices:"",
                // });
                this.setData({
                    popupNumber:"",
                    popupPrices:"",
                    popupShow: false
                });
                this.onLoad({'businessKey':this.data.options.businessKey});
            }
        });
    },
    
    //保存验收结果
    onCheckedSave(){
        for(let i=0;i<this.data.infoData.proProjectApplyDetailList.length;i++){
            if(this.data.infoData.proProjectApplyDetailList[i].isChecked==0){
                app.toast(this.data.infoData.proProjectApplyDetailList[i].assetsName+" 还未验收完成!")
                return false;
            }
        }
        let that = this;
        wx.showModal({
            title: '提示',
            content: '是否确定全部验收完成?',
            success: function (sm) {
                if (sm.confirm) {
                    that.submit();
                } else if (sm.cancel) {
                    console.log('用户点击取消');
                }
            }
        })
    },

    submit(){
        editApplyChecked({'id':this.data.options.businessKey,'applyStatus':"100"}).then(res=>{
            if(res.code==200){
                wx.redirectTo({
                    url: '../list/index',
                })
            }
        })
    },

    //输入验收数量
    onInputCheckNumber(e) {
        let value = e.detail.value;
        this.setData({
            popupNumber: value
        })
    },

    //输入验收单价
    onInputCheckPrices(e) {
        let value = e.detail.value;
        this.setData({
            popupPrices: value
        })
    },

    onAddDetail(){
        wx.redirectTo({
            url: '../edit/index?id='+this.data.infoData.id+"&applyType="+this.data.infoData.applyType,
        })
    },

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

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

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

    },

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

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})