<template>
  <LjDrawer
    v-if="visible"
    ref="LjDrawerRef"
    :class="`${prefixCls}`"
    :id="prefixCls"
    direction="rtl"
    size="50%"
    destroy-on-close
    append-to-body
    :show-close="false"
    @close="autoClose"
  >
    <template #header>
      <div class="flx-justify-between">
        <div class="">
          {{ `${$t("sys.setting.displayColumn")}(${isVisibleCols.length}/${oriList.length})` }}
        </div>
        <div class="flx flx-center mr-4" id="settingSearchInput">
          <el-input
            v-model="searchField"
            :prefix-icon="Search"
            clearable
            style="width: 240px; height: 34px"
            :placeholder="$t('business.baseMsgSetting.searchPh')"
            @clear="searchEvent"
            @input="disshow(searchField)"
          >
            <template #suffix v-if="searchField.length">
              {{ matchSearchNum }}
            </template>
          </el-input>
          <el-tooltip effect="dark" :content="$t('common.table.sesarhFilter')" placement="top" :show-after="200">
            <el-button
              :type="ifSearchFilter ? 'primary' : 'default'"
              plain
              class="ml-8 pl-10 pr-10"
              @click="
                () => {
                  ifSearchFilter = !ifSearchFilter;
                  disshow(searchField);
                }
              "
            >
              <template #icon>
                <i class="iconfont" :class="ifSearchFilter ? 'iconfilter-funnel-01-fill' : 'iconfilter-funnel-01'"></i>
              </template>
            </el-button>
          </el-tooltip>
        </div>
        <div class="flx-shrink">
          <el-button type="danger" :icon="Close" text circle @click="cancelClick"></el-button>
        </div>
      </div>
    </template>
    <template #default>
      <el-container :class="`${prefixCls}__body`" class="h-full">
        <el-main :class="`${prefixCls}__main`" class="h-full">
          <!-- <el-row :gutter="16" class="h-full">
            <el-col :span="18" class="h-full"> -->
          <!-- <div class="flx-2 pl-8 pr-8 affix-container h-full"> -->
          <div class="flx-col h-full overflow-hidden">
            <!-- <LjHeader
                :class="`${prefixCls}__main-header flx-shrink`"
                :title="`${$t('sys.setting.displayColumn')}(${isVisibleCols.length}/${oriList.length})`"
              >
                <template #toolButton>
                  <div class="flx flx-center mr-4">
                    <el-input
                      v-model="searchField"
                      :prefix-icon="Search"
                      clearable
                      style="width: 240px"
                      @clear="searchEvent"
                      @input="disshow(searchField)"
                    >
                      <template #suffix v-if="searchField.length">
                        {{ matchSearchNum }}
                      </template>
                    </el-input>
                    <el-tooltip effect="dark" :content="$t('common.table.sesarhFilter')" placement="top" :show-after="200">
                      <el-button
                        :type="ifSearchFilter ? 'primary' : 'default'"
                        plain
                        class="ml-8"
                        @click="
                          () => {
                            ifSearchFilter = !ifSearchFilter;
                            disshow(searchField);
                          }
                        "
                      >
                        <template #icon>
                          <i class="iconfont" :class="ifSearchFilter ? 'iconfilter-funnel-01-fill' : 'iconfilter-funnel-01'"></i>
                        </template>
                      </el-button>
                    </el-tooltip>
                  </div>
                </template>
              </LjHeader> -->

            <el-row class="flx-1 overflow-auto">
              <el-col>
                <table class="lj-table w-full user-sel-none">
                  <thead class="thead-dark">
                    <tr>
                      <!-- <th style="width: 20px"></th> -->
                      <th class="flx-justify-between">
                        <span>
                          <el-checkbox v-model="ifAllSelect" @click.stop @change="handleSelectAllCol">
                            {{ $t("common.table.col") }}
                          </el-checkbox>
                        </span>
                        <span>
                          {{ $t("common.table.newGroup") }}
                        </span>
                      </th>
                      <th style="width: 30%">{{ $t("common.table.field") }}</th>
                      <th>{{ $t("common.table.table") }}</th>
                      <!-- <th style="width: 85px !important">{{ $t("common.table.hideColumn") }}</th> -->
                    </tr>
                  </thead>
                  <tbody>
                    <!-- @click="handleSelectCol(element, !element.ifSelect)" -->
                    <tr
                      v-for="element in list"
                      :key="element.field"
                      :class="{
                        'main_table-tr': true,
                        'columns-select-item': true,
                        'is-notvisible': !element.visible
                      }"
                      :data-field="element.field"
                    >
                      <td>
                        <div class="flx-justify-between">
                          <!-- <el-checkbox v-model="element.ifSelect"
                            @click.stop
                            @change="(val: any) => handleSelectCol(element, val)"
                            >
                              <span v-html="element?.title_html || element.title"></span>
                            </el-checkbox> -->
                          <div>
                            <i
                              class="iconfont mr-4 checkbox-icon"
                              :class="element.ifSelect ? 'iconcheck-square-fill is-checked' : 'iconsquare'"
                            ></i>
                            <span v-html="element?.title_html || element.title"></span>
                          </div>
                          <div class="col-more-tag">
                            <el-tag
                              v-if="element.basicinfo?.visible !== false"
                              :type="element.basicinfo?.group ? '' : 'info'"
                              effect="plain"
                              round
                              size="small"
                              class="group-tag"
                              disable-transitions
                            >
                              {{
                                element.basicinfo?.group ? htmlDecodeByRegExp(element.basicinfo?.group) : $t("common.notGrouped")
                              }}
                            </el-tag>
                          </div>
                        </div>
                      </td>
                      <td>
                        <div class="flx-justify-between">
                          <span v-html="element?.field_html || element.field"></span>
                          <el-tag v-if="element.datatype" size="small" disable-transitions :title="$t('common.table.dataType')">{{
                            $t(`common.table.${fnGetType(element)}`)
                          }}</el-tag>
                        </div>
                      </td>
                      <td>{{ element.table }}</td>
                    </tr>
                  </tbody>
                </table>
                <template v-if="!list.length">
                  <el-empty description="暂无匹配数据列" />
                </template>
              </el-col>
            </el-row>
          </div>
          <!-- </div> -->
        </el-main>
      </el-container>
    </template>
    <template #footer>
      <div class="flx-justify-between">
        <div class="flx-start flx-1 pr-20">
          <el-checkbox v-model="ifAllSelect" @click.stop @change="handleSelectAllCol">
            {{ $t("common.table.selectAll") }}
          </el-checkbox>
        </div>
        <div class="flx-shrink">
          <span class="flx-shrink">{{
            `${$t("common.selected")}(${selectColumn.length})， ${$t("common.table.basicinfo.toAddGroup")}：`
          }}</span>
          <el-select
            v-model.trim="selectGroup"
            filterable
            clearable
            allow-create
            default-first-option
            :reserve-keyword="false"
            :placeholder="$t('common.notGrouped')"
            class="mr-16"
            style="width: 140px"
          >
            <el-option v-for="item in groupList" :key="item" :label="item" :value="item" />
          </el-select>
          <el-button
            type="primary"
            :loading="confirmBtnLoading"
            :disabled="!selectColumn.length || confirmBtnLoading"
            @click="confirmClick"
            >{{ $t("common.okText") }}</el-button
          >
          <el-button @click="cancelClick">{{ $t("common.cancelText") }}</el-button>
        </div>
      </div>
    </template>
  </LjDrawer>
</template>

<script setup lang="ts" name="LjDetailBaseFormBasicInfoSelect">
import { ref, computed, watch, nextTick } from "vue";
// import Grid from "@/components/Grid/index.vue";
// import GridItem from "@/components/Grid/components/GridItem.vue";
// import { BreakPoint } from "@/components/Grid/interface";
import { ColumnProps } from "@/components/LjVxeTable/interface";
// import draggable from "vuedraggable";
import { useDesign } from "@/hooks/useDesign";
import { useGlobalStore } from "@/stores/modules/global";
import { storeToRefs } from "pinia";
import { htmlEncodeByRegExp, htmlDecodeByRegExp } from "@/utils";
// import LjHeader from "@/components/LjHeader/index.vue";
// import CellGroup from "@/components/CellGroup/index.vue";
// import ColAside from "./ColAside.vue";
import {
  // Plus,
  // Minus,
  // QuestionFilled,
  Close,
  // MoreFilled,
  // Refresh,
  // Location,
  Search
  // View,
  // Hide,
  // Guide
} from "@element-plus/icons-vue";
// import { ElMessage, ElNotification, type TabsPaneContext } from "element-plus";
import { useI18n } from "vue-i18n";
import { cloneDeep, throttle, defaultsDeep } from "lodash-es";
import { useUserStore } from "@/stores/modules/user";
import LjDrawer from "@/components/LjDrawer/index.vue";
import { TourEnum } from "@/enums/tourEnum";
import { useTour } from "@/hooks/useTour";
import { classNameIncludes } from "@/utils/index";

const { t } = useI18n();
const { prefixCls } = useDesign("detail-basicinfo-select");
const globalStore = useGlobalStore();
const { userInfo } = useUserStore();
const { globalAlign, globalLabelWidth } = storeToRefs(globalStore);
/**
 * @description 滚动模式
 */
// const scrollY = ref<scrollYProps>({});
const buttonRef = ref();
const LjDrawerRef = ref();
const LjDrawerAsideRef = ref();
const scrollTooltipsContent = ref();
const visible = ref(false);
// const inputVisible = ref(false);
// const inputValue = ref();
const ifAllSelect = ref(false);

/**
 * @description 当前列索引
 */
const currentIndex = ref(0);
const scrollMoveoverTooltips = (e: any) => {
  buttonRef.value = e.currentTarget;
  scrollTooltipsContent.value = e.currentTarget.getAttribute("data-content");
};

const emit = defineEmits(["confirm"]);

interface ProTableProps {
  title?: string;
  // data?: ColumnProps[]; // 数据列
  // /**
  //  * @description 数据列原型, 用于重置列排序等数据
  //  */
  // prototype?: ColumnProps[];
  searchParam?: { [key: string]: any }; // 搜索参数
  enumMap?: Map<string, { [key: string]: any }[]>;
  // scrollYDefault?: any;
  // updateColumns: Function;
  // search: (params: any) => void; // 搜索方法
  // reset: (params: any) => void; // 重置方法
}

interface BaseMseSettingColumns {
  prop: string;
  label: string;
  table: string;
  // search: SearchProps | undefined; // 搜索项配置
  span: number;
  lableWidth: number;
  // invisible: false,
}

// 默认值
const props = withDefaults(defineProps<ProTableProps>(), {
  // data: () => [],
  // prototype: () => [],
  searchParam: () => ({})
});

const groupList = ref<string[]>([]);

/**
 * @description 已选数据列
 */
const selectColumn = ref<string[]>([]);
const selectGroup = ref("");

const handleSelectCol = (element: any, value: any) => {
  element.ifSelect = value;

  let _idx = selectColumn.value.indexOf(element.field);
  if (_idx > -1) {
    selectColumn.value.splice(_idx, 1);
  } else {
    selectColumn.value.push(element.field);
  }
};

/**
 * @description 全选/取消全选
 */
const handleSelectAllCol = (value: any) => {
  // if (value) {
  //   list.value.map((item: any) => {
  //     item.ifSelect = true;

  //     let _idx = selectColumn.value.indexOf(item.field);
  //     if (_idx == -1) {
  //       selectColumn.value.push(item.field);
  //     }
  //   });
  // } else {
  //   list.value.map((item: any) => {
  //     item.ifSelect = false;

  //     let _idx = selectColumn.value.indexOf(item.field);
  //     if (_idx > -1) {
  //       selectColumn.value.splice(_idx, 1);
  //     }
  //   });
  // }
  let addNodes: any = [];

  if (!value) {
    list.value.map((item: any) => {
      let oDiv = document.querySelector(`.${prefixCls} tr[data-field="${item.field}"]`);
      console.log("oDiv :>> ", oDiv);
      addNodes.push(oDiv);
    });
    columnsDrag.value.removeSelection(addNodes, true);
  } else {
    list.value.map((item: any) => {
      let hasIdx = selectColumn.value.indexOf(item.field);
      if (hasIdx == -1) {
        selectColumn.value.push(item.field);
        let oDiv = document.querySelector(`.${prefixCls} tr[data-field="${item.field}"]`);
        addNodes.push(oDiv);
      }
    });
    columnsDrag.value.addSelection(addNodes, true);
  }
};

// /**
//  * @description 指引步骤
//  */
// const TourSteps = computed(() => {
//   let arr = [
//     {
//       element: `.${prefixCls}__main .main_table-tr:nth-child(${currentIndex.value + 1}) td:nth-child(1)`,
//       popover: {
//         title: t("business.guide.tableSetting.step2.title"),
//         description: t("business.guide.tableSetting.step2.description"),
//         side: "bottom"
//       }
//     },
//     {
//       element: `.${prefixCls}__main .main_table-tr:nth-child(${currentIndex.value + 1})`,
//       popover: {
//         title: t("business.guide.tableSetting.step3.title"),
//         description: t("business.guide.tableSetting.step3.description"),
//         side: "bottom"
//       }
//     }
//   ];
//   if (userInfo.usercode?.trim().toLocaleLowerCase() == "super") {
//     arr.push({
//       element: "#settingBtnSetDefault",
//       popover: {
//         title: t("business.guide.tableSetting.step4.title"),
//         description: t("business.guide.tableSetting.step4.description"),
//         side: "top"
//       }
//     });
//   }
//   arr.push({
//     element: "#settingBtnReset",
//     popover: {
//       title: t("business.guide.tableSetting.step5.title"),
//       description: t("business.guide.tableSetting.step5.description"),
//       side: "top"
//     }
//   });
//   return arr;
// });

// // 新手指导
// const { checkIfNeedGuide } = useTour(t, TourEnum.tableSetting, TourSteps.value);

const cancelClick = () => {
  searchField.value = "";
  LjDrawerRef.value.hide();
  selectColumn.value = [];
  ifAllSelect.value = false;
};
const confirmBtnLoading = ref(false);

/**
 * @description 点击保存
 */
const confirmClick = () => {
  confirmBtnLoading.value = true;
  setTimeout(() => {
    emit("confirm", selectColumn.value, selectGroup.value, () => {
      confirmBtnLoading.value = false;
      cancelClick();
    });
  }, 1);
};

/**
 * @description 显示组件
 */
const open = (params: any, group: string) => {
  visible.value = true;
  console.log("params :>> ", params);
  // data.value = params

  nextTick(() => {
    list.value = cloneDeep(params);
    oriList.value = cloneDeep(params);

    let arr: string[] = [];
    params.map((item: any) => {
      if (item.basicinfo && item.basicinfo.hasOwnProperty("group")) {
        item.basicinfo.group && !arr.includes(item.basicinfo.group) && arr.push(item.basicinfo.group);
      }
    });
    groupList.value = arr;

    selectGroup.value = group;

    LjDrawerRef.value.show();
    console.log("open columnsDrag.value :>> ", columnsDrag.value);

    nextTick(() => {
      initDragSelect();
    });
  });
};

// let activeColumn = ref<any>({});
// /**
//  * @description 更新当前列的配置信息至缓存数组
//  */
// watch(
//   () => activeColumn.value,
//   newVal => {
//     console.log("activeColumn.value newVal :>> ", newVal);

//     let _idx = oriList.value.findIndex(item => item.field === newVal.field);
//     if (_idx > -1) {
//       oriList.value[_idx] = newVal;
//     }
//   },
//   {
//     deep: true
//   }
// );
// let activeBaseColMsg = ref<any>({});
// const rightAsignActive = ref("style");
// const handleSelFormItem = (item: any, index: number) => {
//   let breakPoint = LjDrawerRef.value.breakPoint;

//   if (["sm", "md"].includes(breakPoint)) {
//     LjDrawerAsideRef.value.show();
//   }
//   activeColumn.value = item;
//   currentIndex.value = index;
//   rightAsignActive.value = "style";
//   console.log("item :>> ", item);
//   // activeBaseColMsg.value = getBaseCol(item) ?? {};
// };

// 全局设置
// let _globalAlign: any = globalAlign;
// const handeChange = (arg: any, name: string) => {
//   console.log("name :>> ", name);
//   console.log("arg :>> ", arg);
// };

// // 全局设置
// let _globalLabelWidth: any = globalLabelWidth;

// 样式
// inject("updateSettingColumn", )
// const handeChangeStyle: any = inject("updateSettingColumn");

// 判断数据类型
const fnGetType = (item: ColumnProps) => {
  return item?.datatype ?? (item?.field && item.field?.indexOf("date") > -1 ? "date" : "string");
};

/**
 * @description 重置列排序等数据
 */
const resetBtnLoading = ref(false);

/**
 * @description 重置列排序等数据
 */
const saveDfBtnLoading = ref(false);

const searchField = ref("");
/**
 * @description 是否过滤筛选结果
 */
const ifSearchFilter = ref(false);
const matchSearchNum = ref();
const toScrollCol = (item: any) => {
  console.log("toScrollCol item :>> ", item);
  cancelClick();
  // nextTick(() => {
  //   emit("toScrollCol", item);
  // });
};

/**
 * @description 当前编辑数据源（包括搜索）
 */
const list = ref<any[]>([]);
/**
 * @description 暂存数据源
 */
const oriList = ref<ColumnProps[]>([]);
const searchEvent = () => {
  matchSearchNum.value = 0;
  const filterVal = String(searchField.value).trim().toLowerCase();
  if (filterVal) {
    const filterRE = new RegExp(filterVal, "gi");
    const searchProps = ["field", "title", "table"];
    if (ifSearchFilter.value) {
      const rest = oriList.value.filter((item: any) =>
        searchProps.some(key => String(item[key]).toLowerCase().indexOf(filterVal) > -1)
      );
      matchSearchNum.value = rest.length;
      list.value = rest.map(row => {
        const item: any = Object.assign({}, row);
        searchProps.forEach(key => {
          item[key + "_html"] = String(item[key]).replace(filterRE, match => `<span class="keyword-lighten">${match}</span>`);
        });
        return item;
      });
    } else {
      list.value = oriList.value.map(row => {
        const item: any = Object.assign({}, row);
        if (searchProps.some(key => String(item[key]).toLowerCase().indexOf(filterVal) > -1)) {
          matchSearchNum.value++;
          searchProps.forEach(key => {
            item[key + "_html"] = String(item[key]).replace(filterRE, match => `<span class="keyword-lighten">${match}</span>`);
          });
        }
        return item;
      });
    }
  } else {
    // table 排列
    list.value = cloneDeep(oriList.value);
  }
  list.value.forEach((item: any) => {
    item.ifSelect = selectColumn.value.includes(item.field);
  });
};
// 节流
const disshow = throttle((val: any) => {
  searchEvent();
}, 500);

// const handleDragUpdate = (data: any) => {
//   // 每次排序都更新暂存数组
//   oriList.value = cloneDeep(list.value);
// };

/**
 * @description 按钮: 控制显隐
 * @param item
 */
// const handleSwitchVisible = (item: any) => {
//   console.log("handleSwitchVisible item :>> ", item);
//   let _idx = oriList.value.findIndex(itm => itm.field === item.field);
//   oriList.value[_idx].visible = item.visible;
// };

const isVisibleCols = computed(() => {
  return oriList.value.filter(item => item?.basicinfo?.visible !== false);
});

declare let DragSelect: any;
const columnsDrag = ref<any>(null);

/**
 * @description 拖拽选择时，阻止默认事件的类名列表
 */
const classNamesToCheck = [
  "group_handle", // 分组拖拽按钮
  "setting-grid-item",
  // "el-input__inner", // 搜索输入框
  "hidden-btn", // 字段隐藏按钮
  "select-match", // 搜索输入框,
  "el-drawer__footer" // 底部控制栏
];
/**
 * @description 初始化拖拽
 */
const initDragSelect = () => {
  // settingFooterRef.value?.updateRoot();
  columnsDrag.value && columnsDrag.value.stop();
  columnsDrag.value = null;
  columnsDrag.value = new DragSelect({
    selectables: document.getElementsByClassName("columns-select-item"),
    area: document.getElementById(prefixCls),
    selectedClass: "to-dragselect",
    multiSelectMode: true,
    onDragStart: (element: any) => {
      console.log(element.target);
      console.log(element.target.parentNode);
      console.log(element.target.parentNode.parentNode);
      if (element && element.target) {
        let includesResult = classNameIncludes(element.target, classNamesToCheck);
        console.log("element.target.className :>> ", element.target.className);
        console.log("element.target. includesResult :>> ", includesResult);
        if (includesResult) {
          columnsDrag.value.break();
        }
      }
      // console.log("onDragStart selectColumn.value :>> ", JSON.stringify(selectColumn.value), drag.value.getSelection());
    },
    // onElementSelect(el: any) {
    //   console.log("onElementSelect el :>> ", el);
    // },
    // onElementUnselect(el: any) {
    //   console.log("onElementUnselect el :>> ", el);
    // },
    callback: (arr: any) => {
      //鼠标抬起后返回所有选中的元素
      console.log("callback arr :>> ", arr);
      selectColumn.value = [];

      arr.forEach((item: any) => {
        let _field = item.getAttribute("data-field");
        selectColumn.value.push(_field);
      });

      nextTick(() => {
        list.value.forEach((item: any) => {
          item.ifSelect = selectColumn.value.includes(item.field);
        });
      });

      console.log("selectColumn.value: >>", selectColumn.value);
    }
  });
  console.log("initDragSelect columnsDrag.value :>> ", columnsDrag.value);
};

const autoClose = () => {
  columnsDrag.value && columnsDrag.value.stop();
  columnsDrag.value = null;
  cancelClick();

  setTimeout(() => {
    visible.value = false;
  }, 200);
};

defineExpose({
  open
});
</script>

<style lang="scss">
$prefix-cls: "#{$namespace}-detail-basicinfo-select";
.#{$prefix-cls} {
  .el-drawer__body {
    padding: 0 !important;
  }
}
</style>

<style lang="scss" scoped>
$prefix-cls: "#{$namespace}-detail-basicinfo-select";

.#{$prefix-cls} {
  &__menu {
    background-color: unset !important;
    padding: $space-a2 $space-b2;
    width: 256px !important;
  }
  &__main {
    padding: 0;
    overflow: hidden;
    .card {
      padding: $space-a2 $space-b2;
    }
    .#{$prefix-cls}__grid-item {
      cursor: pointer;
      // .el-form-item {
      position: relative;
      &::before {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        // left: -10px;
        // right: -10px;
        border: 2px dashed $color-primary-100;
        border-radius: $br-sm;
      }
      // }
      &.is-active::before,
      &:hover::before {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        // left: -10px;
        // right: -10px;
        border: 2px solid $color-primary-400;
        border-radius: $br-sm;
      }
      &.is-active {
        position: relative;
        // background-color: $color-primary-200 !important;
      }
      &:not(.is-active):hover::before {
        border-style: dashed;
        border-color: $color-primary-500;
      }
      :deep(.el-scrollbar__view) {
        overflow-x: hidden;
      }
      .right-btn {
        position: absolute;
        top: 0;
        right: 0;
        transform: translate(50%, -50%);
        transition: all 0.2s ease-in-out;
      }
      &:not(.more) .right-btn {
        opacity: 0;
      }
      &:hover {
        .right-btn {
          opacity: 1;
        }
      }
    }

    :deep(.el-scrollbar__view) {
      display: flex;
      flex-direction: column;
      height: 100%;
    }
    .drag-list {
      min-height: 80px;
      padding: 0 16px;
    }
    .col-more-tag {
      .el-tag {
        // margin-top: 2px;
        & + .el-tag {
          margin-left: 4px;
        }
      }
    }
    &-header {
      background-color: $color-gray-1;
    }
  }
  &__aside-menu {
    background-color: $color-gray-2;
    overflow: hidden;
    width: 360px;

    :deep(.el-tabs__content) {
      // height: 100%;
      flex: 1;
    }
    &.absolute {
      position: absolute;
      right: 0;
    }
  }
}

.group-tag:not(.el-tag--info),
.el-check-tag.is-checked {
  color: $color-geek-blue-5 !important;
  border-color: $color-geek-blue-3 !important;
  background-color: $color-geek-blue-1 !important;
}
.checkbox-icon {
  color: $color-gray-5;
  &.is-checked {
    color: $color-primary-500;
  }
}

.columns-select-item {
  cursor: pointer;
}
</style>
