const _Http = getApp().globalData.http;
Page({
    data: {
        loading: true,
        isLeader: false, //是否为负责人
        tabsActive: 1, //tabs 选中项
        sa_customersid: 0,
        sColors: getApp().globalData.sColors,
        deletereasonShow: false,
        deletereason: "",
    },
    onLoad(options) {
        const appAuth = wx.getStorageSync('auth').wCustomer;
        let tabsList = [{
            label: "详细信息",
            icon: "icon-tabxiangxixinxi1"
        }, {
            label: "地址管理",
            icon: "icon-tabdizhi",
            model: "#Address"
        }];
        this.setData({
            sa_customersid: options.id,
            tabsList,
            appAuth
        })
        this.getDetail();
        getApp().globalData.Language.getLanguagePackage(this, '医院详情');
    },

    /* 获取详情 */
    getDetail() {
        /* 基本信息 */
        _Http.basic({
            "id": 20221012164302,
            "content": {
                sa_customersid: this.data.sa_customersid
            },
        }).then(res => {
            console.log("详情", res)
            if (res.code != '1') return wx.showToast({
                title: res.data,
                icon: "none"
            })
            this.setPreview(res);
            this.setData({
                loading: false,
                detail: res.data,
            })
            //获取标签
            if (this.data.appAuth.isdatatag) this.getTags();
            if (this.data.appAuth.isdatateam) this.getGroup()
            this.setTabbar();
            this.partialRenewal();
        });
    },
    areaInput(e) {
        this.setData({
            deletereason: e.detail.value
        })
    },
    onCancel() {
        this.setData({
            deletereasonShow: false,
        })
    },
    deleteItem() {
        _Http.basic({
            id: 20221010164402,
            content: {
                deletereason: this.data.deletereason,
                sa_customersids: [this.data.sa_customersid],
                datastatus: '1'
            }
        }).then(res => {
            console.log("作废", res)

            wx.showToast({
                title: res.code == 1 ? '作废成功' : res.msg,
                icon: "none",
                mask: res.code == 1
            })

            if (res.code == 1) setTimeout(() => {
                wx.navigateBack()
            }, 300)
        })
    },
    setPreview(res) {
        /* 摘要信息 */
        let briefs = [{
            label: "医院编号",
            value: res.data.billno
        }, {
            label: "医院等级",
            value: res.data.grade
        }, {
            label: "医院类型",
            value: res.data.type
        }, {
            label: "开发阶段",
            value: res.data.stagename
        }, {
            label: "开发状态",
            value: getApp().globalData.Language.getMapText(res.data.status),
            style: `color:${this.data.sColors[res.data.status]}`
        }, {
            label: "成交状态",
            value: res.data.tradingstatus,
            style: `color:${this.data.sColors[res.data.tradingstatus]}`
        }];

        /* 基本信息 */
        let list1 = [{
            label: "医院编号",
            value: res.data.billno
        }, {
            label: "医院名称",
            value: res.data.enterprisename
        }, {
            label: "医院类型",
            value: res.data.type
        }, {
            label: "开发阶段",
            value: res.data.stagename
        }, {
            label: "医院等级",
            value: res.data.grade
        }, {
            label: "预估手术总量",
            value: res.data.totalop
        }, {
            label: "医院床位",
            value: res.data.bed
        }, {
            label: "手术间",
            value: res.data.room
        }, {
            label: "主机数量",
            value: res.data.host
        }, {
            label: "负责人",
            value: res.data.leader[0] ? res.data.leader[0].name : ""
        }, {
            label: "营销区域",
            value: res.data.areaname
        }, {
            label: "所属部门",
            value: res.data.depname
        }, {
            label: "开发状态",
            value: getApp().globalData.Language.getMapText(res.data.status),
            style: `color:${this.data.sColors[res.data.status]}`
        }, {
            label: "成交状态",
            value: res.data.tradingstatus,
            style: `color:${this.data.sColors[res.data.tradingstatus]}`
        }];
        /* 系统信息 */
        let 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.deletereason
        }, {
            label: "转手次数",
            value: res.data.leader[0] ? res.data.leader[0].leadernum : 0
        }];
        this.setData({
            briefs,
            list1,
            list2
        });
    },
    //详情按钮回调
    tabbarOnClick({
        detail
    }) {
        let data = this.data.detail,
            that = this;
        switch (detail.label) {
            case "编辑":
                wx.navigateTo({
                    url: `/prsx/hospital/insert?data=${JSON.stringify(data)}`,
                })
                break;
            case "作废":
                that.setData({
                    deletereasonShow: true
                })
                break;
            case "更换负责人":
                wx.navigateTo({
                    url: `/pages/group/select?data=${JSON.stringify({
                         ownertable:"sa_customers",
                         ownerid:this.data.sa_customersid,
                    })}&radio=true&principal=true`,
                })
                break;
            case "查看重复":
                _Http.basic({
                    "id": 20221208172002,
                    "content": {
                        ...data,
                        pageSize: 999
                    }
                }).then(res => {
                    console.log("查看重复", res)
                    if (res.code != '1') return wx.showToast({
                        title: res.msg,
                        icon: "none"
                    });
                    if (res.data.length == 0) return wx.showToast({
                        title: getApp().globalData.Language.getMapText('未查询到重复数据'),
                        icon: "none"
                    });
                    this.setData({
                        repetitionList: res.data.map(v => {
                            v.chars = v.chars.reduce((acc, item) => ({
                                ...acc,
                                ...item
                            }), {});
                            return v
                        }),
                        repetitionShow: true
                    })
                })
                break;
            case "跟进":
                that.selectComponent("#Trace").toAdd()
                break;
            default:
                console.log(detail)
                break;
        }
    },
    /* 更换负责人 */
    handelSubmit(arr) {
        const that = this;
        wx.showModal({
            title: getApp().globalData.Language.getMapText('提示'),
            content: getApp().globalData.Language.getMapText('是否确认更换负责人'),
            complete: ({
                confirm
            }) => {
                if (confirm) wx.showModal({
                    title: getApp().globalData.Language.getMapText('提示'),
                    content: getApp().globalData.Language.getMapText('是否参与该数据的后续工作'),
                    cancelText: getApp().globalData.Language.getMapText('不参与'),
                    confirmText: getApp().globalData.Language.getMapText('参与'),
                    complete: (s) => {
                        _Http.basic({
                            "id": 20220930103701,
                            "content": {
                                ownertable: "sa_customers",
                                ownerid: that.data.sa_customersid,
                                userid: arr[0],
                                isaddoldleader: s.confirm ? 1 : 0
                            }
                        }).then(res => {
                            console.log("更换负责人", res)
                            if (res.code != '1') return wx.showToast({
                                title: res.data,
                                icon: "none"
                            });
                            wx.showToast({
                                title: getApp().globalData.Language.getMapText('更换成功'),
                                icon: "none",
                                mask: true
                            });
                            getCurrentPages().forEach(v => {
                                if (['packageA/setclient/index'].includes(v.__route__)) v.getList(true)
                            })
                            setTimeout(() => {
                                wx.navigateBack({
                                    delta: 2
                                });
                            }, 300)
                        })
                    }
                })
            }
        })
    },
    /* 底部功能 */
    async setTabbar() {
        let detail = this.data.detail,
            isAdmin = this.data.isAdmin,
            isLeader = detail.leader.some(some => some.userid == wx.getStorageSync('userMsg').userid),
            editdataleader = isLeader ? 1 : 0,
            tabbarList = [],
            appAuth = this.data.appAuth,
            tabsList = this.data.tabsList;
        if (!isLeader) {
            let res = await getApp().agentOrNot("sa_customers", this.data.sa_customersid),
                data = res.code == '1' ? res.data : {
                    editable: 0,
                    editdataleader: 0
                }
            if (appAuth.isdatateam) isLeader = this.selectComponent("#Group").data.editable == 1;
            if (!isLeader) isLeader = data.editable == 1;
            editdataleader = data.editdataleader;
        }
        if (appAuth.isdatafollowup) {
            tabsList.unshift({
                label: "跟进动态",
                icon: "icon-tabgenjinjilu",
                model: "#Trace"
            })
            if (detail.status != '已终止') tabbarList.push({
                icon: "color-genjin",
                label: "跟进"
            });
        }
        tabsList = tabsList.concat([{
            label: "附件",
            icon: "icon-tabfujian1",
            model: "#Files"
        }, {
            label: "操作",
            icon: "icon-tabcaozuojilu1",
            model: "#Record"
        }])
        if (isLeader || isAdmin) {
            tabbarList.push({
                icon: "color-bianji",
                label: "编辑"
            })
            tabbarList.push({
                icon: "icon-shanchu",
                label: "作废"
            })
        }
        if (this.data.appAuth.options.find(v => v == 'viewRepetition')) tabbarList.push({
            icon: "icon-a-shouyejingangquhehuoren",
            label: "查看重复"
        });
        this.setData({
            tabbarList,
            isLeader,
            tabsList
        })
    },
    //tabs 切换
    tabsChange({
        detail
    }) {
        this.setData({
            tabsActive: detail
        });
        this.partialRenewal();
    },
    //局部数据更新 tabs
    partialRenewal(init = false) {
        try {
            let model = this.data.tabsList[this.data.tabsActive].model;
            if (model) {
                let Component = this.selectComponent(model),
                    {
                        total,
                        pageNumber,
                        pageTotal
                    } = Component.data.content,
                    id = model == "#Clue" ? this.data.detail.sa_customersid : this.data.detail.sys_enterpriseid;
                if (model == "#Files") init = true;
                if (total == null || init) {
                    Component.getList(id, init);
                } else if (pageNumber <= pageTotal) {
                    Component.getList(id, false);
                }
            }
        } catch (error) {

        }
    },
    //更新标签
    getTags() {
        this.selectComponent("#Tags").getTags()
    },
    //更新团队成员
    getGroup() {
        this.selectComponent("#Group").getList().then(this.setTabbarList)
    },
    onReachBottom() {
        this.partialRenewal();
    },
    onUnload() {
        _Http.updateList && _Http.updateList()
        const page = getCurrentPages().find(v => v.__route__ == 'packageA/setclient/index');
        if (!page) return;
        let content = JSON.parse(JSON.stringify(page.data.content));
        content.pageSize = (content.pageNumber - 1) * content.pageSize;
        content.pageNumber = 1;
        _Http.basic({
            id: '20221012164402',
            content
        }).then(res => {
            console.log("更新客户列表", res);
            if (res.code == '1') {
                page.setData({
                    list: res.data,
                    "content.total": res.total
                })
                page.getTags()
            }
        })
    },
    onUnload() {
        const page = getCurrentPages().find(v => v.__route__ == 'prsx/hospital/index');
        if (!page) return;
        let content = JSON.parse(JSON.stringify(page.data.content));
        content.pageSize = (content.pageNumber - 1) * content.pageSize;
        content.pageNumber = 1;
        _Http.basic({
            id: '20221012164402',
            content
        }).then(res => {
            console.log("更新列表", res);
            if (res.code == '1') {
                res.data = res.data.map(v => {
                    v.totalstage = v.stages.length
                    v.stage = v.stages.findIndex(s => s.stagename == v.stagename) + 1
                    v.progress = v.stage / v.totalstage * 100;
                    return v
                })
                page.setData({
                    list: res.data,
                    "content.total": res.total
                })
            }
        })
    }
})