<template>
  <LjDialog
    ref="LjSelectorRef"
    class="is-selector lj-selector"
    v-bind="{
      ...drawerDefineProp
    }"
    :modal="false"
    :style="{ height: '60%' }"
  >
    <template #header>
      <div class="flx-1">
        <span class="text-h5-b">{{ title }}</span>
      </div>
    </template>
    <div class="flx-col h-full">
      <LjHeaderMenu :update="dialogVisible" :data="initParams" :action="btnGroup" />
      <LjFoldLayoutDouble v-bind="showLayout" class="flx-1 overflow-hidden">
        <template #firstLeft>
          <template v-if="multipleLimit == 1">
            <el-collapse v-model="activeCollapse" accordion class="ljselector-aside-collapse ml-12">
              <slot name="aside"></slot>
            </el-collapse>
          </template>
          <template v-else>
            <el-collapse v-model="activeCollapse" accordion class="ljselector-aside-collapse ml-12">
              <el-collapse-item name="selected">
                <template #title>
                  {{ $t("common.selected") }}
                  <el-tag
                    :type="value.length ? 'danger' : 'info'"
                    class="ml-4"
                    effect="dark"
                    round
                    disable-transitions
                    size="small"
                  >
                    {{ value.length }}
                  </el-tag>
                </template>
                <template v-if="value.length">
                  <slot name="selected">
                    <draggable :list="value" :item-key="itemKey" animation="300" forceFallback="true" draggable>
                      <template #item="{ element, index }">
                        <SalePriceItem
                          v-bind="itemLayout"
                          keyattr="classid"
                          :data="element"
                          editable
                          @del-item="handleDelItem(index)"
                        >
                        </SalePriceItem>
                      </template>
                    </draggable>
                  </slot>
                </template>
                <el-empty v-else description="暂未选择" :image-size="120" />
              </el-collapse-item>
              <slot name="aside"></slot>
            </el-collapse>
          </template>
        </template>
        <template #secondMain>
          <div class="flx h-full">
            <div class="flx-col w-full">
              <slot name="default" :params="initParams"></slot>
            </div>
          </div>
        </template>
      </LjFoldLayoutDouble>
    </div>
  </LjDialog>
</template>

<script lang="tsx" setup name="LjSelector">
import { reactive, toRefs, ref, onMounted, nextTick, inject, watch, computed } from "vue";
import LjDialog from "@/components/LjDialog/index.vue";
import LjFoldLayoutDouble from "@/components/LjFoldLayoutDouble/index.vue";
// import LjVxeTable from "@/components/LjVxeTable/index.vue";

// import { getL1Cusarea } from "@/api/modules/saletask";
// import TreeFilter from "@/components/TreeFilter/index.vue";
// import { useCust } from "@/views/saletask/cust/hooks/index";
import { useI18n } from "vue-i18n";
// import { DwnameEnum } from "@/enums/dwnameEnum";
import { defaultsDeep } from "lodash-es";
// import { CommonDynamicSelect } from "@/api/modules/common";
import LjHeaderMenu from "@/components/LjHeaderMenu/index.vue";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { detailAction } from "@/components/LjDetail/interface";
import SalePriceItem from "./components/SalePriceItem.vue";
import draggable from "vuedraggable";
import { ElMessage } from "element-plus";
import { isArray, isBoolean } from "@/utils/is";
import { t } from "@/utils/i18n";

interface LjDialogSelectorProps {
  /**
   * @description 弹窗标题
   */
  title: string;
  /**
   * @description 按钮功能组
   */
  action?: detailAction[];
  /**
   * @description 多选限制，0：不设限，1：单选，>1：多选
   * @default 1
   */
  multipleLimit?: number;
  /**
   * @description 已选列表
   */
  value?: any;
  /**
   * @description 已选列表的item布局
   */
  itemLayout?: any;
  /**
   * @description 唯一字段名，draggable需要
   */
  itemKey?: string;
  /**
   * @description 提交前检查
   * @param params
   */
  beforeSubmit?: (params?: any) => boolean;
  layout?: any;
  submitText?: string;
}

// const { t } = useI18n();

const props = withDefaults(defineProps<LjDialogSelectorProps>(), {
  multipleLimit: 1,
  submitText: t("common.table.submit")
  // action: () => []
});

const { CheckPower, funcFilterPower, funcRightActionPower, buttonDefault } = useAuthButtons(t);
const LjSelectorRef = ref();

/**
 * @description 当前活动面板，手风琴
 */
const activeCollapse = ref("");
/*
 * @description 抽屉默认属性
 */
const drawerDefineProp = {
  draggable: true,
  overflow: true,
  width: "60%",
  modalClass: "lj-file-dialog"
};

/**
 * @description flod-layout 默认属性
 */
const layoutDefault: any = {
  first: {
    left: {
      minWidth: "0"
      // minWidth: "20%"
    }
  },
  params: {}
};

const showLayout = props.layout ?? layoutDefault;

/**
 * @description submit 返回数据
 */
const funcSubmit = () => {
  // 回调
  if (props.multipleLimit != 0 && props.value.length > props.multipleLimit) {
    ElMessage.warning(`最多选择${props.multipleLimit}条`);
    return;
  }

  if (!props.value.length) {
    ElMessage.warning(t("business.error.selector.confirmTips"));
    return;
  }

  let result = props.value;

  if (props.beforeSubmit) {
    let res = props.beforeSubmit(props.value);
    if (isBoolean(res)) {
      return;
    } else {
      result = res;
    }
  }

  emits("submit", { action: "submit", value: result });
  // 关闭弹窗
  // props.closed && props.closed();
  LjSelectorRef.value.hide();
  dialogVisible.value = false;
};

/**
 * @description cancel 取消
 */
const funcCancel = () => {
  // 回调
  emits("cancel", { action: "cancel" });
  // 关闭弹窗
  // props.closed && props.closed();
  LjSelectorRef.value.hide();
  dialogVisible.value = false;
};

const btnGroup = ref<any>([]);

const initParams = ref<any>();

const emits = defineEmits(["submit", "cancel", "changeValue", "update:value"]);
const dialogVisible = ref(false);

/**
 * @description 展示组件
 * @param params 入参
 * @param activeName 多选时 活动面板入参
 */
const show = (params: any, activeName?: string, refresh?: boolean) => {
  initParams.value = params;

  activeName && (activeCollapse.value = activeName);

  LjSelectorRef.value.show(refresh);
  nextTick(() => {
    let defaultAction: detailAction[] = [
      buttonDefault({
        label: props.submitText,
        clickFunc: () => funcSubmit()
      }),
      buttonDefault({
        label: t("common.cancelText"),
        clickFunc: () => funcCancel()
      })
    ];
    btnGroup.value = defaultAction.concat(funcFilterPower(props.action));
    dialogVisible.value = true;
  });
};

const changeActiveCollapse = (val: string) => {
  if (props.multipleLimit != 1) {
    activeCollapse.value = val;
  }
};

const handleDelItem = (index: number) => {
  props.value.splice(index, 1);
  emits("changeValue");
};

defineExpose({
  show,
  changeActiveCollapse,
  funcSubmit,
  funcCancel
});
</script>

<style lang="scss">
.lj-selector {
  padding: 0;
  .el-tree {
    background: unset;
  }
}
.ljselector-aside-collapse {
  height: 100%;
  display: flex;
  flex-direction: column;
  // background-color: $color-gray-2;

  .el-collapse-item {
    display: flex;
    flex-direction: column;
    overflow: auto;
    height: auto;

    &.is-active {
      flex: 1;
    }
    &:not(.is-active) {
      flex-shrink: 0;
    }
    .el-collapse-item__header {
      flex-shrink: 0;
    }
    .el-collapse-item__wrap {
      flex: 1;
      overflow: auto;
      background-color: $color-gray-2;
      padding: 8px 4px;

      .lj-infor-item {
        background-color: $color-gray-1;
      }
    }
  }
}
</style>
