const _Http = getApp().globalData.http;
Page({
    data: {
        tabsActive: 0, //tabs 选中项
        sys_taskid: "",
        detail: '',
        tabsList: [{
            label: "详细信息",
            icon: "icon-tabxiangxixinxi1"
        }, {
            label: "跟进动态",
            icon: "icon-tabgenjinjilu"
        }, {
            label: "操作",
            icon: "icon-tabcaozuojilu1"
        }, {
            label: "附件",
            icon: "icon-tabfujian1",
            model: "#Files"
        }],
        tabbarList: [],
        confirmShow: false,
        finishnotes: "", //完成说明
        sColors: getApp().globalData.sColors,
    },
    onLoad(options) {
        getApp().globalData.Language.getLanguagePackage(this, '任务详情')
        this.setData({
            sys_taskid: options.id
        });
        this.getDetail();
        getApp().globalData.previewClick = this.previewClick.bind(this);
    },
    /* 完成情况说明输入 */
    areaInput(e) {
        this.setData({
            finishnotes: e.detail.value
        })
    },
    onConfirm(e) {
        _Http.basic({
            "id": 20221211112501,
            "content": {
                "sys_taskid": this.data.sys_taskid,
                "finishnotes": this.data.finishnotes
            }
        }).then(res => {
            console.log("完成情况说明", res)
            wx.showToast({
                title: res.code == '1' ?  getApp().globalData.Language.getMapText('提交成功') : res.msg,
                icon: "none"
            })
            if (res.code == '1') setTimeout(this.getDetail, 500)
        })
    },
    /* 取消提交说明 */
    onCancel(e) {
        this.setData({
            confirmShow: false
        })
    },
    previewClick({
        label,
        value
    }) {
        if (label == '关联应用数据') {
            const detail = this.data.detail;
            if (detail.ownerid) {
                const authComparison = wx.getStorageSync('authComparison');
                //判断具体消息归属
                switch (detail.ownertable) {
                    case "sa_customers":
                        this.saCustomer(detail.ownerid);
                        break;
                    case "sat_orderclue":
                        this.satOrderclue(detail.ownerid);
                        break;
                    case "sa_order":
                        this.saOrder(detail.ownerid)
                        break;
                    case "sa_salesforecastbill":
                        let url = detail.baseonproject == 1 ? '/packageA/finishforecast/detail' : '/packageA/invoiceforecast/detail';
                        wx.navigateTo({
                            url: url + "?id=" + detail.ownerid,
                        })
                        break;
                    case "sys_phonebook":
                        wx.navigateTo({
                            url: `/packageA/contacts/detail?id=${detail.ownerid}&contactsid=0&sa_project_contactsid=0`,
                        })
                        break;
                    case "sys_enterprise_contacts":
                        wx.navigateTo({
                            url: `/packageA/contacts/detail?id=0&contactsid=${detail.ownerid}&sa_project_contactsid=0`,
                        })
                        break;
                    case "sa_project_contacts":
                        wx.navigateTo({
                            url: `/packageA/contacts/detail?id=0&contactsid=0&sa_project_contactsid=${detail.ownerid}`,
                        })
                        break;
                    default:
                        let data = authComparison.find(s => (s.objectname || "") == detail.ownertable);
                        if (data) wx.navigateTo({
                            url: data.path.split("/index")[0] + "/detail?id=" + detail.ownerid,
                        })
                        break;
                }
            }
        }
    },
    saOrder(sa_orderid) {
        _Http.basic({
            "id": 20221108151302,
            "content": {
                nocache: true,
                sa_orderid
            }
        }).then(res => {
            console.log("订单", res)
            if (res.code != '1') return wx.showToast({
                title: res.data,
                icon: "none"
            });
            let path = '';
            switch (res.data.type) {
                case '工具借用单':
                    path = '/packageA/borrow/detail'
                    break;
                case '借用归还单':
                    path = '/packageA/toolBill/detail'
                    break;
                default:
                    path = '/packageA/orderForm/detail'
                    break;
            }

            wx.navigateTo({
                url: path + '?id=' + sa_orderid,
            })
        });
    },
    satOrderclue(sat_orderclueid) {
        _Http.basic({
            "classname": "saletool.orderclue.web.orderclue",
            "method": "selectDetail",
            "version": 1,
            "content": {
                "nocache": true,
                sat_orderclueid
            },
        }).then(res => {
            console.log("线索详情", res)
            if (res.code != '1') return wx.showToast({
                title: res.data,
                icon: "none"
            });
            wx.navigateTo({
                url: (res.data.isprivate ? '/packageA/saleClue/detail' : '/packageA/publicClue/detail') + '?id=' + sat_orderclueid,
            })
        });
    },
    saCustomer(sa_customersid) {
        _Http.basic({
            "id": 20221012164302,
            "content": {
                sa_customersid
            },
        }).then(res => {
            console.log("医院详情", res)
            if (res.code != '1') return wx.showToast({
                title: res.data,
                icon: "none"
            });

            wx.navigateTo({
                url: (res.data.ispublic ? '/packageA/publicCustomer/detail' : '/packageA/setclient/detail') + '?id=' + sa_customersid,
            })
        });
    },
    getDetail() {
        _Http.basic({
            "id": 20221211111901,
            "content": {
                "nocache": true,
                "sys_taskid": this.data.sys_taskid
            },
        }).then(res => {
            console.log("任务详情", res)
            if (res.code != '1') return wx.showToast({
                title: res.msg,
                icon: "none"
            });
            let tabbarList = [{
                icon: "color-genjin",
                label: "跟进"
            }];
            if (res.data.status != '已完成') tabbarList.push({
                icon: "icon-dibu-chengjiao",
                label: "完成"
            })
            try {
                let isLeader = res.data.createuserid == wx.getStorageSync('userMsg').userid;
                if (isLeader) {
                    tabbarList.splice(1, 0, {
                        icon: "icon-shanchu",
                        label: "删除"
                    })
                    tabbarList.splice(1, 0, {
                        icon: "icon-guanlian-bianji",
                        label: "编辑"
                    })
                }
            } catch (error) {}
            this.setData({
                tabbarList,
                detail: res.data,
                briefs: [{
                        label: "任务内容",
                        value: res.data.remarks
                    }, {
                        label: "开始日期",
                        value: res.data.starttime
                    }, {
                        label: "结束日期",
                        value: res.data.endtime
                    },
                    {
                        label: '关联应用数据',
                        value: res.data.title
                    }, {
                        label: '状态',
                        value: getApp().globalData.Language.getMapText(res.data.status),
                        style:`color:${this.data.sColors[res.data.status]}`
                    }
                ],
                list1: [{
                    label: "任务标题",
                    value: res.data.title
                }, {
                    label: "任务内容",
                    value: res.data.remarks
                }, {
                    label: "开始日期",
                    value: res.data.starttime
                }, {
                    label: "结束日期",
                    value: res.data.endtime
                }, {
                    label: "执行人",
                    value: res.data.leader[0].name
                }, {
                    label: "协助人",
                    value: ""
                }, {
                    label: '关联应用数据',
                    value: res.data.title,
                    color: "#085CDF",
                    slot: 'title'
                }, {
                    label: '状态',
                    value: getApp().globalData.Language.getMapText(res.data.status),
                    style:`color:${this.data.sColors[res.data.status]}`
                }, {
                    label: '完成说明',
                    value: res.data.finishnotes
                }],
                list2: [{
                    label: "创建人",
                    value: res.data.createby
                }, {
                    label: "创建时间",
                    value: res.data.createdate
                }, {
                    label: "最近编辑人",
                    value: res.data.changeby
                }, {
                    label: "最近编辑时间",
                    value: res.data.changedate
                }, {
                    label: "完成人",
                    value: res.data.finishby
                }, {
                    label: "完成时间",
                    value: res.data.finishdate
                }, {
                    label: "转手次数",
                    value: res.data.leader.length ? res.data.leader[0].leadernum : 0
                }]
            });
            /* 更新列表中状态 */
            let page = getCurrentPages().find(v => v.__route__ == 'packageA/saleClue/index');
            if (page) {
                let index = page.data.list.findIndex(v => v.sys_taskid == res.data.sys_taskid);
                if (index != -1) page.setData({
                    [`list[${index}].status`]: res.data.status,
                    [`list[${index}].title`]: res.data.title,
                    [`list[${index}].remarks`]: res.data.remarks

                })
            } else {
                let pages = getCurrentPages(),
                    p = pages[pages.length - 2].selectComponent("#Work");
                if (p) {
                    let index = p.data.list.findIndex(v => v.sys_taskid == res.data.sys_taskid);
                    if (index != -1) p.setData({
                        [`list[${index}].status`]: res.data.status,
                        [`list[${index}].title`]: res.data.title,
                        [`list[${index}].remarks`]: res.data.remarks
                    })
                }
            }
            this.getTags();
            this.getGroup();
            this.partialRenewal();
        })
    },
    //tabs 切换
    tabsChange({
        detail
    }) {
        this.setData({
            tabsActive: detail
        });
        this.partialRenewal();
    },
    //更新标签
    getTags() {
        this.selectComponent("#Tags").getTags();
    },
    //更新团队成员
    getGroup() {
        this.selectComponent("#Group").getList().then(res => {
            let i = this.data.list1.findIndex(v => v.label == '协助人')
            this.setData({
                [`list1[${i}].value`]: res.filter(v => !v.isleader).map(v => v.name)
            })
        });
    },
    onClose() {
        this.setData({
            show: false
        });
    },
    //局部数据更新 tabs
    partialRenewal(init = false) {
        let id = this.data.detail.sys_taskid;
        let model = '';
        let name = this.data.tabsList[this.data.tabsActive].label;
        switch (name) {
            case "操作":
                model = "#Record"
                break;
            case "跟进动态":
                model = "#Trace"
                break;
            case "附件":
                model = "#Files"
                break;
        };
        if (model) {
            // 确定好模块ID total = null 是第一次加载 加载数据
            // init是新增或修改需要清数据
            let Component = this.selectComponent(model);
            const {
                total,
                pageNumber,
                pageTotal
            } = Component.data.content;
            if (total == null || init) {
                Component.getList(id, init);
            } else if (pageNumber <= pageTotal) {
                Component.getList(id, false);
            } else {
                //用来判断 在搜索页面修改，与tabs选项不一致 但是切换到该选项 重置数据
            }
        }
    },
    onReachBottom() {
        this.partialRenewal();
    },
    //详情按钮回调
    tabbarOnClick({
        detail
    }) {
        let that = this;
        switch (detail.label) {
            case "编辑":
                let group = this.selectComponent("#Group").query();
                wx.navigateTo({
                    url: `/packageA/work/add?data=${JSON.stringify(this.data.detail)}&group=${JSON.stringify(group)}`,
                })

                break;
            case "完成":
                this.setData({
                    confirmShow: true
                })
                break;
            case "跟进":
                wx.navigateTo({
                    url: `/prsx/trace/add/index?ownertable=sys_task&ownerid=${this.data.sys_taskid}&resource=任务`,
                })
                break;
            case "删除":
                wx.showModal({
                    title: getApp().globalData.Language.getMapText('提示'),
                    content: getApp().globalData.Language.getMapText(`是否要删除当前任务`) + '?',
                    cancelText: getApp().globalData.Language.getMapText('取消'),
                    confirmText: getApp().globalData.Language.getMapText('确定'),
                    complete: (res) => {
                        if (res.confirm) _Http.basic({
                            "id": 20221211112601,
                            "content": {
                                "sys_taskids": [that.data.detail.sys_taskid]
                            }
                        }).then(res => {
                            console.log("删除任务", res)
                            wx.showToast({
                                title: res.code == '1' ? getApp().globalData.Language.getMapText('删除成功') : res.msg,
                                icon: "none",
                                mask: res.code == '1'
                            })
                            if (res.code == '1') setTimeout(() => {
                                wx.navigateBack()
                            }, 800)
                        })
                    }
                })
                break;
        }
    },
    onUnload() {
        let page = getCurrentPages()[getCurrentPages().length - 2]
        if (page.__route__ == 'packageA/work/index') {
            let content = JSON.parse(JSON.stringify(page.data.content));
            content.pageSize = (content.pageNumber - 1) * content.pageSize;
            content.pageNumber = 1;
            _Http.basic({
                id: '20220901162901',
                content
            }).then(res => {
                console.log("更新任务列表", res);
                if (res.code == '1') page.setData({
                    list: res.data,
                    "content.total": res.total
                })
            })
        } else {
            page.getTags && page.getTags()
            page.partialRenewal && page.partialRenewal(true)
        }
    },
    startSynchronization() {
        console.log("开始同步")
        wx.navigateTo({
            url: '/packageA/work/synchronization?data=' + JSON.stringify({
                ownertable: this.data.detail.ownertable,
                ownerid: this.data.detail.ownerid
            }),
        });
        _Http.selectSync = (item, ownertable) => {
            if (["sys_task", "sa_customers", "sa_project"].includes(ownertable)) {
                this.setData({
                    finishnotes: `跟进类型：${item.type}\n跟进对象：${item.contacts ? item.contacts.join(","):""}\n${item.content}`
                })
            } else if (ownertable == 'sat_orderclue') {
                this.setData({
                    finishnotes: `跟进类型：${item.followupmode}\n跟进内容：${item.content}`
                })
            } else {
                this.setData({
                    finishnotes: '跟进内容：' + item.content
                })
            }
            wx.navigateBack()
            delete(_Http.selectSync)
        }
    },
})