import {
  GridEditItemController,
  GridRowController,
} from '@ibiz-template/controller';
import { computed, defineComponent, getCurrentInstance } from 'vue';
import '@ibiz-template/theme/style/components/widgets/grid/grid-edit-item.scss';
import { useForce, useNamespace } from '@ibiz-template/vue-util';

export const GridEditItem = defineComponent({
  name: 'GridEditItem',
  props: {
    controller: {
      type: GridEditItemController,
      required: true,
    },
    row: {
      type: GridRowController,
      required: true,
    },
  },
  setup(props) {
    const ns = useNamespace('grid-edit-item');
    const force = useForce(getCurrentInstance()!.proxy);

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

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

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

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

    return { ns, alignStyle, rowDataChange, rowSave, onStopPropagation };
  },
  render(h) {
    const codeName = this.controller.model.codeName;
    return (
      <appGridEditItem
        required={this.controller.required}
        error={this.row.errors[codeName]}
        nativeondblclick={this.onStopPropagation}
        nativeonClick={this.onStopPropagation}
        style={this.alignStyle}
      >
        {this.controller.editorProvider &&
          h(this.controller.editorProvider.gridEditor, {
            props: {
              value: this.row.data[codeName],
              data: this.row.data,
              controller: this.controller.editor,
              disabled: this.row.columnState[codeName]!.disabled,
              rowDataChange: this.rowDataChange.bind(this),
              rowSave: this.rowSave.bind(this),
            },
          })}
      </appGridEditItem>
    );
  },
});
export default GridEditItem;
