<#ibizinclude>
./CONTROL-BASE.template.ftl
</#ibizinclude>

<#assign import_block>
import moment from 'moment';
</#assign>

<#ibizinclude>
../@MACRO/CONTROL/CONTROL_HEADER-BASE.vue.ftl
</#ibizinclude>

    /**
     * 显示处理提示
     *
     * @type {boolean}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    @Prop({ default: true }) protected showBusyIndicator!: boolean;

    /**
     * 当前年份
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected year: number = 0;

    /**
     * 当前月份(0~11)
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected month: number = 0;

    /**
     * 开始时间
     *
     * @type {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected start: any;

    /**
     * 标志数据
     * @type {Array<any>}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public sign: Array<any> = []
    
    /**
     * 结束时间
     *
     * @type {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected end: any;

    /**
     * 当前日期
     * @type {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected currentDate:any = new Date();

    /**
     * 当前天
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected day: number = 0;

    /**
     * 标记数组
     *
     * @type {Array<any>}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected markDate: Array<any> = [];

    /**
     * 事件时间
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public eventsDate :any = {};

    /**
     * 日历项集合对象
     *
     * @type {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public calendarItems: any = {};

    /**
     * 应用状态事件
     *
     * @public
     * @type {(Subscription | undefined)}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    public appStateEvent: Subscription | undefined;

    /**
     * 日历数据项模型
     *
     * @type {Map<string, any>}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public calendarItemsModel: Map<string, any> = new Map([
<#if ctrl.getPSSysCalendarItems()??>
    <#list ctrl.getPSSysCalendarItems() as calendarItem>
        [
            '${calendarItem.getItemType()?lower_case}', {
        <#if calendarItem.getPSAppDataEntity()??>
        <#assign _appde = calendarItem.getPSAppDataEntity() />
                appde: '${appde.getCodeName()?lower_case}',
                keyPSAppDEField: '${appde.getKeyPSAppDEField().getCodeName()?lower_case}',
                majorPSAppDEField: '<#if appde.getMajorPSAppDEField()??>${appde.getMajorPSAppDEField().getCodeName()?lower_case}<#else>srfmajortext</#if>',
        </#if>
            }
        ],
    </#list>
</#if>
    ]);

    /**
     * 日历显示状态
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public show = false;

    /**
     *  选中日期
     * 
     * @type {Array<any>}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected tileContent: Array<any> = [];

    /**
     *  默认选中
     * 
     * @type {Array<any>}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected value: Array<any> = [];

    /**
     *  日历样式
     * 
     * @type {Array<any>} 
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected calendarStyle: string = '${ctrl.getCalendarStyle()?lower_case}';

    /**
     * 获取多项数据
     *
     * @returns {any[]}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public getDatas(): any[] {
      return [];
    }
    
    /**
     * 时间轴加载条数
     *
     * @type {number}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */  
    public count :number = 20;


    /**
     * 获取单项树
     *
     * @returns {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public getData(): any {
      return {};
    }

    /**
     * vue生命周期created
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected created() {
      this.afterCreated();
    }

    /**
     * 处理created之后的逻辑
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected afterCreated() {
        this.initcurrentTime();
        if (this.viewState) {
            this.viewStateEvent = this.viewState.subscribe(({ tag, action, data }) => {
                if (!Object.is(this.name, tag)) {
                    return;
                }
                if (Object.is(action, "load")) {
                    this.formatData(this.currentDate, data);
                }
            });
        }
        if(AppCenterService && AppCenterService.getMessageCenter()){
            this.appStateEvent = AppCenterService.getMessageCenter().subscribe(({ name, action, data }) =>{
                if(!Object.is(name,"${ctrl.getPSAppDataEntity().getCodeName()}")){
                    return;
                }
                if(Object.is(action,'appRefresh')){
                    this.formatData(this.currentDate, data);
                }
            })
        }
    }

    /**
     * 事件绘制数据
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public evendata :any = {<#if ctrl.getPSSysCalendarItems()??><#list ctrl.getPSSysCalendarItems() as calendaritem><#if calendaritem.getItemType()??>${calendaritem.getItemType()?lower_case}</#if>:[],</#list></#if>}

    /**
     * 图标信息
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public illustration = [<#if ctrl.getPSSysCalendarItems()??><#list ctrl.getPSSysCalendarItems() as calendaritem>{color:"<#if calendaritem.getBKColor()??>${calendaritem.getBKColor()}</#if>",text:"<#if calendaritem.getName()??>${calendaritem.getName()}</#if>"},</#list></#if>]
    /**
     * 激活项
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected activeItem: string = '<#if ctrl.getPSSysCalendarItems()??><#list ctrl.getPSSysCalendarItems() as calendarItem><#if calendarItem_index == 0>${calendarItem.getItemType()?lower_case}<#break></#if></#list></#if>';

    /**
     * 分页节点切换
     *
     * @param {*} $event
     * @returns
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected ionChange($event:any) {
        let { detail: _detail } = $event;
        if (!_detail) {
            return ;
        }
        let { value: _value } = _detail;
        if (!_value) {
            return ;
        }
        this.activeItem = _value;
    }

    /**
     * 查询天数
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected selectday(year: any, month: any, weekIndex: any) {
        this.value = [year, month, this.day];
    }

    /**
     * 上一月事件的回调方法
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected prev(year: any, month: any, weekIndex: any) {
        if(this.calendarStyle == "month_timeline" || this.calendarStyle == "month"){
            this.selectday(year, month, this.day);
            this.formatData(new Date(year+'/'+month+'/'+'1'));
        }
        if(this.calendarStyle == "week_timeline" || this.calendarStyle == "week"){
            this.countWeeks(year,month,weekIndex);
        }
    }

    /**
     * 下一月事件的回调方法
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected next(year: any, month: any, weekIndex: any) {
        if(this.calendarStyle == "month_timeline" || this.calendarStyle == "month" ){
            this.selectday(year, month, this.day);
            this.formatData(new Date(year+'/'+month+'/'+'1'));
        }
        if(this.calendarStyle == "week_timeline" || this.calendarStyle == "week"){
            this.countWeeks(year,month,weekIndex);
        }
    }

    /**
     * 删除
     *
     * @param {any[]} datas
     * @returns {Promise<any>}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public async remove(datas: any[]): Promise<any> {
        const calendarItemModel: any = this.calendarItemsModel.get(this.activeItem);
        let { appde, keyPSAppDEField, majorPSAppDEField }: { appde: string, keyPSAppDEField: string, majorPSAppDEField: string } = calendarItemModel;
        let arg: any = {};
        let keys: Array<string> = [];
        let infoStr: string = '';
        datas.forEach((data: any, index: number) => {
            keys.push(data[keyPSAppDEField]);
            if (index < 5) {
                if (!Object.is(infoStr, '')) {
                    infoStr += '、';
                }
                infoStr += data[majorPSAppDEField];
            }
        });

        if (datas.length < 5) {
            infoStr = infoStr + this.$t('app.message.totle') + datas.length + this.$t('app.message.data');
        } else {
            infoStr = infoStr + '...' + this.$t('app.message.totle') + datas.length + this.$t('app.message.data');
        }
        return new Promise((resolve, reject) => {
            const _remove = async () => {
                let _context: any = { [appde]: keys.join(';') }
                const response: any = await this.service.delete(this.activeItem, { ...this.context, ..._context }, arg, this.showBusyIndicator);
                if (response && response.status === 200) {
                    this.$notice.success((this.$t('app.message.deleteSccess') as string));
                    this.formatData(this.currentDate);
                    resolve(response);
                } else {
                    const { error: _data } = response;
                    this.$notice.error(_data.message);
                    reject(response);
                }
            }

            this.$dialog.confirm({
                title: (this.$t('app.message.warning') as string),
                message: this.$t('app.message.confirmToDelete') + infoStr +','+ this.$t('app.message.unrecoverable') + '?',
            }).then(() => {
                _remove();
            }).catch(() => {
            });
        });
    }

    /**
     * 选择年份事件的回调方法
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected selectYear(year: any) {
      this.value = [year, this.month, this.day];
      this.formatData(new Date(year+'/'+this.month+'/'+this.day));
    }

    /**
     * 选择月份事件的回调方法
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected selectMonth(month: any, year: any) {
      this.selectday(year, month, this.day);
      this.formatData(new Date(year+'/'+month+'/'+this.day));
    }

    /**
     * 初始化当前时间
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected initcurrentTime() {
      let tempTime = new Date();
      this.year = tempTime.getFullYear();
      this.month = tempTime.getMonth();
      this.day = tempTime.getDate();
    }

    /**
     * 格式化数据
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected formatData(curtime:any,data: any = {}) {
        this.currentDate = curtime;
        this.year = curtime.getFullYear();
        this.month = curtime.getMonth();
        this.day = curtime.getDate();
        <#if ctrl.getCalendarStyle() == 'DAY'>
        this.start = (moment as any)(curtime).startOf('day').format('YYYY-MM-DD HH:mm:ss');
        this.end = (moment as any)(curtime).endOf('day').format('YYYY-MM-DD HH:mm:ss');
        </#if>
        <#if ctrl.getCalendarStyle() == 'MONTH' || ctrl.getCalendarStyle() == 'MONTH_TIMELINE' || ctrl.getCalendarStyle() == 'TIMELINE'>
        this.start = (moment as any)(curtime).startOf('month').format('YYYY-MM-DD HH:mm:ss');
        this.end = (moment as any)(curtime).endOf('month').format('YYYY-MM-DD HH:mm:ss');
        </#if>
        <#if ctrl.getCalendarStyle() == 'WEEK' || ctrl.getCalendarStyle() == 'WEEK_TIMELINE'>
        this.start = (moment as any)(curtime).startOf('week').format('YYYY-MM-DD HH:mm:ss');
        this.end = (moment as any)(curtime).endOf('week').format('YYYY-MM-DD HH:mm:ss');
        </#if>
        this.load(Object.assign(data, {
          "start": this.start,
          "end": this.end
        }));
    }
<#if ctrl.getCalendarStyle() == "DAY">
    /**
     * 点击前一天
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public prevDate(){ 
        let preDate = new Date(this.currentDate.getTime() - 24*60*60*1000); //前一天
        this.formatData(preDate);
    }

    /**
     * 点击后一天
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public nextDate(){
        let nextDate = new Date(this.currentDate.getTime() + 24*60*60*1000); //后一天
        this.formatData(nextDate);
    }
</#if>

    /**
     * 数据加载
     *
     * @protected
     * @param {*} [opt={}]
     * @returns {Promise<any>}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected async load(opt: any = {},isSetTileContent:boolean=true): Promise<any> {
        const arg: any = { ...opt };
        const isloading: boolean = this.showBusyIndicator === true ? true : false;
        const response: any = await this.service.search(this.activeItem, { ...this.context }, { ...arg }, this.showBusyIndicator);
        if (response && response.status === 200) {
            this.calendarItems = response.data;
            isSetTileContent?this.setTileContent():"";
        } else {
            this.$notice.error('系统异常,请重试!');
        }
        this.show = true;
    }

    /**
     * 设置事件数组
     *
     * @protected
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected setTileContent(){
        this.evendata = {<#if ctrl.getPSSysCalendarItems()??><#list ctrl.getPSSysCalendarItems() as calendaritem><#if calendaritem.getItemType()??>${calendaritem.getItemType()?lower_case}</#if>:[],</#list></#if>}
        <#if ctrl.getPSSysCalendarItems()??>
        <#list ctrl.getPSSysCalendarItems() as calendaritem>
        let ${calendaritem.getItemType()?lower_case}Item :Array<any> = this.parsingData('<#if calendaritem.getItemType()??>${calendaritem.getItemType()?lower_case}</#if>','<#if calendaritem.getBeginTimePSAppDEField()?? && calendaritem.getBeginTimePSAppDEField().getName()??>${calendaritem.getBeginTimePSAppDEField().getName()?lower_case}<#else>start</#if>');
        </#list>
        </#if>
        this.setSign(<#if ctrl.getPSSysCalendarItems()??><#list ctrl.getPSSysCalendarItems() as calendaritem><#if calendaritem.getItemType()??>${calendaritem.getItemType()?lower_case}Item</#if>,</#list></#if>);
    }

    /**
     * 格式化标志数据
     * 
     * @param any 
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public setSign(<#if ctrl.getPSSysCalendarItems()??><#list ctrl.getPSSysCalendarItems() as calendaritem><#if calendaritem.getItemType()??>${calendaritem.getItemType()?lower_case}Item: any</#if>,</#list></#if>){
      let signData: any[] = [<#if ctrl.getPSSysCalendarItems()??><#list ctrl.getPSSysCalendarItems() as calendaritem><#if calendaritem.getItemType()??>...${calendaritem.getItemType()?lower_case}Item</#if>,</#list></#if>];
      let obj: any = {}
      this.sign.length = 0;
      // 格式化数据
      signData.forEach((item:any,index:number) => {
          if(item.time.length == 10){
            let year = item.time.split('-')[0];
            let month = item.time.split('-')[1];
            let day = item.time.split('-')[2];
            if( month < 10 ){
              month = month.replace('0','')
            }
            if(day < 10){
              day = day.replace('0','')
            }
            item.time = year+'-'+month+'-'+day;
          }
          if(!obj[item.time]){
            Object.assign(obj,{[item.time]:item.evens})
          }else{
            obj[item.time].push(item.evens[0])
          }
      });
      for (const key in obj) {
        this.sign.push({time:key,evens:obj[key]});
      }
    }

    /**
     * 解析日历事件数据
     *
     * @param {string} tag
     * @param {string} mark
     * @returns {Array<any>}
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public parsingData(tag: string, mark: string): Array<any> {
        let dataItem: any = [];
        if (this.calendarItems[tag]) {
            this.calendarItems[tag].forEach((item: any) => {
                if (dataItem.length == 0) {
                    dataItem.push({ time: item[mark].substring(0, 10), evens: [item] });
                } else {
                    let flag = dataItem.every((currentValue:any)=>{
                        return (currentValue.time !== item[mark].substring(0, 10))
                    })
                    if(flag){
                        dataItem.push({ time: item[mark].substring(0, 10), evens: [item] });
                    }
                }
            });
        }
        return dataItem;
    }

    /**
     * 日历部件数据选择日期回调
     *
     * @param any 
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected clickDay(data: any) {
      if (data) {
        let reTime = data.join('/');
        let temptime = new Date(reTime);
        this.year = temptime.getFullYear();
        this.month = temptime.getMonth();
        this.day = temptime.getDate();
        this.start = (moment as any)(temptime).startOf('day').format('YYYY-MM-DD HH:mm:ss');
        this.end = (moment as any)(temptime).endOf('day').format('YYYY-MM-DD HH:mm:ss');
        this.load(Object.assign(this.viewparams, { "start": this.start, "end": this.end }),false);
      }
    }

    /**
     * 日程点击事件
     *
     * @param {*} $event 事件信息
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected getEditView(deName: string) {
        let view: any = {};
        switch(deName){
<#if view.getAllRelatedPSAppViews?? && view.getAllRelatedPSAppViews()??>
  <#list view.getAllRelatedPSAppViews() as editview>
            case "${editview.getPSDataEntity().getCodeName()?lower_case}": 
                view = {
                    viewname: '${srffilepath2(editview.getCodeName())}', 
                    height: ${editview.getHeight()?c}, 
                    width: ${editview.getWidth()?c},  
                    title: '${editview.title}', 
                    placement: '${editview.getOpenMode()}',
                    deResParameters: <#rt>
    <#if editview.isPSDEView()>
      [<#t>
      <#if editview.getPSAppDERSPathCount() gt 0>
        <#list editview.getPSAppDERSPath(editview.getPSAppDERSPathCount() - 1) as deRSPath>
        <#assign majorPSAppDataEntity = deRSPath.getMajorPSAppDataEntity()/><#t>
          { pathName: '${srfpluralize(majorPSAppDataEntity.codeName)?lower_case}', parameterName: '${majorPSAppDataEntity.getCodeName()?lower_case}' }, <#t>
        </#list>
      </#if>
      ],<#lt>
    <#else>
      [],<#lt>
    </#if>
                    parameters: <#rt>
    [<#t>
    <#if editview.isPSDEView() && editview.getPSAppDataEntity()??>
      <#assign appDataEntity = editview.getPSAppDataEntity()/>
      { pathName: '${srfpluralize(appDataEntity.codeName)?lower_case}', parameterName: '${appDataEntity.getCodeName()?lower_case}' }, <#t>
      { pathName: '${editview.getPSDEViewCodeName()?lower_case}', parameterName: '${editview.getPSDEViewCodeName()?lower_case}' } <#t>
    <#else>
      { pathName: '${editview.getCodeName()?lower_case}', parameterName: '${editview.getCodeName()?lower_case}' } <#t>
    </#if>
    ],<#lt>
                };
                break;
  </#list>
</#if>
        }
        return view;
    }

    /**
     * 日程点击事件
     *
     * @param {*} $event 事件信息
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected async onEventClick($event: any): Promise<any> {
        let view: any = {};
        let _context: any = { ...this.context };
        let itemType = $event.itemType;
        switch(itemType) {
<#if ctrl.getPSSysCalendarItems()??>
  <#list ctrl.getPSSysCalendarItems() as calendarItem>
    <#if calendarItem.getPSAppDataEntity()??>
      <#assign _appde = calendarItem.getPSAppDataEntity() />
            case "${calendarItem.getItemType()?lower_case}":
                _context.${_appde.getCodeName()?lower_case} = $event.${_appde.getCodeName()?lower_case};
                view = this.getEditView("${_appde.getCodeName()?lower_case}");
                break;
    </#if>
  </#list>
</#if>
        }
        if (Object.is(view.placement, 'INDEXVIEWTAB') || Object.is(view.placement, '')) {
            const routePath = this.globaluiservice.openService.formatRouteParam(_context, view.deResParameters, view.parameters, [this.context], this.viewparams);
            this.$router.push(routePath);
        } else {
            let response: any;
            if (Object.is(view.placement, 'POPUPMODAL')) {
                response = await this.$appmodal.openModal(view,  _context,  { ...this.viewparams });
            } else if (view.placement.startsWith('DRAWER')) {
                response = await this.$appdrawer.openDrawer(view,  _context,  { ...this.viewparams });
            }
            if (response && Object.is(response.ret, 'OK')) {
                // 刷新日历
                this.load(Object.assign(this.viewparams, { "start": this.start, "end": this.end }),false);
            }
        }
    }
    /**
     * 根据周下标计算事件
     *
     * @param {*} $event 事件信息
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public countWeeks(year: any, month: any, week: any) {
        let date = new Date(year + '/' + month + '/' + 1);
        let weekline = date.getDay();
        if(weekline == 0){
          this.formatData(new Date(year + '/' + month + '/' + (week*7 +1)));
        }else{
          this.formatData(new Date(year + '/' + month + '/' + (week*7 - weekline + 1)));
        }
    }

    
    /**
    * 选中数组
    *
    * @param {Array<any>}
     * @memberof ${srfclassname('${ctrl.codeName}')}
    */
    public selectedArray:Array<any> = [];
    
   /**
     * 是否展示多选
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    @Prop({default:false}) showCheack?: boolean;

    /**
     * 选中或取消事件
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public checkboxSelect(item:any){
        let count = this.selectedArray.findIndex((i) => {
            return i.mobile_entity1id == item.mobile_entity1id;
        });
        if(count == -1){
            this.selectedArray.push(item);
        }else{
            this.selectedArray.splice(count,1);
        }
    }

    /**
     * vue 生命周期
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    public destroyed() {
        this.afterDestroy();
    }

    /**
     * 执行destroyed后的逻辑
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}
     */
    protected afterDestroy() {
        if (this.viewStateEvent) {
            this.viewStateEvent.unsubscribe();
        }
        if(this.appStateEvent){
            this.appStateEvent.unsubscribe();
        }
        window.removeEventListener('contextmenu',()=>{});
        <#if destroyed_block??>
        ${destroyed_block}
        </#if>
    }

<#ibizinclude>
../@MACRO/CONTROL/CONTROL_BOTTOM-BASE.vue.ftl
</#ibizinclude>

<#ibizinclude>
../@MACRO/CONTROL/CONTROL-BASE.style.ftl
</#ibizinclude>