import {
  formatToCodeListText,
  GridFieldColumnController,
  GridRowController,
} from '@ibiz-template/controller';
import { computed, defineComponent } from 'vue';
import { useNamespace } from '@ibiz-template/vue-util';
import '@ibiz-template/theme/style/components/widgets/grid/grid-field-column.scss';

export const GridFieldColumn = defineComponent({
  name: 'GridFieldColumn',
  props: {
    controller: {
      type: GridFieldColumnController,
      required: true,
    },
    row: {
      type: GridRowController,
      required: true,
    },
  },
  setup(props) {
    const ns = useNamespace('grid-field-column');

    // 代码表转换文本，如果不转换则为null
    const codeListText = computed(() => {
      // 非前台处理，不做值转换
      if (props.controller.model.source.cLConvertMode !== 'FRONT') {
        return null;
      }
      const fieldValue = props.row.data[props.controller.model.codeName];
      if (props.controller.codeListItems?.length && fieldValue) {
        return formatToCodeListText(
          fieldValue,
          props.controller.codeListItems!,
        );
      }
      return null;
    });

    /**
     * 单元格点击事件
     *
     * @author lxm
     * @date 2022-09-28 18:09:27
     * @param {MouseEvent} event
     */
    const onCellClick = (event: MouseEvent) => {
      if (props.controller.isLinkColumn) {
        // 阻止触发行点击
        event.stopPropagation();
        props.controller.openLinkView(props.row, event);
      } else if (props.controller.hasAction) {
        // 阻止触发行点击
        event.stopPropagation();
        props.controller.triggerAction(props.row, event);
      }
    };

    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 });
    });

    const showText = computed(() => {
      return (
        codeListText.value || props.row.data[props.controller.model.codeName]
      );
    });

    return { ns, alignStyle, showText, onCellClick };
  },
  render() {
    const c = this.controller;
    return (
      <div
        class={[this.ns.b(), c.clickable && this.ns.m('clickable')]}
        style={this.alignStyle}
        onClick={this.onCellClick}
      >
        <span class={this.ns.e('text')}>
          {this.showText}
          {this.showText && c.model.unitName}
        </span>
      </div>
    );
  },
});
export default GridFieldColumn;
