<script>
import LjImgPro from "components/lj-img-pro";
import LjVideoDownload from "components/lj-video-download";

export default {
    name: 'L1APPRouteFormItem',

    components: {
        LjImgPro,
        LjVideoDownload
    },

    data() {
        return {
            styleList: null,
            filtedList: [],
            // cellPrimary: "content",
            // textAlign: "left",
            // height: '100px',
            dateTimeDisplayFormatMap: {}
        };
    },

    props: {
        /**
         * colums: {
         *  label: 标题
         *  property: 字段,
         *  labelWidth： number | string， 默认：60px，左侧文本宽度，默认单位为px
         *  type： DateTime/Number/Select/Action/AlwaysAction/Boolean/TextField/TextInput/slot, 默认TextField
         *  required: -1不可编辑/0默认/1必填,
         *  inputLine: 文字输入行数
         *  maxlength: number | string 输入的最大字符数
         *  autosize: Boolean/Object 是否自适应内容高度，
         *          只对 textarea 有效，可传入对象,如 { maxHeight: 100, minHeight: 50 }，单位为px
         *  slot: render()
         *  rightIcon: 右侧图标名称或图片链接
         *  icon-prefix: 默认：iconfont
         * 
         *  type: DateTime/Number/Select/Action/AlwaysAction/Boolean/TextField/TextInput,
         *  format: DateTime所用的时间选择及显示格式，默认YYYY-MM-DD，参考格式YYYY-MM-DD HH:mm
         *  selectOptions:lj-select属性,
         *  append: 后缀
         *  buttonText:右侧附加按钮文字
         *  inlineDesc:日期类型-描述
         *  icon :后置图标
         *  maxEnable:最高级判断是否能编辑
         * }
         */
        columns: Array,
        data: {
            // 数据模型
            type: Object,
            default: function () {
                return {};
            }
        },
        editing: Boolean, // 是否可编辑
    },

    mounted() {
        this.refreshDisplayColumnList();
    },

    methods: {
        computeStyleList() {
            let self = this;
            // 计算标签类型、是否必填、是否可编辑
            let list = this.columns;
            for (let item of list) {
                if (item.display === undefined) {
                    item.display = true;
                }
                let cardParams = {};
                if (item.type) {
                    if (item.type === "Boolean") {
                        cardParams.type = 'Checkbox';
                    } else if (item.type === 'Select') {
                        cardParams.type = item.type;
                        if (item.selectOptions) {
                            cardParams.selectOptions = item.selectOptions;
                        } else {
                            console.error("错误，未设置select属性")
                        }
                    } else if (item.type === "DateTime") {
                        cardParams.type = item.type;
                        let vuxFormat = "YYYY-MM-DD";
                        if (item.format) {
                            vuxFormat = item.format;
                        }
                        cardParams.format = vuxFormat;
                        let ljFormat = vuxFormat.toLowerCase().replace("mm", "MM");
                        if (!this.dateTimeDisplayFormatMap[vuxFormat]) {
                            this.dateTimeDisplayFormatMap[vuxFormat] = function (val) {
                                return $lj.dateformat(val, ljFormat);
                            }
                        }
                    } else {
                        cardParams.type = item.type; // Number || AlwaysAction|| Action
                    }
                } else {
                    if (item.inputLine && item.inputLine > 1) {
                        cardParams.type = 'TextArea';
                    } else {
                        cardParams.type = 'TextField';
                    }
                }
                var editable = (item.required !== -1);

                if (cardParams.type === 'AlwaysAction') {
                    cardParams.type = 'Action'
                } else if (cardParams.type === 'AlwaysInput') {
                    cardParams.enabled = true;
                    cardParams.type = 'TextInput';
                } else if (this.editing && editable) {
                    cardParams.enabled = true;
                    if (cardParams.type === 'TextField') {
                        cardParams.type = 'TextInput';
                    } else if (cardParams.type === 'AlwaysAction') {
                        cardParams.type = 'Action';
                    }
                    if (item.required === 1) {
                        cardParams.required = true;
                    }
                } else {
                    cardParams.enabled = false;
                    if ('Checkbox,Select,DateTime'.indexOf(cardParams.type) < 0) {
                        cardParams.type = 'TextField';
                    }
                }

                if (item.maxEnable === true) {
                    cardParams.enabled = true;
                }else if (item.maxEnable === false){
                    cardParams.enabled = false;
                    
                }

                cardParams.labelWidth = item.labelWidth || '60px';

                item.cardParams = cardParams;
            }
            this.styleList = list;
        },
        refreshDisplayColumnList() {
            this.computeStyleList();
            this.filtedList = [];
            for (let column of this.styleList) {
                if (column.display) {
                    this.filtedList.push(column);
                }
            }
        },
        handleInputFocus(value, element) {
            // element.srcElement.select();
            this.$emit('inputfocus');
        },
        handleInputBlur() {
            this.$emit('inputblur');
        },
        _fnFocus(name) {
            this.$refs[name][0] && this.$refs[name][0].focus();
        },
        _fnReset(name) {
            this.$refs[name][0] && this.$refs[name][0].reset();
        },
        fnFileDataSlot(h, {row, column}) {
            let self = this;
            let _render = null;
            let length = row.length;
            let _renderRow = []
            for (let i = 0; i < length; i++) {
                let isImg = this.checkImg(row[i].fileType);
                let isVlog = this.checkTv(row[i].fileType);
                if (isImg) {
                    _renderRow.push(h('lj-img-pro', {
                        class: "file-rel-item",
                        props: {
                            src: row[i].base64,
                            md5: row[i].filemd5,
                            fileType: row[i].fileType,
                            delbtn: true
                        },
                        on: {
                            'bottom-nav': function() {
                                console.log(' bottomNav :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(i));
                                self.$emit("fileBottomNav", {row: row, column: column, rowIndex: i})
                            },
                            'image-click': function() {
                                console.log(' imageClick :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(i));
                                var images = [];
                                for (const picture of row) {
                                    var url = $lj.constant.cacheDir + "/" + picture.filemd5;
                                    images.push(url);
                                }
                                $lj.photoBrowser(images, i);
                            }
                        }
                    }));
                } else if (isVlog) {
                    _renderRow.push(h('lj-video-download', {
                        class: "file-rel-item",
                        props: {
                            src: row[i].url,
                            md5: row[i].filemd5,
                            fileType: row[i].fileType,
                            fileName: row[i].fileName,
                            delbtn: true
                        },
                        on: {
                            // bottomNav: "evOne.fjmxList.splice(index,1)",
                            'bottom-nav': function() {
                                self.$emit("fileBottomNav", {row: row, column: column, rowIndex: i})
                            },
                        }
                    }));
                }
            }
            let _renderAdd = h('div', {
                    class: "add-fj",
                    on: {
                        click: function() {
                            self.$emit("fileAdd")
                        }
                    }
                },
                [
                    h('i', {class: ["iconfont", "icon-camera1"]})
                ]
            );
            _render = h('van-cell', {
                class: "fj-box",
                },
                [
                    _renderRow,
                    this.editing ? _renderAdd : null,
                ]
            )
            return _render
        },
        photoBrowser(index) {
            var images = [];
            for (const picture of this.data.filedatas) {
                var url = $lj.constant.cacheDir + "/" + picture.filemd5;
                images.push(url);
            }
            $lj.photoBrowser(images, index);
        },
        checkImg(fileType){
            fileType = fileType.trim().toLowerCase();
            return fileType =="bmp" || fileType == "png" || fileType == "gif" || fileType == "jpg" || fileType == "jpeg";
        },
        checkTv(fileType){
            fileType = fileType.trim().toLowerCase();
            return fileType == "mp4" || fileType == "rmvb" || fileType == "avi" || fileType == "ts" || fileType == "mov";
        },
        getRender(h, column) {
            let _render = null;
            let _type = column.cardParams.type;
            if (column.type == 'file') {
                // 图片、视频，预览、上传
                _render = this.fnFileDataSlot(h, {row: this.data[column.property], column: column});
            } else if (_type == 'TextInput') {
                let _props = {
                    type: 'text',
                    value: this.data[column.property],
                    name: column.property,
                    label: column.label,
                    labelWidth: column.cardParams.labelWidth,
                    placeholder: column.placeholder || "",
                    clearable: true,
                }
                if (column.rules) {
                    _props.rules = column.rules
                }
                if (column.rightIcon) {
                    // _props["icon-prefix"] = column.iconPrefix || "iconfont"
                    _props.rightIcon = column.rightIcon
                }
                _render =  h('van-field', {
                    props: _props,
                    on: {
                        focus: this.handleInputFocus,
                        blur: this.handleInputBlur,
                        input: (val) => {
                            this.data[column.property] = val
                            this.$emit("cellInput", {row: this.data, column: column})
                        },
                        "click-right-icon": (event) => {
                            console.log(' click-right-icon :>>>>>>>>>>>>>>>>>>>>>', JSON.stringify(11111111111));
                            this.$emit("cellRightIcon", {row: this.data, column: column})
                        }
                    }
                });

            } else if (_type == 'TextArea') {
                let _props = {
                    type: 'textarea',
                    value: this.data[column.property],
                    name: column.property,
                    label: column.label,
                    labelWidth: column.cardParams.labelWidth,
                    placeholder: column.placeholder || "",
                };
                if (column.maxlength && column.maxlength > 0) {
                    _props.maxlength = column.maxlength;
                    _props['show-word-limit'] = true
                }
                if (column.autosize ) {
                    _props.autosize = column.autosize
                }
                if (column.inputLine ) {
                    _props.rows = column.inputLine
                }
                if (column.rules ) {
                    _props.rules = column.rules
                }
                _render =  h('van-field', {
                    props: _props,
                    on: {
                        focus: this.handleInputFocus,
                        blur: this.handleInputBlur,
                        input: (val) => {
                            this.data[column.property] = val
                            this.$emit("cellInput", {row: this.data, column: column})
                        }
                    }
                });

            } else if (_type == 'TextField') {
                _render =  h('van-cell', {
                    props: {
                        value: this.data[column.property],
                        name: column.property,
                        label: column.label,
                        labelWidth: column.cardParams.labelWidth,
                    }
                });

            }
            if (!_render) {
                alert("未匹配!" + column)
            }
            return _render
        }
    },

    watch: {
        editing(newVal, oldVal) {
            if (newVal !== oldVal) {
                this.refreshDisplayColumnList();
            }
        },
        columns(newVal, oldVal) {
            if (newVal !== oldVal) {
                this.refreshDisplayColumnList();
            }
        }
    },

    render(h) {
        let self = this;
        let RenderApp = null;
        let renderArray = [];

        if (this.filtedList.length) {
            this.filtedList.forEach(col => {
                let _render = this.getRender(h, col);
                renderArray.push(_render)
            });
        }
        RenderApp = h('div',{
                class: ["procode-route-edit-main"]
            }, 
            renderArray
        );
        return RenderApp
    }
};
</script>

<style lang="less" scoped>
    
</style>