import {
  GridFieldEditColumnController,
  GridRowController,
} from '@ibiz-template/controller';
import { computed, defineComponent } from 'vue';
import { useNamespace } from '@ibiz-template/vue-util';

export const GridFieldEditColumn = defineComponent({
  name: 'GridFieldEditColumn',
  props: {
    controller: {
      type: GridFieldEditColumnController,
      required: true,
    },
    row: {
      type: GridRowController,
      required: true,
    },
  },
  setup(props) {
    const ns = useNamespace('grid-field-edit-column');
    const editItemC = props.controller.editItem;

    // 编辑器值变更事件
    const rowDataChange = async (val: unknown, name?: string) => {
      await editItemC.setRowValue(props.row, val, name);
    };

    // 行数据保存
    const rowSave = async () => {
      return editItemC.grid.save(props.row.data);
    };

    const onStopPropagation = (e: MouseEvent) => {
      e.stopPropagation();
    };

    const alignStyle = computed(() => {
      let justContent = '';
      switch (editItemC.model.align) {
        case 'LEFT':
          justContent = 'flex-start';
          break;
        case 'RIGHT':
          justContent = 'flex-end';
          break;
        default:
          justContent = 'center';
          break;
      }
      return ns.cssVarBlock({ 'justify-content': justContent });
    });

    const isReadonly = computed(() => {
      const codeName = editItemC.model.codeName;
      return (
        props.row.columnState[codeName]!.disabled || editItemC.editor!.readonly
      );
    });

    return {
      ns,
      alignStyle,
      editItemC,
      isReadonly,
      rowDataChange,
      rowSave,
      onStopPropagation,
    };
  },
  render(h) {
    const codeName = this.editItemC.model.codeName;
    return (
      <appGridEditItem
        required={this.editItemC.required}
        error={this.row.errors[codeName]}
        nativeondblclick={this.onStopPropagation}
        nativeonClick={this.onStopPropagation}
        style={this.alignStyle}
      >
        {this.editItemC.editorProvider &&
          h(this.editItemC.editorProvider.gridEditor, {
            props: {
              value: this.row.data[codeName],
              data: this.row.data,
              controller: this.editItemC.editor,
              // 单元格行编辑下，单个出禁用无意义，所以禁用走的还是只读
              disabled: false,
              readonly: this.isReadonly,
              hasError: !!this.row.errors[codeName],
            },
            on: {
              change: this.rowDataChange.bind(this),
              rowSave: this.rowSave.bind(this),
            },
          })}
      </appGridEditItem>
    );
  },
});
export default GridFieldEditColumn;
