<template>
    <div class="app-picker-select-view">
        <Dropdown :visible="visible" trigger="custom" style="left:0px;width: 100%" @on-clickoutside="() => {triggerMenu(false);}" >
          <Input v-model="inputValue" class="tree-input" type="text" :placeholder="placeholder" :disabled="disabled" @on-change="OnInputChange" @on-focus="()=>{triggerMenu(true);}" >
              <template v-slot:suffix>
                  <i v-if="inputValue && !disabled" class='el-icon-circle-close' @click="onClear"></i>
                  <Icon :type="visible ? 'ios-arrow-up' : 'ios-arrow-down'" class="icon-arrow" @click="() => {triggerMenu();}"></Icon>
                  <icon v-if="linkview" type="ios-open-outline" @click="openLinkView"/>
              </template>
          </Input>
          <DropdownMenu slot="list">
              <component
                :is="pickupView.viewname"
                :viewdata="viewdata"
                :viewparam="viewparam"
                :ifShowButtons="false"
                :viewDefaultUsage="false"
                @viewdataschange="setValue"
                style="height:100%;">
              </component>
          </DropdownMenu>
        </Dropdown>
    </div>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator';
import { CreateElement } from 'vue';
import { Subject, Subscription } from 'rxjs';
import { ViewTool } from '@/utils/view-tool/view-tool';

@Component({})
export default class AppPickerSelectView extends Vue {
    /**
     * 视图上下文
     *
     * @type {*}
     * @memberof AppFormDRUIPart
     */
    @Prop() public context!: any;

    /**
     * 视图参数
     *
     * @type {*}
     * @memberof AppFormDRUIPart
     */
    @Prop() public viewparams!: any;
    
    /**
     * 视图参数
     *
     * @type {string}
     * @memberof AppTreePicker
     */
    public viewparam: any = JSON.stringify(this.viewparams);;
    
    /**
     * 视图上下文
     *
     * @type {string}
     * @memberof AppTreePicker
     */
    public viewdata: any = JSON.stringify(this.context);

    /**
     * 表单数据
     *
     * @type {*}
     * @memberof AppPicker
     */
    @Prop() public data!: any;

    /**
     * 值
     *
     * @type {*}
     * @memberof AppTreePicker
     */
    @Prop() public value: any;

    /**
     * 是否启用
     *
     * @type {boolean}
     * @memberof AppPicker
     */
    @Prop({default: false}) public disabled!: boolean;
    
    /**
     * 应用实体主信息属性名称
     *
     * @type {string}
     * @memberof AppAutocomplete
     */
    @Prop({default: 'srfmajortext'}) public deMajorField!: string;

    /**
     * 应用实体主键属性名称
     *
     * @type {string}
     * @memberof AppAutocomplete
     */
    @Prop({default: 'srfkey'}) public deKeyField!: string;

    /**
     * 输入框值
     *
     * @type {string}
     * @memberof AppTreePicker
     */
    public inputValue: any = '';

    /**
     * 值项名称
     *
     * @type {string}
     * @memberof AppPicker
     */
    @Prop() public valueitem?: string;

    /**
     * 关联视图名称
     *
     * @type {string}
     * @memberof AppPicker
     */
    @Prop() public pickupView?: any;

    /**
     * 数据链接视图参数
     *
     * @type {*}
     * @memberof AppPicker
     */
    @Prop() public linkview?: any;

    /**
     * 提示信息
     *
     * @type {string}
     * @memberof AppTreePicker
     */
    @Prop({default:"请选择..."}) public placeholder!: string;

    /**
     * 属性项名称
     *
     * @type {string}
     * @memberof AppPicker
     */
    @Prop() public name!: string;

    /**
     * 编辑器参数
     *
     * @type {*}
     * @memberof AppTreePicker
     */
    @Prop() public itemParam: any;

    /**
     * 下拉显示控制变量
     *
     * @type {string}
     * @memberof AppTreePicker
     */
    public visible: boolean = false;

    /**
     * 父视图数据
     *
     * @type {string}
     * @memberof AppTreePicker
     */
    public srfparentdata: any = {};

    /**
     * 输入框change事件
     * 
     * @param $event 事件对象
     * @memberof AppTreePicker
     */
    public OnInputChange($event: any){
        let _viewdata =  Object.assign({ query: this.inputValue }, JSON.parse(this.viewdata)) ;
        this.viewdata = JSON.stringify(_viewdata);
    }

    /**
     * 输入框change事件
     * 
     * @param $event 事件对象
     * @memberof AppTreePicker
     */
    public triggerMenu(visible?: boolean){
        if(this.disabled){
          return;
        }
        if (!visible) {
            this.visible = !this.visible;
        } else {
            this.visible = visible;
        }
    }

    /**
     * 公共参数处理
     *
     * @param {*} arg
     * @returns
     * @memberof AppPicker
     */
    public handlePublicParams(arg: any): boolean {
        if (!this.itemParam) {
            return true;
        }
        if (!this.data) {
            this.$Notice.error({ title: '错误', desc: '表单数据异常' });
            return false;
        }
        // 合并表单参数
        arg.param = JSON.parse(JSON.stringify(this.viewparams));
        arg.context = JSON.parse(JSON.stringify(this.context));
        // 附加参数处理
        if (this.itemParam.context) {
          let _context = this.$util.formatData(this.data,this.itemParam.context);
            Object.assign(arg.context,_context);
        }
        if (this.itemParam.param) {
          let _param = this.$util.formatData(this.data,this.itemParam.param);
            Object.assign(arg.param,_param);
        }
        if (this.itemParam.parentdata) {
          let _parentdata = this.$util.formatData(this.data,this.itemParam.parentdata);
            Object.assign(arg.param,_parentdata);
        }
        return true;
    }

    /**
     * 监控值
     *
     * @param {*} newVal
     * @param {*} oldVal
     * @memberof AppFormDRUIPart
     */
    @Watch('data',{deep:true})
    onActivedataChange(newVal: any, oldVal: any) {
        // 公共参数处理
        let data: any = {};
        const bcancel: boolean = this.handlePublicParams(data);
        if (!bcancel) {
            return;
        }
        // 参数处理
        this.viewdata = JSON.stringify(data.context);
        this.viewparam = JSON.stringify(data.param);
    }

    /**
     * 值变化
     *
     * @param {*} newVal
     * @param {*} oldVal
     * @memberof AppPicker
     */
    @Watch('value')
    public onValueChange(newVal: any, oldVal: any) {
        this.inputValue = newVal;
    }

    /**
     * 生命周期
     *
     * @memberof AppTreePicker
     */
    public created() {
        // 公共参数处理
        let data: any = {};
        const bcancel: boolean = this.handlePublicParams(data);
        if (!bcancel) {
            return;
        }
        // 参数处理
        this.viewdata = JSON.stringify(data.context);
        this.viewparam = JSON.stringify(data.param);
    }

    /**
     * vue 生命周期
     *
     * @memberof SelectType
     */
    public destroyed() {

    }

    /**
     * 设置值
     *
     * @param {*} item
     * @memberof AppTreePicker
     */
    public setValue(item: any) {
        this.visible = false;
        if(item.length == 0){
            this.onClear(null);
            return;
        }
        if (this.valueitem) {
            let tempvalue = item[0][this.deMajorField] ? item[0][this.deKeyField] : item[0].srfkey;
            this.$emit('formitemvaluechange', { name: this.valueitem, value: item[0][this.deKeyField] });
        }
        if (this.name) {
            let tempvalue = item[0][this.deMajorField] ? item[0][this.deMajorField] : item[0].srfmajortext;
            this.$emit('formitemvaluechange', { name: this.name, value: tempvalue });
        }
    }

    /**
     * 清除
     */
    public onClear($event: any): void {
        if (this.valueitem) {
            this.$emit('formitemvaluechange', { name: this.valueitem, value: '' });
        }
        if (this.name) {
            this.$emit('formitemvaluechange', { name: this.name, value: '' });
        }
        this.$forceUpdate();
    }

    
    /**
     * 打开链接视图
     *
     * @memberof AppPicker
     */
    public openLinkView($event: any): void {
        if (this.disabled) {
            return;
        }
        if (!this.data || !this.valueitem || !this.data[this.valueitem]) {
            this.$Notice.error({ title: '错误', desc: '值项异常!' });
            return;
        }
        // 公共参数处理
        let data: any = {};
        const bcancel: boolean = this.handlePublicParams(data);
        if (!bcancel) {
            return;
        }
        // 参数处理
        let _context = data.context;
        let _param = data.param;
        Object.assign(_context, { [this.deKeyField]: this.data[this.valueitem] });
        const view = JSON.parse(JSON.stringify(this.linkview));
        const viewname2: string = this.$util.srfFilePath2(view.viewname);
        view.viewname = viewname2;

        if (Object.is(view.placement, 'INDEXVIEWTAB') || Object.is(view.placement, '')) {
            this.openIndexViewTab(view, _context, _param);
        } else if (Object.is(view.placement, 'POPOVER')) {
            this.openPopOver($event, view, _context, _param);
        } else if (Object.is(view.placement, 'POPUPMODAL')) {
            this.openPopupModal(view, _context, _param);
        } else if (view.placement.startsWith('DRAWER')) {
            this.openDrawer(view, _context, _param);
        }
    }

    /**
     * 路由模式打开视图
     *
     * @private
     * @param {string} viewpath
     * @param {*} data
     * @memberof AppPicker
     */
    private openIndexViewTab(view: any, context: any, param: any): void {
        const routePath = this.$viewTool.buildUpRoutePath(this.$route, this.context, view.deResParameters, view.parameters, [context] , param);
        this.$router.push(routePath);
    }

    /**
     * 气泡卡片模式打开
     *
     * @private
     * @param {*} $event
     * @param {*} view
     * @param {*} data
     * @memberof AppPicker
     */
    private openPopOver($event: any, view: any, context: any, param: any): void {
        let container: Subject<any> = this.$apppopover.openPop($event, view, context, param);
        container.subscribe((result: any) => {
            if (!result || !Object.is(result.ret, 'OK')) {
                return;
            }
            this.openViewClose(result);
        });
    }


    /**
     * 模态模式打开视图
     *
     * @private
     * @param {*} view
     * @param {*} data
     * @memberof AppPicker
     */
    private openPopupModal(view: any, context: any, param: any): void {
        let container: Subject<any> = this.$appmodal.openModal(view, context, param);
        container.subscribe((result: any) => {
            if (!result || !Object.is(result.ret, 'OK')) {
                return;
            }
            this.openViewClose(result);
        });
    }

    /**
     * 抽屉模式打开视图
     *
     * @private
     * @param {*} view
     * @param {*} data
     * @memberof AppPicker
     */
    private openDrawer(view: any, context: any, param: any): void {
        let container: Subject<any> = this.$appdrawer.openDrawer(view, context, param);
        container.subscribe((result: any) => {
            if (!result || !Object.is(result.ret, 'OK')) {
                return;
            }
            this.openViewClose(result);
        });
    }

    /**
     * 打开页面关闭
     *
     * @param {*} result
     * @memberof AppPicker
     */
    public openViewClose(result: any) {
        let item: any = {};
        if (result.datas && Array.isArray(result.datas)) {
            Object.assign(item, result.datas[0]);
        }

        if (this.data) {
            if (this.valueitem) {
                this.$emit('formitemvaluechange', { name: this.valueitem, value: item[this.deKeyField]?item[this.deKeyField]:item["srfkey"] });
            }
            if (this.name) {
                this.$emit('formitemvaluechange', { name: this.name, value: item[this.deMajorField]?item[this.deMajorField]:item["srfmajortext"] });
            }
        }
    }

}
</script>

<style lang='less'>
@import './app-picker-select-view.less';
</style>