import { ListModel } from '@ibiz-template/model';
import { ControlVO } from '@ibiz-template/service';
import { useListController, useNamespace } from '@ibiz-template/vue-util';
import {
  defineComponent,
  h,
  PropType,
  onMounted,
  watch,
  getCurrentInstance,
} from 'vue';
import './list-control.scss';
import { useListEvent } from './list-control.util';

export const ListControl = defineComponent({
  name: 'ListControl',
  props: {
    modelData: {
      type: ListModel,
      required: true,
    },
    context: { type: Object as PropType<IContext>, required: true },
    params: { type: Object as PropType<IParams>, default: () => ({}) },
    /**
     * 行数据默认激活模式
     * - 0 不激活
     * - 1 单击激活
     * - 2 双击激活(默认值)
     *
     * @type {(number | 0 | 1 | 2)}
     */
    mdCtrlActiveMode: { type: Number, default: 2 },
    /**
     * 是否默认选中第一条数据
     *
     * @type boolean
     */
    isSelectFirstDefault: { type: Boolean, required: false },
    /**
     * 默认选中的数据
     *
     * @type Array
     */
    defaultSelectKeys: { type: Array<string>, required: false },
    /**
     * 是否包含在导航视图内
     *
     * @type boolean
     */
    isExpView: { type: Boolean, required: false },
  },
  setup(props) {
    const { proxy } = getCurrentInstance()!;
    const ns = useNamespace('control-list');
    const c = useListController(
      proxy,
      props.modelData!,
      props.context!,
      props.params,
    );

    const { handleClick, handleDblClick } = useListEvent(c);

    onMounted(() => {
      // 外部传入默认选中数组，第一次加载数据后选中其中第一项，未传入默认数据，选中全部数据第一项
      watch(
        () => c,
        (newVal, oldVal) => {
          if (props.isExpView && newVal && newVal !== oldVal) {
            let defaultSelectItem = c.items[0];
            if (props.defaultSelectKeys && props.defaultSelectKeys.length > 0) {
              const defaultItem = c.items.find((item: ControlVO) => {
                return item.srfkey === props.defaultSelectKeys![0];
              });
              if (defaultItem) {
                defaultSelectItem = defaultItem;
              }
            }
            // 默认选中数据
            if (defaultSelectItem) {
              c.onSelectionChange([defaultSelectItem]);
            }
          }
        },
        { immediate: true },
      );

      watch(
        () => c.items.length,
        (newVal, oldVal) => {
          // 导航删除后高亮第一条
          if (props.isExpView && newVal && newVal + 1 === oldVal) {
            c.onSelectionChange([c.items[0]]);
          }
        },
        { immediate: true, deep: true },
      );
    });

    // 绘制默认列表项
    const renderDefaultItem = (item: ControlVO) => {
      const findIndex = c.selectedData.findIndex(data => {
        return data.srfkey === item.srfkey;
      });
      const itemClass = [ns.b('item'), ns.is('active', findIndex !== -1)];
      return (
        <div
          class={itemClass}
          key={item.srfkey}
          onClick={() => handleClick(item)}
          onDblclick={() => handleDblClick(item)}
        >
          {c.layoutPanelProvider
            ? h(c.layoutPanelProvider.component, {
                props: {
                  modelData: c.model,
                  context: c.context,
                  params: c.params,
                  inputData: item,
                },
              })
            : `${item.srfmajortext}:${item.srfkey}`}
        </div>
      );
    };

    // // 绘制分组
    // const renderGroup = () => {
    //   return c.groupData.map((group: IData) => {
    //     return (
    //       <el-collapse-item class={ns.e('group-item')}>
    //         {{
    //           title: () => {
    //             return <b>{group.group}</b>;
    //           },
    //           default: () => {
    //             if (group.children.length > 0) {
    //               return (
    //                 <div>
    //                   {group.children.map((groupChild: ControlVO) => {
    //                     return renderDefaultItem(groupChild);
    //                   })}
    //                 </div>
    //               );
    //             }
    //             return <div class={ns.e('group-item-empty')}>无数据</div>;
    //           },
    //         }}
    //       </el-collapse-item>
    //     );
    //   });
    // };

    // 绘制卡片内容
    const renderListContent = () => {
      if (!c.model.source.enableGroup) {
        return c.items.map(item => {
          return renderDefaultItem(item);
        });
      }
      return <el-collapse></el-collapse>;
    };

    // 绘制加载更多
    const renderLoadMore = () => {
      return Object.is(c.total, c.items.length) ? null : (
        <div
          onClick={(e: MouseEvent) => c.loadMore(e)}
          class={ns.e('load-more')}
        >
          加载更多
        </div>
      );
    };

    return { c, ns, renderListContent, renderLoadMore };
  },
  render() {
    return (
      <control-layout modelData={this.c.model}>
        {this.c.complete && [this.renderListContent(), this.renderLoadMore()]}
      </control-layout>
    );
  },
});
