const _Http = getApp().globalData.http,
    currency = require("../../utils/currency"),
    CNY = value => currency(value, {
        symbol: "￥",
        precision: 2
    }).format();

let paramvalue = false;
Page({
    data: {
        isInsert: false,
        loading: true,
        isLeader: false, //是否为负责人
        isRecover: false, //关闭弹窗是否恢复项目
        tabsActive: 0, //tabs 选中项
        sa_projectid: "",
        tabbarList: [],
        sColors: getApp().globalData.sColors,
    },
    onLoad(options) {
        const appAuth = wx.getStorageSync('auth').wproject;
        let tabsList = [{
            label: "报价单",
            icon: "icon-tabbaojiadan",
            model: "#Offers"
        }, {
            label: "合同",
            icon: "icon-tabhetong",
            model: "#Contract"
        }, {
            label: "详细信息",
            icon: "icon-tabxiangxixinxi1"
        }, {
            label: "关联客户",
            icon: "icon-tabkehu",
            model: "#Treaty"
        }, {
            label: "联系人",
            icon: "icon-tablianxiren",
            model: "#Contacts"
        }]
        if (appAuth.isdatafollowup) tabsList.unshift({
            label: "跟进动态",
            icon: "icon-tabgenjinjilu",
            model: "#Trace"
        })
        if (appAuth.options.some(v => v == 'product')) tabsList.push({
            label: "产品配置单",
            icon: "icon-tabchanpin",
            model: "#Product"
        })
        tabsList = tabsList.concat([{
            label: "关联线索",
            icon: "icon-tabxiansuo",
            model: "#Clue"
        }, {
            label: "报备进度",
            icon: "icon-tabfujian1",
            model: "#ReportingProgress"
        }])
        if (appAuth.istask) tabsList.push({
            label: "任务",
            icon: "icon-tabrenwu",
            model: "#Work"
        })
        tabsList = tabsList.concat([{
            label: "竞争对手",
            icon: "icon-tabjingzhengduishou",
            model: "#Opponent"
        }, {
            label: "项目评估",
            icon: "icon-tabxiangmupinggu",
            model: "#Task"
        }, {
            label: "附件",
            icon: "icon-tabfujian1",
            model: "#Files"
        }, {
            label: "操作记录",
            icon: "icon-tabcaozuojilu1",
            model: "#Record"
        }])
        this.setData({
            sa_projectid: options.id,
            isAdmin: appAuth.options.some(v => v == "admin"), //是否具有管理权限
            options: appAuth.options, //权限列表
            tabsList,
            appAuth
        })
        this.getDetail(true);
        getApp().globalData.Language.getLanguagePackage(this, '项目详情');
    },
    getDetail(init = false) {
        _Http.basic({
            "id": 20221021103902,
            "content": {
                nocache: true,
                "sa_projectid": this.data.sa_projectid
            },
        }).then(res => {
            console.log("项目商机详情", res)
            if (res.code != '1') return wx.showToast({
                title: res.data,
                icon: "none"
            });
            this.setPreview(res.data);
            this.setData({
                loading: false,
                detail: res.data,
            })
            if (init) {
                if (this.data.appAuth.isdatatag) this.getTags();
                if (this.data.appAuth.isdatateam) this.getGroup();
                this.selectComponent("#TaskTabs").getList();
            }
            this.setTabbarList();
            this.partialRenewal(init);
        })
    },
    /* 设置显示信息 */
    async setPreview(data) {
        let list1 = [{
            label: "项目编号",
            value: data.projectnum
        }, {
            label: "项目名称",
            value: data.projectname
        }, {
            label: "报备进度",
            value: data.reportstatus,
            style: `color:${this.data.sColors[data.reportstatus]}`
        }, {
            label: "项目类型",
            value: data.projecttype
        }, {
            label: "项目阶段",
            value: data.stagename
        }, {
            label: "项目方阶段",
            value: data.squarestage
        }, {
            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: CNY(data.signamount_due)
        }, {
            label: "项目成交金额",
            value: CNY(data.dealamount)
        }, {
            label: "领域",
            value: data.tradefield
        }, {
            label: "品牌",
            value: data.brandname
        }, {
            label: "品牌是否填报方植入",
            value: data.isfillbrangd == 1 ? '是' : (data.isfillbrangd + "").length == 0 ? '' : "否"
        }, {
            label: "项目来源",
            value: data.source
        }, {
            label: "赢率",
            value: data.winrate
        }, {
            label: "负责人",
            value: data.name
        }, {
            label: "项目状态",
            value: getApp().globalData.Language.getMapText(data.status),
            style: `color:${data.status == '跟进中'? '#3874f6':this.data.sColors[data.status]}`
        }, {
            label: "结案/失败原因",
            value: data.status == '已结案' ? data.endreason : data.defeattype + (data.defeatreason ? "," + data.defeatreason : data.defeatreason)
        }];
        if (wx.getStorageSync('userMsg').siteid == 'HY') list1 = list1.filter(v => !["项目预算(万元)", "总投资额(万元)", "造价(万元)"].includes(v.label))
        this.setData({
            briefs: [{
                label: "项目编号",
                value: data.projectnum
            }, {
                label: "报备进度",
                value: data.reportstatus,
                style: `color:${this.data.sColors[data.reportstatus]}`
            }, {
                label: "项目类型",
                value: data.projecttype
            }, {
                label: "项目阶段",
                value: data.stagename
            }, {
                label: "项目等级",
                value: data.grade
            }, {
                label: "状态",
                value: getApp().globalData.Language.getMapText(data.status),
                style: `color:${data.status == '跟进中'? '#3874f6':this.data.sColors[data.status]}`
            }, {
                label: '营销费用',
                value: CNY(data.salesfeesamount || '0')
            }],
            list1,
            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.changecount
            }]
        })
    },
    /* 设置tabbar */
    async setTabbarList() {
        let detail = this.data.detail,
            status = detail.status,
            isLeader = detail.leader.some(some => some.userid == wx.getStorageSync('userMsg').userid),
            isAdmin = this.data.isAdmin,
            editdataleader = isLeader,
            tabbarList = [];

        if (this.data.appAuth.isdatafollowup) tabbarList.push({
            icon: "color-genjin",
            label: "跟进"
        });
        if (wx.getStorageSync('auth').wproject.options.some(v => v == "auditauthorization")) tabbarList.unshift({
            icon: "icon-shenheshouquan",
            label: "审核授权"
        })
        if (!isLeader) {
            let res = await getApp().agentOrNot("sa_project", this.data.sa_projectid),
                data = res.code == '1' ? res.data : {
                    editable: 0,
                    editdataleader: 0
                }
            if (this.data.appAuth.isdatateam) isLeader = this.selectComponent("#Group").data.editable == 1;
            if (!isLeader) isLeader = data.editable == 1;
            editdataleader = data.editdataleader;
        }
        if (isAdmin && detail.reportstatus == '报备中') tabbarList = [{
            icon: "icon-baobeishenhe",
            label: "报备审核"
        }, {
            icon: "icon-genjin",
            label: "报备驳回(退回)"
        }].concat(tabbarList)

        if (isLeader || isAdmin) {
            if (status != '已失败' && status != '已结案') {
                _Http.basic({
                    "classname": "sysmanage.develop.datafunction.datafunction",
                    "method": "execute",
                    "content": {
                        functionname: "bpmswitch"
                    }
                }).then(res => {
                    console.log("查询是否启用BPM流程", res)
                    if (res.code != '0') paramvalue = res.data[0].paramvalue == "true";
                })
                tabbarList.push({
                    icon: "color-bianji",
                    label: "编辑"
                })
                if (detail.reportstatus == '未报备') tabbarList.push({
                    icon: "icon-tijiaobaobei1",
                    label: "提交报备"
                })
                if (editdataleader) tabbarList.push({
                    icon: "color-genghuanfuzeren",
                    label: "更换负责人"
                })
            }
            if (isLeader) {
                if (status == '已成交') tabbarList.push({
                    icon: "icon-dibu-jieshu",
                    label: "结案"
                })
                if (status == '跟进中') tabbarList.push({
                    icon: "icon-dibu-wuxiao",
                    label: "失败"
                })

                if (status == '已失败' || status == '已结案') tabbarList = [{
                    icon: "icon-dibu-chehui",
                    label: "恢复"
                }]
            }
            tabbarList.push({
                icon: "icon-shanchu",
                label: "作废"
            })
        }
        if (this.data.options.find(v => v == 'viewRepetition')) tabbarList.push({
            icon: "icon-a-shouyejingangquhehuoren",
            label: "查看重复"
        });
        this.setData({
            isLeader,
            tabbarList,
            disabled: status != '已失败' && status != '已结案'
        });
    },
    //详情按钮回调
    tabbarOnClick({
        detail
    }) {
        let data = this.data.detail,
            that = this;
        switch (detail.label) {
            case "失败":
                wx.navigateTo({
                    url: '/packageA/project/modules/fail/index?id=' + this.data.sa_projectid
                })
                break;
            case "结案":
                this.selectComponent("#Dialog").onClick(this.data.sa_projectid)
                break;
            case "发起授权":
                wx.navigateTo({
                    url: `./impower/initiate?projectname=${data.projectname}&sa_projectid=${data.sa_projectid}`,
                })
                break;
            case "审核授权":
                wx.navigateTo({
                    url: `./impower/impower?sa_projectid=${data.sa_projectid}`,
                })
                break;
            case "恢复":
                _Http.basic({
                    "id": 20221208184202,
                    "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) {
                        wx.showModal({
                            title: getApp().globalData.Language.getMapText('提示'),
                            content: getApp().globalData.Language.getMapText('是否确认恢复项目'),
                            cancelText: getApp().globalData.Language.getMapText('取消'),
                            confirmText: getApp().globalData.Language.getMapText('确定'),
                            complete: ({
                                confirm
                            }) => {
                                if (confirm) that.onRecover()
                            }
                        })
                    } else {
                        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
                                }), {});
                                v.projectname = v.projectname.split('').map(text => {
                                    let projectname = v.chars.projectname.join("") || ''
                                    return projectname.includes(text) ? {
                                        text,
                                        color: "red"
                                    } : {
                                        text,
                                        color: "#666666"
                                    }
                                })
                                return v
                            }),
                            repetitionShow: true,
                            isRecover: true
                        });
                    }
                })
                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: ({
                        confirm
                    }) => {
                        if (confirm) that.handleReport(1)
                    }
                })
                break;
            case "报备审核":
                if (paramvalue) {
                    wx.showModal({
                        title: getApp().globalData.Language.getMapText('提示'),
                        content: getApp().globalData.Language.getMapText('请前往WEB端操作'),
                        showCancel: false,
                        confirmText: getApp().globalData.Language.getMapText('确定'),
                    })
                } else {
                    wx.showModal({
                        title: getApp().globalData.Language.getMapText('提示'),
                        content: getApp().globalData.Language.getMapText('是否确认报备审核'),
                        cancelText: getApp().globalData.Language.getMapText('取消'),
                        confirmText: getApp().globalData.Language.getMapText('确定'),
                        complete: ({
                            confirm
                        }) => {
                            if (confirm) that.handleReport(2)
                        }
                    })
                }
                break;
            case "报备驳回(退回)":
                if (paramvalue) {
                    wx.showModal({
                        title: getApp().globalData.Language.getMapText('提示'),
                        content: getApp().globalData.Language.getMapText('请前往WEB端操作'),
                        showCancel: false,
                        confirmText: getApp().globalData.Language.getMapText('确定'),
                    })
                } else {
                    wx.showModal({
                        title: getApp().globalData.Language.getMapText('提示'),
                        content: getApp().globalData.Language.getMapText('是否确认报备驳回(退回)项目'),
                        cancelText: getApp().globalData.Language.getMapText('取消'),
                        confirmText: getApp().globalData.Language.getMapText('确定'),
                        complete: ({
                            confirm
                        }) => {
                            if (confirm) that.handleReport(3)
                        }
                    })
                }
                break;
            case "跟进":
                that.selectComponent("#Trace").insetr();
                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.code != '1') return wx.showToast({
                        title: res.data,
                        icon: "none"
                    })
                    if (res.data.some(v => v.status == '审核')) {
                        wx.showModal({
                            title: getApp().globalData.Language.getMapText('提示'),
                            content: getApp().globalData.Language.getMapText('当前项目中存在审核状态合同，不可作废') + '!',
                            showCancel: false,
                            confirmText: getApp().globalData.Language.getMapText('确定'),
                        })
                    } 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.code != '1') return wx.showToast({
                        title: res.msg,
                        icon: "none"
                    });
                    if (res.data.length == 0) {
                        getApp().globalData.Language.showToast('未查询到重复数据')
                        this.getTags()
                    } else {
                        this.setTags();
                        this.setData({
                            repetitionList: res.data.map(v => {
                                v.chars = v.chars.reduce((acc, item) => ({
                                    ...acc,
                                    ...item
                                }), {});
                                return v
                            }),
                            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.code == '1' ? getApp().globalData.Language.getMapText('已恢复') : res.msg,
                icon: "none",
                mask: true
            });
            if (res.code == '1') setTimeout(this.getDetail, 300);
        })
    },
    /* 关闭查重弹窗 */
    repClose() {
        let that = this;
        if (this.data.isRecover) wx.showModal({
            title: getApp().globalData.Language.getMapText('提示'),
            content: getApp().globalData.Language.getMapText('存在重复项目，是否确认恢复'),
            cancelText: getApp().globalData.Language.getMapText('取消'),
            confirmText: getApp().globalData.Language.getMapText('确定'),
            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.code == '1') 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)
            if (res.code != '1') {
                wx.showModal({
                    title: getApp().globalData.Language.getMapText('提示'),
                    content: res.msg,
                    showCancel: false,
                    confirmText: getApp().globalData.Language.getMapText('确定'),
                })
            } else {
                wx.showToast({
                    title: getApp().globalData.Language.getMapText('操作成功'),
                    icon: "none",
                    mask: true
                })
                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 (model == "#Files") init = true;
            if (total == null || init) {
                Component.getList(id, init);
            } else if (pageNumber <= pageTotal) {
                Component.getList(id, false);
            }
        }
    },
    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: getApp().globalData.Language.getMapText('提示'),
            content: getApp().globalData.Language.getMapText('是否确认更换负责人'),
            cancelText: getApp().globalData.Language.getMapText('取消'),
            confirmText: 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_project",
                                ownerid: that.data.detail.sa_projectid,
                                userid: arr[0],
                                isaddoldleader: s.confirm ? 1 : 0
                            }
                        }).then(res => {
                            console.log("更换负责人", res)
                            wx.showToast({
                                title: res.code != '1' ? res.msg : getApp().globalData.Language.getMapText('更换成功'),
                                icon: "none",
                                mask: true
                            });
                            if (res.code == '1') setTimeout(() => {
                                wx.navigateBack({
                                    delta: 2
                                });
                            }, 300)
                        })
                    }
                })
            }
        })
    },
    //更新标签
    getTags() {
        this.selectComponent("#Tags").getTags();
    },
    //更新团队成员
    getGroup() {
        this.selectComponent("#Group").getList().then(this.setTabbarList)
    },
    /* tag更新列表 */
    onGetList({
        detail
    }) {
        let tabbarList = this.data.tabbarList;
        if (detail.data.systemtag.includes('已报备')) {
            let status = this.data.detail.status
            if (this.data.isLeader && status != '已失败' && status != '已结案') tabbarList.unshift({
                icon: "icon-faqishouquan",
                label: "发起授权"
            })
            this.setData({
                isInsert: true,
                tabbarList
            })
        }
    },
    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.code == '1') {
                page.data.list = res.data.map(v => {
                    v.progress = v.stage / v.totalstage * 100;
                    return v
                });
                page.data.content.total = res.total;
                page.getTags();
            }
        })
    }
})