<template>
  <LjSelector
    ref="LjSelectorRef"
    :title="$t('business.selector.codeMx.title')"
    v-model:value="selectList"
    v-bind="$attrs"
    :item-key="TABLE_KEY"
    :layout="layout"
    @change-value="autoUpdateTableCheckbox"
  >
    <template #default>
      <LjVxeTable
        ref="vxeTableRef"
        table-cls=""
        :columns="selColumns"
        :request-api="getData"
        :data-callback="dataCallback"
        :init-param="initParams"
        :dwname="dwname"
        pagination
        :search-col="tableSearchCol"
        :table-events="tableEvents"
        :table-props="tableProps"
        :tool-button="['refresh', 'setting', 'search']"
        :auto-load-layout="false"
        collapse-buttons
        :page-change-call-back="autoUpdateTableCheckbox"
      >
        <template #tableHeader>
          <el-input
            v-model="searchInput"
            size="default"
            class="mb-8"
            :prefix-icon="Search"
            clearable
            @input="disshow"
            @clear="() => disshow('')"
            placeholder="配置名称"
          ></el-input>
        </template>
      </LjVxeTable>
    </template>
  </LjSelector>
</template>

<script setup lang="tsx" name="SelectorCodeMx">
import { ref, reactive, inject, nextTick, watch, computed } from "vue";
import { useDesign } from "@/hooks/useDesign";
import { getConfigureCodeMxList } from "@/api/modules/basicinfo";
import LjVxeTable from "@/components/LjVxeTable/index.vue";
import { Search, ColdDrink, QuestionFilled, SwitchButton, ArrowRight } from "@element-plus/icons-vue";
import { ElMessage, ElButton } from "element-plus";
import { useI18n } from "vue-i18n";
import { cloneDeep, pick, defaultsDeep, throttle } from "lodash-es";
// import type { u_mtrldef } from "@/typings/business";
import { dateFormatEnum } from "@/utils/serviceDict";
import dayjs from "dayjs";
import TreeFilter from "@/components/TreeFilter/index.vue";
import LjFoldLayout from "@/components/LjFoldLayout/index.vue";
import CascaderFilter from "@/components/TreeFilter/cascader.vue";
import LjSelector from "@/components/LjSelector/index.vue";
import { ColumnProps } from "@/components/LjVxeTable/interface";
import { CommonDynamicSelect } from "@/api/modules/common";

const { prefixCls } = useDesign("saletask-selector");
const { t } = useI18n();
const dwname = "web_configure_codemxlist_select";
const extraLoading = ref(false);
const drawerVisible = ref(false);
const newDate = dayjs().format("YYYY-MM-DD HH:mm:ss");
const layoutSetting = {};
const selectList = ref([]);
const TABLE_KEY = "pzid";
const layout = { first: { left: { hidden: true } } };
const searchInput = ref("");
const tableSearchCol = { xs: 4, sm: 5, md: 6, lg: 6, xl: 8 };

const vxeTableRef = ref();
const columns: ColumnProps<any>[] = [];
const selColumns: any = computed(() => {
  let selCol: any = { type: "radio", width: 50, fixed: "left" };
  let _columns = cloneDeep(columns);
  _columns.unshift(selCol);
  console.log("_columns :>> ", _columns);
  return _columns;
});
/**
 * @description 鼠标双击表格
 */
const handleDBlClickTable = async ({ row, column, rowIndex }: any) => {
  const $table = vxeTableRef.value.element;
  if ($table) {
    await $table.clearCurrentRow();
    selectList.value = [row];
    $table.setRadioRow(row);

    LjSelectorRef.value.funcSubmit();
  }
};
/**
 * @description 鼠标单击表格
 */
const handleClickTable = ({ row, column, rowIndex }: any) => {
  nextTick(async () => {
    const $table = vxeTableRef.value.element;
    if ($table) {
      await $table.clearCurrentRow();
      selectList.value = [row];
      $table.setRadioRow(row);
    }
  });
};

// 返回绑定的事件
const tableEvents = {
  "cell-dblclick": handleDBlClickTable,
  "cell-click": handleClickTable
};

const dataCallback = (data: any) => {
  console.log("data :>> ", data);
  return {
    list: data.datatable,
    tableinfo: data.tableinfo,
    total: data.totalcnt,
    pageNum: data.pageindex,
    pageSize: data.pagesize
  };
};

const rowClsNameFunc = (data: any) => {
  const { row, rowIndex, $rowIndex } = data;
  return "";
};
/**
 * @description vxetable props
 */
const tableProps = {
  height: "auto",
  columnConfig: { resizable: true, useKey: true },
  checkboxConfig: {
    checkField: "checked",
    trigger: "row",
    highlight: true,
    range: true
  },
  rowClassName: rowClsNameFunc
};

// 节流
const disshow = throttle((val: any) => {
  initParams.value.keyword = val;
}, 500);

const getData = (params: any) => {
  let newParams: any = {};
  params.pageNum && (newParams.pageindex = params.pageNum);
  params.pageSize && (newParams.pagesize = params.pageSize);

  delete params.pageNum;
  delete params.pageSize;
  newParams.queryParams = initParams.value;
  console.log("params :>> ", newParams);
  newParams.dsname = "web_configure_codemxlist";
  return CommonDynamicSelect(newParams, dwname);
};

const autoUpdateTableCheckbox = () => {
  const $table = vxeTableRef.value.element;
  if ($table && selectList.value.length) {
    console.log("autoUpdateTableCheckbox selectLst.value :>> ", selectList.value);
    $table.clearCheckboxRow();
    let _rows: any = [];
    selectList.value.map((item: any) => {
      if ($table.getRowById(item[TABLE_KEY])) {
        _rows.push($table.getRowById(item[TABLE_KEY]));
      }
    });
    _rows.length && $table.setCheckboxRow(_rows, true);
  }
};

const show = (params: any) => {
  selectList.value = [];
  searchInput.value = "";
  initParams.value = defaultsDeep(params, initParams.value);
  LjSelectorRef.value.show(initParams.value);
};

const LjSelectorRef = ref();
const initParams = ref<any>({});

// 确认按钮
const emit = defineEmits(["confirm"]);
const confirm = () => {
  let selectRecords = [];
  const $table = vxeTableRef.value?.element;
  if ($table) {
    selectRecords = $table.getCheckboxRecords();
  }
  if (!selectRecords.length) {
    ElMessage.warning(t("business.error.saletaskmx.confirmTips"));
    return;
  }

  emit("confirm", selectRecords);
  drawerVisible.value = false;
};

defineExpose({
  show
});
</script>
