import {CommonUtil} from "./common.util";

export class UFormUtil {

    /**
     * 初始化表单对象
     * @param validateForm
     */
    static init(validateForm) {
        // console.log("-------------------------------init-------------------------------", validateForm);
        // 给表单对象添加controls属性
        const _self = this;
        let controls = {};
        let i = 0;
        for (let attrName in validateForm.value) {
            controls[attrName] = {
                id: CommonUtil.generateUUID(),
                rawValue: validateForm.value[attrName],  // 原始值，可以用重置表单
                value: validateForm.value,  // 引用value对线，可以在control中直接操作value对象
                timestamp: new Date().getTime() + i++,
                valueName: attrName,
                options: [],
                isShow: false,
                textDesc: '',
                defaultIndex: -1,
            }
        }

        // 添加重置表单方法
        validateForm.resetValues = function () {
            for (let attrName in validateForm.value) {
                validateForm.value[attrName] = validateForm.controls[attrName].rawValue;
                if (validateForm.controls[attrName].options) {
                    _self.selectOptions(validateForm.controls[attrName], validateForm.controls[attrName].selectColNums, validateForm.controls[attrName].selectValues);
                }
            }
            console.log("resetValues------------------------", validateForm);
        };

        // 添加搜索事件
        validateForm.doSearch = function (_selfVue, dataList, uDropdownRef = 'uDropdown') {
            console.log(_selfVue)
            console.log(_selfVue.$refs)
            if (_selfVue.$refs[uDropdownRef]) {
                _selfVue.$refs[uDropdownRef].close();
            }
            _selfVue.doRefresh(dataList);
            console.log("doSearch------------------------", validateForm);
        };

        validateForm.controls = controls;
        return validateForm;
    }

    /**
     * 给表单字段设置默认值
     * @param validateForm
     * @param data
     */
    static setDefaultValues(validateForm, data) {
        console.log("-------------------------------setDefaultValues-------------------------------", validateForm, data);
        if (data === null || data === undefined) {
            return;
        }
        for (let controlName in validateForm.value) {
            for (let dataName in data) {
                if (controlName == dataName) {
                    if (typeof  data[dataName] === 'boolean') {
                        validateForm.value[controlName] = data[dataName];
                        validateForm.controls[controlName].rawValue = data[dataName];
                    } else {
                        validateForm.value[controlName] = data[dataName] + "";  // todo 值必须转成字符串类型，表单校验规则数字和字符串类型不兼容。
                        validateForm.controls[controlName].rawValue = data[dataName] + "";  // 原始值，可以用重置表单 todo 值必须转成字符串类型，表单校验规则数字和字符串类型不兼容。
                    }
                }
            }
        }
    }

    /**
     * 选择地区回调事件
     */
    static regionConfirm(e, control, provinceName = 'provinceName', cityName = 'cityName', areaName = 'areaName') {
        console.log(e);
        let value = control.value;
        value[control.valueName] = e.province.label + '-' + e.city.label + '-' + e.area.label;
        value[provinceName] = e.province.label;
        value[cityName] = e.city.label;
        value[areaName] = e.area.label;
        control.isShow = false;
    }

    /**
     * 选择时间回调事件
     */
    static timeConfirm(e, control) {
        console.log(e);
        let value = control.value;
        let yyyyMMdd = [];
        if (e.year) {
            yyyyMMdd.push(e.year);
        }
        if (e.month) {
            yyyyMMdd.push(e.month);
        }
        if (e.day) {
            yyyyMMdd.push(e.day);
        }
        let hhmmss = [];
        if (e.hour) {
            hhmmss.push(e.hour);
        }
        if (e.minute) {
            hhmmss.push(e.minute);
        }
        if (e.second) {
            hhmmss.push(e.second);
        }
        value[control.valueName] = `${yyyyMMdd.join("-")} ${hhmmss.join(":")}`.trim();
        control.isShow = false;
    }

    /**
     * @param control
     * @param options
     * @param colNums 列数
     * @param values 默认值
     */
    static setOptions(control, options, colNums = 1, values) {
        console.log("-------------------------------setOptions-------------------------------", control, options, colNums, values);
        if (colNums === 1) {  // 删除第一列的子节点
            options.forEach((item1, index) => {
                delete item1.children;
            });
        } else if (colNums === 2) {  // 删除第二列的子节点
            options.forEach((item1, index1) => {
                item1.children.forEach((item2, index2) => {
                    delete item2.children;
                });
            });
        } else if (colNums === 3) {  // 删除第三列的子节点
            options.forEach((item1, index1) => {
                item1.children.forEach((item2, index2) => {
                    item2.children.forEach((item3, index3) => {
                        delete item3.children;
                    });
                });
            });
        }
        control.options = options;
        control.selectColNums = colNums;
        control.selectValues = values;
        this.selectOptions(control, colNums, values);
    }

    /**
     * 选中某个控件值
     *
     * 模式选择，"single-column"-单列模式，"mutil-column"-多列模式，"mutil-column-auto"-多列联动模式
     * 三列数据格式
     * [
     *    {
     *       value: 1,
     *       label: '中国',
     *       children: [
     *           {
     *               value: 2,
     *               label: '广东',
     *               children: [
     *                   {
     *                       value: 3,
     *                       label: '深圳'
     *                   },
     *                   {
     *                       value: 4,
     *                       label: '广州'
     *                   }
     *               ]
     *           }
     *       ]
     *     }
     * ]
     */
    static selectOptions(control, colNums, values) {
        let defaultValue = control.value[control.valueName];
        if (values) {
            defaultValue = values;
        }

        // todo 如果值是boolean类型，则换成1或0
        if (defaultValue === false || defaultValue === 'false') {
            defaultValue = "0";
        } else if (defaultValue === true || defaultValue === 'true') {
            defaultValue = "1";
        }

        // 单列模式
        if (colNums === 1) {
            control.options.forEach((item, index) => {
                if (item.label !== undefined && item.value !== undefined) {
                    if (item.value + "" === defaultValue + "") {
                        control.textDesc = item.label;
                        control.defaultIndex = index;
                        control.defaultValue = [index];
                    }
                } else if (item.code !== undefined && item.name !== undefined) {
                    if (item.code + "" === defaultValue + "") {
                        control.textDesc = item.name;
                        control.defaultIndex = index;
                        control.defaultValue = [index];
                    }
                }
            });
        } else if (colNums === 2) {
            // 一般默认值是第二列的值
            control.options.forEach((item1, index1) => {
                item1.children.forEach((item2, index2) => {
                    if (item2.label !== undefined && item2.value !== undefined) {
                        if (item2.value + "" === defaultValue + "") {
                            let labels = [];
                            if (item1.label) {
                                labels.push(item1.label);
                            }
                            if (item2.label) {
                                labels.push(item2.label);
                            }
                            control.textDesc = labels.join("-");
                            control.defaultIndex = index2;
                            control.defaultValue = [index1, index2];
                        }
                    } else if (item2.code !== undefined && item2.name !== undefined) {
                        if (item2.code + "" === defaultValue + "") {
                            let names = [];
                            if (item1.name) {
                                names.push(item1.name);
                            }
                            if (item2.name) {
                                names.push(item2.name);
                            }
                            control.textDesc = names.join("-");
                            control.defaultIndex = index2;
                            control.defaultValue = [index1, index2];
                        }
                    }
                });
            });
        } else if (colNums === 3) {
            // 一般默认值是第三列的值
            control.options.forEach((item1, index1) => {
                item1.children.forEach((item2, index2) => {
                    item2.children.forEach((item3, index3) => {
                        if (item3.label !== undefined && item3.value !== undefined) {
                            if (item3.value + "" === defaultValue + "") {
                                let labels = [];
                                if (item1.label) {
                                    labels.push(item1.label);
                                }
                                if (item2.label) {
                                    labels.push(item2.label);
                                }
                                if (item3.label) {
                                    labels.push(item3.label);
                                }
                                control.textDesc = labels.join("-");
                                control.defaultIndex = index3;
                                control.defaultValue = [index1, index2, index3];
                            }
                        } else if (item3.code !== undefined && item3.name !== undefined) {
                            if (item3.code + "" === defaultValue + "") {
                                let names = [];
                                if (item1.name) {
                                    names.push(item1.name);
                                }
                                if (item2.name) {
                                    names.push(item2.name);
                                }
                                if (item3.name) {
                                    names.push(item3.name);
                                }
                                control.textDesc = names.join("-");
                                control.defaultIndex = index3;
                                control.defaultValue = [index1, index2, index3];
                            }
                        }
                    });
                });
            });
        }
    }

    /**
     * 单列下拉选择选中事件
     */
    static selectSingleColumnConfirm($event, control) {
        console.log($event, control);
        control.value[control.valueName] = $event[0].value;
        control.textDesc = $event[0].label;
        this.selectOptions(control, $event.length);
        control.isShow = false;
    }

    /**
     * 多列联动下拉选择选中事件
     */
    static selectMutilColumnConfirm($event, control) {
        console.log($event, control);  // $event = [{label: '', value: ''}, {label: '', value: ''}, ...]
        control.value[control.valueName] = $event[$event.length - 1].value;  // 多列联动，取最后一列的值
        let labels = [];
        $event.forEach(item => {
            if (item.label) {
                labels.push(item.label);
            }
        });
        control.textDesc = labels.join("-");

        // 解决弹框不会选中问题。
        this.selectOptions(control, $event.length);
        control.isShow = false;
    }

    /**
     * 获取表单中某个字段
     * @param formRef this.$refs.uForm
     * @param prop 'code'
     * @returns {*}
     */
    static getFormItem(formRef, prop) {
        if (!formRef) {
            return undefined;
        }

        const list = formRef.fields.filter(item => item.prop === prop);
        if (list.length) {
            return list[0];
        }

        return undefined;
    }

    /**
     * 校验单个字段，触发单个字段的校验规则
     * @param formRef this.$refs.uForm
     * @param prop 'code'
     *
     * UFormUtil.validation(_self.$refs.validateFormRef, 'sysFileId');
     */
    static validation(formRef, prop) {
        const _self = this;
        return new Promise(function (resolve, reject) {
            const item = _self.getFormItem(formRef, prop);
            item.validation('', error => {
                if (error) {
                    CommonUtil.toast(error);
                    resolve(false);
                } else {
                    resolve(true);
                }
            });
        });
    }
}
