const _Http = getApp().globalData.http,
    getTime = require("../../utils/getTime");

Page({
    data: {
        loading: false,
        isReset: true,
        showAll: false,
        form: [{
            label: "任务标题",
            error: false,
            errMsg: "",
            type: "textarea",
            value: "",
            placeholder: "请输入0/40字",
            valueName: "title",
            checking: "base",
            required: true,
            maxlength: '40'
        }, {
            label: "任务内容",
            error: false,
            errMsg: "",
            type: "textarea",
            value: "",
            placeholder: "",
            valueName: "remarks",
            checking: "base",
            required: false,
            slot: "synchronization"
        }, {
            label: "执行人",
            error: false,
            errMsg: "",
            type: "route",
            url: "/packageA/select/contacts/select",
            value: "",
            params: {
                "id": "20221018122201",
                "content": {
                    "ownertable": "sys_task",
                    "ownerid": 0,
                    "where": {
                        "condition": "",
                        "withoutselect": 1
                    }
                }
            },
            query: "&radio=true&idname=userid",
            interrupt: true,
            placeholder: "选择任务执行人",
            valueName: "principal",
            checking: "base",
            required: true
        }, {
            label: "协助人",
            error: false,
            errMsg: "",
            type: "route",
            url: "/packageA/select/contacts/select",
            value: "",
            params: {
                "id": "20221018122201",
                "content": {
                    "ownertable": "sys_task",
                    "ownerid": 0,
                    "where": {
                        "condition": "",
                        "withoutselect": 1
                    }
                }
            },
            query: "&idname=userid",
            interrupt: true,
            placeholder: "选择任务协助人",
            valueName: "member",
            checking: "base",
            required: false
        }, {
            label: "开始日期",
            error: false,
            errMsg: "",
            type: "date",
            start: getTime.formatTime(new Date(), '-').split(' ')[0],
            value: "",
            placeholder: "开始日期",
            interrupt: true,
            valueName: "starttime",
            checking: "base",
            required: true
        }],
        synchronization: null, //同步任务内容参数
        disabled: true,
        uoloadDisabled: false,
        accessory: true
    },
    onLoad(options) {
        getApp().globalData.Language.getLanguagePackage(this, '新建任务')
        let content = {
            "sys_taskid": 0,
            "ownertable": "sys_task",
            "ownerid": options.ownerid || 0,
        };
        // 详情中进入
        if (options.data) {
            getApp().globalData.Language.getLanguagePackage(this, '编辑任务')
            let data = JSON.parse(options.data);
            if (options.group) {
                let group = JSON.parse(options.group)
                let leader = group.findIndex(v => v.userid == data.leader[0].userid);
                if (leader != -1) {
                    data.principal = [group[leader].name, [group[leader].userid]]
                    group.splice(leader, 1)
                    data.member = [group.map(s => s.name), group.map(s => s.userid - 0)]
                }
            }
            data.starttime = data.starttime.split(" ")[0]
            data.endtime = data.endtime ? data.endtime.split(" ")[0] : ""
            let form = this.data.form.concat([{
                label: "结束日期",
                error: false,
                errMsg: "",
                type: "date",
                start: data.value,
                value: "",
                interrupt: true,
                placeholder: "结束日期",
                valueName: "endtime",
                checking: "base",
                required: false
            }, {
                label: "提醒时间",
                error: false,
                errMsg: "",
                type: "namber",
                value: "",
                placeholder: "结束时间前几天提醒",
                valueName: "remindday",
                checking: "base",
                required: false
            }]);
            content = {
                "sys_taskid": data.sys_taskid,
                "ownertable": data.ownertable || "sys_task",
                "ownerid": data.ownerid || 0,
            }
            this.setData({
                content,
                isReset: false,
                accessory: false,
                disabled: false,
                form: form.map(v => {
                    if (data[v.valueName]) v.value = data[v.valueName];
                    return v
                })
            })
        } else if (options.ownertable) {
            content = {
                "ownertable": options.ownertable || "sys_task",
                "ownerid": options.ownerid || 0
            }
            this.setData({
                synchronization: content
            })
        } else {
            //可修改情况
            if (["sys_task", "sat_orderclue", "sa_customers", "sa_project"].includes(content.ownertable)) {
                let form = this.data.form,
                    synchronization = content.ownertable != 'sys_task' ? {
                        "ownertable": content.ownertable,
                        "ownerid": content.ownerid,
                    } : null;
                form.splice(1, 0, {
                    label: "关联应用",
                    error: false,
                    errMsg: "",
                    hint: "",
                    type: "radio",
                    value: content.ownertable,
                    radioList: [{
                        id: 'sa_customers',
                        name: '医院管理'
                    }, {
                        id: 'sa_project',
                        name: '项目商机'
                    }, {
                        id: 'sat_orderclue',
                        name: '销售线索'
                    }, {
                        id: 'sys_task',
                        name: '不关联'
                    }],
                    valueName: "ownertable", //绑定的字段名称
                    required: false, //必填
                    interrupt: true,
                    disabled: content.ownerid != 0
                });
                if (wx.getStorageSync('siteP').siteid == 'HY') {
                    form[1].radioList.pop()
                    if (content.ownertable == 'sys_task') {
                        form[1].value = 'sa_customers'
                        this.setSelectAppRoute(form, 'sa_customers')
                    }
                }
                if (content.ownertable != 'sys_task') this.setSelectAppRoute(form, content.ownertable, content.ownerid != 0)
                this.setData({
                    form
                })
            }
        }
        this.setData({
            content
        })
    },
    /* 打断处理form */
    interrupt(e) {
        let {
            data,
            form,
            temporary
        } = e.detail;
        console.log(data, form, temporary)
        let obj = null,
            index = null;
        switch (temporary.item.label) {
            case '开始日期':
                obj = {
                    label: "结束日期",
                    error: false,
                    errMsg: "",
                    type: "date",
                    start: data.value,
                    value: "",
                    interrupt: true,
                    placeholder: "结束日期",
                    valueName: "endtime",
                    checking: "base",
                    required: false
                };
                let index = form.findIndex(v => v.label == '结束日期');
                index == -1 ? form.push(obj) : form[index] = obj;
                this.setData({
                    isReset: false
                })
                break;
            case '结束日期':
                index = form.findIndex(v => v.label == '提醒时间');
                if (index == -1) form.push({
                    label: "提醒时间",
                    error: false,
                    errMsg: "",
                    type: "namber",
                    value: "",
                    placeholder: "结束时间前几天提醒",
                    valueName: "remindday",
                    checking: "base",
                    required: false
                });
                break;
            case '执行人':
                index = form.findIndex(v => v.label == '协助人');
                form[index].params.excludeid = data.value[1][0];
                if (index != -1 && form[index].value[1]) {
                    let i = form[index].value[1].findIndex(v => v == data.value[1][0]);
                    if (i != -1) {
                        form[index].value[0].splice(i, 1);
                        form[index].value[1].splice(i, 1);
                        if (form[index].value[0].length == 0) form[index].value = '';
                    }
                }
                temporary.item.value = data.value;
                form[temporary.index] = temporary.item;
                wx.navigateBack()
                break;
            case '协助人':
                index = form.findIndex(v => v.label == '执行人');
                if (index != -1 && form[index].value[1]) {
                    if (data.value[1].findIndex(v => v == form[index].value[1][0]) != -1) form[index].value = ''
                }
                temporary.item.value = data.value;
                form[temporary.index] = temporary.item;
                wx.navigateBack()
                break;
            case '关联应用':
                this.setSelectAppRoute(form, data.value)
                this.setData({
                    synchronization: null
                })
                break;
            case '关联数据':
                form[temporary.index].value = data.value;
                wx.navigateBack()
                this.setData({
                    synchronization: {
                        "ownertable": form[temporary.index - 1].value,
                        "ownerid": data.id[0]
                    }
                })
                break;
        };
        this.setData({
            form
        })
        this.selectComponent("#Form").confirm();
    },
    startSynchronization() {
        console.log("开始同步", this.data.synchronization)
        wx.navigateTo({
            url: '/packageA/work/synchronization?data=' + JSON.stringify(this.data.synchronization),
        });
        _Http.selectSync = (item, ownertable) => {
            let form = this.selectComponent("#Form").data.form,
                index = form.findIndex(v => v.label == '任务内容');
            if (index != -1) {
                if (ownertable == 'sat_orderclue') {
                    form[index].value = `${getApp().globalData.Language.getMapText('跟进类型')}：${item.followupmode}\n${getApp().globalData.Language.getMapText('跟进内容')}：${item.content}`;
                } else {
                    form[index].value = `${getApp().globalData.Language.getMapText('跟进类型')}：${item.type}\n${getApp().globalData.Language.getMapText('跟进对象')}：${item.contacts ? item.contacts.join(","):""}\n${item.content}`;
                }
            }
            this.setData({
                form
            })
            wx.navigateBack()
        }
    },
    setSelectAppRoute(form, ownertable, disabled = false) {
        let owneridIndex = form.findIndex(v => v.valueName == 'ownerid');
        if (ownertable == "sys_task") {
            if (owneridIndex != -1) form.splice(owneridIndex, 1);
        } else {
            let data = {
                label: "关联数据",
                error: false,
                errMsg: "",
                type: "route",
                url: "",
                value: "",
                query: "&radio=true",
                interrupt: true,
                valueName: "ownerid",
                checking: "base",
                required: true,
                disabled
            };
            switch (ownertable) {
                case "sa_project":
                    data.params = {
                        "id": 20221020143502,
                        "content": {
                            "nochace": true,
                            "pageNumber": 1,
                            "pageSize": 20,
                            "where": {
                                "condition": ""
                            },
                            "type": 0,
                            "deleted": 0
                        }
                    }
                    data.placeholder = "选择项目商机";
                    data.url = "/packageA/select/project/select";
                    break;
                case "sa_customers":
                    data.params = {
                        "content": {
                            isExport: 0,
                            "pageNumber": 1,
                            "pageSize": 20,
                            "where": {
                                "condition": ""
                            },
                            "type": 0,
                            "deleted": 0,
                            "isend": 0
                        },
                        "id": 20221012164402,
                    }
                    data.placeholder = "选择医院管理";
                    data.url = "/packageA/select/setclient/select";
                    break;
                case "sat_orderclue":
                    data.params = {
                        "content": {
                            "pageNumber": 1,
                            "pageSize": 20,
                            "where": {
                                "condition": ""
                            },
                            "type": 0
                        },
                        "id": 20221101094502,
                    }
                    data.placeholder = "选择销售线索";
                    data.url = "/packageA/select/clue/select";
                    break;
            };
            form.splice(2, owneridIndex == -1 ? 0 : 1, data);
        }
        this.setData({
            form
        })
    },
    submit() {
        this.setData({
            loading: true
        })
        let content = {
            ...this.data.content,
            ...this.selectComponent("#Form").submit()
        };
        content.leaderuserid = content.principal[1][0];
        delete(content.principal)
        content.team = {
            "userids": content.member.length ? content.member[1] : [],
            "justuserids": 1
        }
        delete(content.member)
        if (content.ownerid && typeof (content.ownerid) == 'object') content.ownerid = content.ownerid.length == 2 ? content.ownerid[1][0] : "";
        if (!content.ownerid) content.ownertable = "";
        _Http.basic({
            "id": 20221211112101,
            content
        }).then(res => {
            console.log("创建任务成功", res)
            wx.showToast({
                title: res.code == '1' ? this.data.language['成功的'] || '保存成功' : res.msg,
                icon: "none"
            });
            if (res.code == '1') try {
                let attachmentids = this.selectComponent("#Yl_files").getFiles().attachmentids;
                if (attachmentids.length) {
                    this.handleFileLink(attachmentids, 'sys_task', res.data.sys_taskid, res.data)
                } else {
                    setTimeout(() => {
                        this.changeItem(res.data)
                    }, 500)
                }
            } catch (error) {
                setTimeout(() => {
                    this.changeItem(res.data)
                }, 500)
            }
        })
    },
    changeState({
        detail
    }) {
        this.setData({
            uoloadDisabled: detail
        })
    },
    /* 绑定媒体 */
    insertImgEdit({
        detail
    }) {
        this.handleFileLink(detail)
    },
    handleFileLink(attachmentids, ownertable = "temporary", ownerid = 1, data) {
        _Http.basic({
            "classname": "system.attachment.Attachment",
            "method": "createFileLink",
            "content": {
                ownertable,
                ownerid,
                usetype: 'default',
                attachmentids
            }
        }).then(res => {
            console.log('跟进记录绑定附件', res)
            if (res.code != '1') return wx.showToast({
                title: res.msg,
                icon: "none"
            })
            if (ownertable == 'temporary') {
                this.selectComponent("#Yl_files").handleFiles(res.data)
                this.setData({
                    uoloadDisabled: false
                })
            } else {
                if (res.data.length) data.attinfos = res.data;
                this.changeItem(data)
            }
        })
    },
    changeItem(data) {
        this.setData({
            loading: false
        })
        getCurrentPages().forEach(v => {
            if (v.__route__ == 'packageA/work/index') {
                let index = v.data.list.findIndex(v => v.sys_taskid == data.sys_taskid);
                if (index == -1) {
                    v.data.list.unshift(data)
                    v.setData({
                        list: v.data.list,
                        "content.total": v.data.content.total + 1
                    })
                } else {
                    v.setData({
                        [`list[${index}]`]: data
                    })
                }
            }
        });
        let pages = getCurrentPages(),
            page = pages[pages.length - 2];
        if (page.__route__ == 'packageA/work/index') {
            wx.redirectTo({
                url: '/packageA/work/detail?id=' + data.sys_taskid,
                fail(err) {
                    console.log(err)
                }
            })
        } else if (page.__route__ == 'packageA/work/detail') {
            wx.navigateBack();
            page.getDetail();
        } else {
            page.getTags && page.getTags();
            let p = page.selectComponent("#Work");
            if (p) p.getList(0, true);
            wx.navigateBack();
        }
    },
    reset() {
        let form = this.data.form;
        let index = form.findIndex(v => v.label == '开始日期');
        form[index].value = "";
        form.splice(index + 1, 2);
        this.setData({
            isReset: true,
            disabled: true,
            form
        });
        wx.showToast({
            title: this.data.language['重置成功'] || '重置成功',
            icon: "none"
        })
    },
    // 是否显示全部
    onChange({
        detail
    }) {
        this.setData({
            showAll: detail
        })
    },
    /* 表单必填项是否完成 */
    onConfirm({
        detail
    }) {
        this.setData({
            disabled: detail
        })
    }
})