const _Http = getApp().globalData.http,
    currency = require("../../utils/currency"),
    CNY = value => currency(value, {
        symbol: "￥",
        precision: 2
    }).format();
Page({
    data: {
        loading: true,
        isLeader: false, //是否为负责人
        isRecover: false, //关闭弹窗是否恢复项目
        tabsActive: 0, //tabs 选中项
        sa_projectid: "",
        tabsList: [{
            label: "详细信息",
            icon: "icon-tabxiangxixinxi1"
        }, {
            label: "关联客户",
            icon: "icon-tabkehu",
            model: "#Treaty"
        }, {
            label: "联系人",
            icon: "icon-tablianxiren",
            model: "#Contacts"
        }, {
            label: "产品配置单",
            icon: "icon-tabchanpin",
            model: "#Product"
        }, {
            label: "报价单",
            icon: "icon-tabbaojiadan",
            model: "#Offers"
        }, {
            label: "竞争对手",
            icon: "icon-tabjingzhengduishou",
            model: "#Opponent"
        }, {
            label: "合同",
            icon: "icon-tabhetong",
            model: "#Contract"
        }, {
            label: "关联线索",
            icon: "icon-tabxiansuo",
            model: "#Clue"
        }, {
            label: "项目评估",
            icon: "icon-tabxiangmupinggu",
            model: "#Task"
        }, {
            label: "任务",
            icon: "icon-tabrenwu",
            model: "#Work"
        }, {
            label: "报备进度",
            icon: "icon-tabfujian1",
            model: "#ReportingProgress"
        }, {
            label: "附件",
            icon: "icon-tabfujian1",
            model: "#Files"
        }, {
            label: "操作记录",
            icon: "icon-tabcaozuojilu1",
            model: "#Record"
        }, {
            label: "跟进动态",
            icon: "icon-tabgenjinjilu",
            model: "#Trace"
        }],
        tabbarList: [],
    },
    onLoad(options) {
        this.setData({
            sa_projectid: options.id,
            isAdmin: wx.getStorageSync('auth').wproject.options.some(v => v == "admin"), //是否具有管理权限
            options: wx.getStorageSync('auth').wproject.options, //权限列表
        });
        this.getDetail(true)
    },
    getDetail(init = false) {
        _Http.basic({
            "id": 20221021103902,
            "content": {
                nocache: true,
                "sa_projectid": this.data.sa_projectid
            },
        }).then(res => {
            console.log("项目商机详情", res)
            if (res.msg != '成功') return wx.showToast({
                title: res.data,
                icon: "none"
            });
            this.setPreview(res.data);
            this.setTabbar(res.data.status, res.data.leader.some(some => some.userid == wx.getStorageSync('userMsg').userid));
            this.setData({
                loading: false,
                detail: res.data,
            })
            if (init) {
                this.getTags();
                this.getGroup();
                this.selectComponent("#TaskTabs").getList();
            }
            this.partialRenewal(init);
        })
    },
    /* 设置显示信息 */
    async setPreview(data) {
        data.signamount_due = CNY(data.signamount_due);
        this.setData({
            briefs: [{
                label: "项目编号",
                value: data.projectnum
            }, {
                label: "项目等级",
                value: data.grade
            }, {
                label: "项目类型",
                value: data.projecttype
            }, {
                label: "项目阶段",
                value: data.stagename
            }, {
                label: "赢率",
                value: data.winrate ? data.winrate + "%" : data.winrate
            }],
            list1: [{
                    label: "项目编号",
                    value: data.projectnum
                }, {
                    label: "项目名称",
                    value: data.projectname
                }, {
                    label: "项目类型",
                    value: data.projecttype
                }, {
                    label: "项目阶段",
                    value: data.stagename
                }, {
                    label: "项目等级",
                    value: data.grade
                }, {
                    label: "省市县",
                    value: data.province ? data.province + data.city + data.county : ''
                }, {
                    label: "地址",
                    value: data.address
                }, {
                    label: "项目规模",
                    value: data.scale ? data.scale + data.unitname : ""
                }, {
                    label: "项目预算(万元)",
                    value: CNY(data.budgetary)
                },
                {
                    label: "总投资额(万元)",
                    value: CNY(data.totalinvestment)
                },
                {
                    label: "造价(万元)",
                    value: CNY(data.costofconstruction)
                },
                {
                    label: "预计开工时间",
                    value: data.begdate_due
                },
                {
                    label: "预计完工时间",
                    value: data.enddate_due
                }, {
                    label: "预计签约时间",
                    value: data.signdate_due
                }, {
                    label: "预计签约金额(元)",
                    value: data.signamount_due
                }, {
                    label: "领域",
                    value: data.tradefields
                }, {
                    label: "品牌",
                    value: data.brandname
                }, {
                    label: "赢率",
                    value: data.winrate
                }, {
                    label: "项目状态",
                    value: data.status
                }, {
                    label: "负责人",
                    value: data.name
                }
            ],
            list2: [{
                label: "创建人",
                value: data.createby
            }, {
                label: "创建时间",
                value: data.createdate
            }, {
                label: "最近编辑人",
                value: data.changeby
            }, {
                label: "最近编辑时间",
                value: data.changedate
            }, {
                label: "提交报备人",
                value: data.reportby
            }, {
                label: "提交报备时间",
                value: data.reportdate
            }, {
                label: "报备审核人",
                value: data.reportcheckby
            }, {
                label: "报备审核时间",
                value: data.reportcheckdate
            }, {
                label: "作废原因",
                value: data.deletereason
            }, {
                label: "转手次数",
                value: data.changecount
            }]
        })
    },
    /* 设置tabbar */
    async setTabbar(status, Leader) {
        let isLeader = Leader,
            isAdmin = this.data.isAdmin,
            editdataleader = true,
            tabbarList = [{
                icon: "icon-genjin",
                label: "跟进"
            }];
        if (!isLeader) {
            let s = await getApp().agentOrNot("sa_project", this.data.sa_projectid);
            isLeader = s.data.editable == 1;
            editdataleader = s.data.editdataleader == 1;
        }
        if (isAdmin) tabbarList = [{
            icon: "icon-genjin",
            label: "报备审核"
        }].concat(tabbarList);

        if (isLeader || isAdmin) {
            if (status != '已失败') tabbarList = tabbarList.concat([{
                icon: "icon-bianji",
                label: "编辑"
            }, {
                icon: "icon-genjin",
                label: "提交报备"
            }])
            if (editdataleader) tabbarList.push({
                icon: "icon-zhuanyi",
                label: "更换负责人"
            })
            tabbarList.push({
                icon: "icon-shanchu",
                label: "作废"
            })
            tabbarList.push(status == '已失败' ? {
                icon: "icon-dibu-chehui",
                label: "恢复"
            } : {
                icon: "icon-dibu-jieshu",
                label: "结束"
            })
        }
        if (this.data.options.find(v => v == 'viewRepetition')) tabbarList.push({
            icon: "icon-a-shouyejingangquhehuoren",
            label: "查看重复"
        });
        this.setData({
            isLeader,
            tabbarList,
            editdataleader
        });
    },
    //详情按钮回调
    tabbarOnClick({
        detail
    }) {
        let data = this.data.detail,
            that = this;
        switch (detail.label) {
            case "结束":
                if (data.status != '跟进中') return wx.showToast({
                    title: '当前状态不可结束',
                    icon: "none"
                });

                wx.showModal({
                    title: '提示',
                    content: '是否确认结束项目',
                    complete: ({
                        confirm
                    }) => {
                        if (confirm) _Http.basic({
                            "id": 20221215163702,
                            "content": {
                                "sa_projectid": data.sa_projectid
                            }
                        }).then(res => {
                            console.log('结束', res)
                            wx.showToast({
                                title: res.msg == '成功' ? '已结束' : res.msg,
                                icon: "none"
                            });
                            if (res.msg == '成功') setTimeout(this.getDetail, 300);
                        })
                    }
                })
                break;
            case "恢复":
                if (data.status != '已失败') return wx.showToast({
                    title: '失败项目才可恢复!',
                    icon: "none"
                });
                _Http.basic({
                    "id": 20221208184202,
                    "content": {
                        ...data,
                        pageSize: 999
                    }
                }).then(res => {
                    console.log("查看重复", res)
                    if (res.msg != '成功') return wx.showToast({
                        title: res.msg,
                        icon: "none"
                    });
                    if (res.data.length == 0) {
                        wx.showModal({
                            title: '提示',
                            content: '是否确认恢复项目',
                            complete: ({
                                confirm
                            }) => {
                                if (confirm) that.onRecover()
                            }
                        })
                    } else {
                        wx.showToast({
                            title: '查询到有疑似重复项目',
                            icon: "none"
                        })
                        this.setData({
                            repetitionList: res.data,
                            repetitionShow: true,
                            isRecover: true
                        });
                    }
                })
                break;
            case "提交报备":
                wx.showModal({
                    title: '提示',
                    content: '是否确认提交项目审核',
                    complete: ({
                        confirm
                    }) => {
                        if (confirm) that.handleReport(1)
                    }
                })
                break;
            case "报备审核":
                if (wx.getStorageSync('userMsg').siteid == 'HY') {
                    wx.showToast({
                        title: '请前往WEB端操作',
                        icon: "none"
                    })
                } else {
                    wx.showModal({
                        title: '提示',
                        content: '是否确认审核项目',
                        complete: ({
                            confirm
                        }) => {
                            if (confirm) that.handleReport(2)
                        }
                    })
                }

                /*  _Http.basic({
                     "id": 20230628155602,
                     "content": {
                         "sa_projectid": that.data.sa_projectid,
                         "type": "mobile"
                     }
                 }).then(res => {
                     console.log("获取报备地址", res)
                     if (res.msg != '成功') return wx.showToast({
                         title: res.msg,
                         icon: "none"
                     });
                     if (res.data === '') return wx.showToast({
                         title: '暂无审核权限',
                         icon: "none"
                     });
                     getApp().globalData.webviewurl = res.data;
                     wx.navigateTo({
                         url: './webview',
                     })
                 }) */
                break;
            case "报备驳回(退回)":
                if (wx.getStorageSync('userMsg').siteid == 'HY') {
                    wx.showToast({
                        title: '请前往WEB端操作',
                        icon: "none"
                    })
                } else {
                    wx.showModal({
                        title: '提示',
                        content: '是否确认报备驳回(退回)项目',
                        complete: ({
                            confirm
                        }) => {
                            if (confirm) that.handleReport(3)
                        }
                    })
                }
                break;
            case "跟进":
                wx.navigateTo({
                    url: `/packageA/setclient/modules/trace/add/index?ownertable=sa_project&ownerid=${data.sa_projectid}`,
                })
                break;
            case "编辑":
                let tags = that.selectComponent("#Tags").data.systemtag;
                wx.navigateTo({
                    url: `/packageA/project/addAndEdit?data=${JSON.stringify(data)}&disabled=${tags.includes("报备中")||tags.includes("已报备")}`,
                })
                break;
            case "作废":
                _Http.basic({
                    "id": "20221223102102",
                    "content": {
                        "nocache": true,
                        "sa_projectid": that.data.sa_projectid,
                        pageNumbe: 1,
                        pageSize: 9999,
                        "where": {
                            "conditino": ""
                        }
                    }
                }).then(res => {
                    console.log("查询合同列表", res)
                    if (res.msg != '成功') return wx.showToast({
                        title: res.data,
                        icon: "none"
                    })
                    if (res.data.some(v => v.status == '审核')) {
                        wx.showToast({
                            title: '当前项目中存在审核状态合同，不可作废!',
                            icon: "none",
                            mask: true
                        })
                    } else {
                        wx.navigateTo({
                            url: `/packageA/project/delete?id=${this.data.detail.sa_projectid}`,
                        })
                    }
                })
                break;
            case "更换负责人":
                wx.navigateTo({
                    url: `/pages/group/select?data=${JSON.stringify({
                             ownertable:"sa_project",
                             ownerid:data.sa_projectid,
                        })}&radio=true&principal=true`,
                })
                break;
            case "查看重复":
                _Http.basic({
                    "id": 20221208184202,
                    "content": {
                        ...data,
                        pageSize: 999
                    }
                }).then(res => {
                    console.log("查看重复", res)
                    if (res.msg != '成功') return wx.showToast({
                        title: res.msg,
                        icon: "none"
                    });
                    if (res.data.length == 0) {
                        wx.showToast({
                            title: '未查询到重复数据',
                            icon: "none"
                        });
                        this.getTags()
                    } else {
                        this.setTags();
                    }
                    this.setData({
                        repetitionList: res.data,
                        repetitionShow: true
                    })
                })
                break;
            default:
                console.log(detail)
                break;
        }
    },
    /* 恢复项目 */
    onRecover() {
        _Http.basic({
            "id": 20221215164002,
            "content": {
                "sa_projectid": this.data.sa_projectid
            }
        }).then(res => {
            console.log('恢复', res)
            wx.showToast({
                title: res.msg == '成功' ? '已恢复' : res.msg,
                icon: "none",
                mask: true
            });
            if (res.msg == '成功') setTimeout(this.getDetail, 300);
        })
    },
    /* 关闭查重弹窗 */
    repClose() {
        let that = this;
        if (this.data.isRecover) wx.showModal({
            title: '提示',
            content: '存在重复项目，是否确认恢复',
            complete: ({
                confirm
            }) => {
                if (confirm) {
                    that.onRecover(true)
                    that.setTags();
                }
            }
        });
        this.setData({
            repetitionShow: false,
            isRecover: false
        })
    },
    /* setTags */
    setTags() {
        let {
            datatag,
            systemtag
        } = this.selectComponent("#Tags").returnTags();
        if (!systemtag.some(v => v == '疑似重复')) {
            systemtag.push("疑似重复")
            _Http.basic({
                "id": 20220929090901,
                "content": {
                    "ownertable": "sa_project",
                    "ownerid": this.data.sa_projectid,
                    datatag,
                    systemtag
                }
            }).then(res => {
                console.log("绑定疑似重复标签", res)
                if (res.msg == '成功') this.getTags();
            })
        } else {
            this.getTags();
        }
    },
    /* 1提交报备，2报备审核，3报备驳回(退回) */
    handleReport(type) {
        _Http.basic({
            "id": 20221114163402,
            "content": {
                "sa_projectid": this.data.sa_projectid,
                type
            }
        }).then(res => {
            console.log("报备", type, res)
            wx.showToast({
                title: res.data == '失败' ? res.msg : "操作成功",
                icon: "none",
                mask: true
            })
            if (res.data != '失败') {
                this.getDetail();
                this.getTags();
            }
        })
    },
    //局部数据更新 tabs
    partialRenewal(init = false) {
        let model = this.data.tabsList[this.data.tabsActive].model;
        if (model) {
            let Component = this.selectComponent(model),
                {
                    total,
                    pageNumber,
                    pageTotal
                } = Component.data.content,
                id = this.data.sa_projectid;
            if (total == null || init) {
                Component.getList(id, init);
            } else if (pageNumber <= pageTotal) {
                Component.getList(id, false);
            }
        }
    },
    onShow() {
        console.log()
    },
    onReachBottom() {
        this.partialRenewal();
    },
    /* 项目评估切换 */
    taskTabsChange({
        detail
    }) {
        if (detail.change) {
            this.setData({
                tabsActive: this.data.tabsList.findIndex(v => v.label == '项目评估')
            });
            this.selectComponent("#Task").getList(this.data.sa_projectid, true)
        }
    },
    //tabs 切换
    tabsChange({
        detail
    }) {
        this.setData({
            tabsActive: detail
        });
        this.partialRenewal();
    },
    /* 更换负责人 */
    handelSubmit(arr) {
        const that = this;
        wx.showModal({
            title: '提示',
            content: '是否确认更换负责人',
            complete: ({
                confirm
            }) => {
                if (confirm) _Http.basic({
                    "id": 20220930103701,
                    "content": {
                        ownertable: "sa_project",
                        ownerid: that.data.detail.sa_projectid,
                        userid: arr[0]
                    }
                }).then(res => {
                    wx.showToast({
                        title: res.msg != '成功' ? res.data : '更换成功',
                        icon: "none",
                        mask: true
                    });
                    if (res.msg == '成功') setTimeout(() => {
                        that.getDetail(true);
                        wx.navigateBack();
                    }, 300)
                })
            }
        })
    },
    //更新标签
    getTags() {
        this.selectComponent("#Tags").getTags();
    },
    //更新团队成员
    getGroup() {
        this.selectComponent("#Group").getList();
    },
    /* tag更新列表 */
    onGetList({
        detail
    }) {
        if (detail.data.systemtag.includes('报备中')) {
            let tabbarList = this.data.tabbarList.filter(v => v.label != '提交报备')
            let index = tabbarList.findIndex(v => v.label == '报备审核');
            if (index != -1) tabbarList.splice(index, 0, {
                icon: "icon-genjin",
                label: "报备驳回(退回)"
            })
            this.setData({
                tabbarList
            })
        }
        this.setData({
            isInsert: detail.data.systemtag.includes('已报备')
        })
        console.log(123123, this.data.isInsert)
    },
    onUnload() {
        const page = getCurrentPages().find(v => v.__route__ == 'packageA/project/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: 20221020143502,
            content
        }).then(res => {
            console.log("更新项目商机列表", res);
            if (res.msg == '成功') {
                page.data.list = res.data.map(v => {
                    v.progress = v.stage / v.totalstage * 100;
                    return v
                });
                page.data.content.total = res.total;
                page.setListHeight();
                page.getTags();
            }
        })
    }
})