<template>
    <div :class="curClassName" :style="curStyle">
        <img :src="imgUrl" />
    </div>
</template>
<script lang = 'ts'>
import { Vue, Component, Prop, Watch } from 'vue-property-decorator';
import { Environment } from "@/environments/environment";
@Component({})
export default class AppFieldImageDynamic extends Vue {
    /**
     * 名称
     *
     * @type {*}
     * @memberof AppRawItemImage
     */
    @Prop() public name!: string;

    /**
     * 模型
     *
     * @type {*}
     * @memberof AppRawItemImage
     */
    @Prop() public layoutModelDetails!: any;

    /**
     * 输入值
     *
     * @type {string}
     * @memberof AppFieldImageDynamic
     */
    @Prop() public value: any;

    /**
     * 下标
     *
     * @type {number}
     * @memberof AppFieldImageDynamic
     */
    @Prop() public index?: number;

    /**
     * 值变更
     *
     * @memberof AppFieldImageDynamic
     */
    @Watch('value',{immediate: true})
    onValueChange(newVal: any, oldVal: any) {
        this.handleDynaImg();
    }

    /**
     * 项名称
     *
     * @type {*}
     * @memberof AppFieldImageDynamic
     */
    get itemName() {
        return (this.index || this.index === 0) ? `${this.name}_${this.index}` : this.name;
    }

    /**
     * 动态图片路径
     *
     * @memberof AppFieldImageDynamic
     */
    protected dynaImgUrl: string = '';

    /**
    * 下载文件路径
    *
    * @memberof AppFieldImageDynamic
    */
    public downloadUrl = Environment.ExportFile;

    /**
     * 图片路径
     *
     * @memberof AppFieldImageDynamic
     */
    get imgUrl(): string {
        return this.dynaImgUrl;
    }

    /**
     * 类名
     *
     * @memberof AppFieldImageDynamic
     */
    get curClassName() {
        const layoutModel = this.layoutModelDetails[this.itemName];
        if (layoutModel) {
            return `app-field-image-dynamic ${this.itemName} ${layoutModel.sysCss}`;
        }
    }

    /**
     * 当前容器样式
     * 
     * @memberof AppFieldImageDynamic
     */
    get curStyle() {
        const layoutModel = this.layoutModelDetails[this.itemName];
        if (layoutModel) {
            return layoutModel.getElementStyle();
        }
    }

    /**
    * 处理动态图片
    *
    * @memberof AppFieldImageDynamic
    */
    protected handleDynaImg() {
        if (this.value && typeof this.value == "string") {
            // 默认识别文件对象形式，识别失败则为全路径模式
            try {
                const _files = JSON.parse(this.value);
                const file = _files instanceof Array ? _files[0] : null;
                const url = file && file.id ? `${this.downloadUrl}/${file.id}` : "";
                this.dynaImgUrl = url;
            } catch (error) {
                this.dynaImgUrl = this.value;
            }
        }
    }
}
</script>
<style lang = "less">
@import './app-field-image-dynamic.less';
</style>