<template>
  <el-dialog
    :title="$t('business.selector.mtrldef.title')"
    :class="`${prefixCls} flx-col`"
    width="80%"
    draggable
    v-model="drawerVisible"
    align-center
    style="height: 80vh"
  >
    <template #header>
      <div class="flx-justify-between">
        <div class="title flx-shrink">
          {{ $t("business.selector.mtrldef.title") }}
        </div>
        <div class="flx-end mr-32">
          <vxe-input
            class="mr-12"
            v-model="filterName"
            type="search"
            placeholder="试试搜索(物料名称\编号\配置)"
            @clear="searchEvent"
            @input="disshow(filterName)"
            clearable
          ></vxe-input>
          <el-button :icon="Refresh" circle @click="getData" />
          <el-button :icon="Operation" circle @click="openColSetting" />
        </div>
      </div>
    </template>
    <template #default>
      <LjFoldLayout ref="LjFoldLayoutRef" v-bind="layoutSetting" :dwname="dwname">
        <template #left>
          <TreeFilter
            id="value"
            label="text"
            :expand-on-click-node="true"
            :request-api="getMtrlType"
            @change="changeTreeFilter"
          />
        </template>
        <div class="main-box flx-col">
          <LjVxeTable
            ref="vxeTableRef"
            :data="list"
            :columns="columns"
            :dwname="dwname"
            table-cls="h-full"
            :table-props="tableProps"
            :request-auto="false"
            :extraLoading="extraLoading"
            :table-events="tableEvents"
            :tool-button="[]"
          >
          </LjVxeTable>
        </div>
      </LjFoldLayout>
    </template>

    <template #footer>
      <div class="flx-justify-between">
        <div class="dialog-footer">
          <el-button @click="drawerVisible = false">{{ $t("common.cancelText") }}</el-button>
          <el-button type="primary" :disabled="!selectList.length" @click="confirm">
            {{ $t("common.okText") }}
            <template v-if="selectList.length">
              {{ `(${selectList.length})` }}
            </template>
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="tsx" name="SelectorMtrldef">
import { ref, reactive, inject, nextTick, watch } from "vue";
import { useDesign } from "@/hooks/useDesign";
import { getMtrldefList } from "@/api/modules/technology";
import LjVxeTable from "@/components/LjVxeTable/index.vue";
import { Refresh, Operation } from "@element-plus/icons-vue";
import { ElMessage, ElButton } from "element-plus";
import { useI18n } from "vue-i18n";
import { throttle } from "lodash-es";
// import type { u_mtrldef } from "@/typings/business";
import { dateFormatEnum } from "@/utils/serviceDict";
import dayjs from "dayjs";
import { useMtrldef } from "@/views/technology/mtrldef/hooks/index";
import TreeFilter from "@/components/TreeFilter/index.vue";
import LjFoldLayout from "@/components/LjFoldLayout/index.vue";
import { getL1MtrlType } from "@/api/modules/technology";

const { prefixCls } = useDesign("saletask-selector");
const { t } = useI18n();
const dwname = "web_crm_mtrldef_sel";
const extraLoading = ref(false);
const drawerVisible = ref(false);
const newDate = dayjs().format("YYYY-MM-DD HH:mm:ss");
const layoutSetting = {};
const selectList = ref([]);

const handleCheckboxChange = (data: any) => {
  selectList.value = data.records;
};

const tableEvents = {
  "checkbox-change": handleCheckboxChange,
  "checkbox-all": handleCheckboxChange,
  "checkbox-range-change": handleCheckboxChange
};

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

// 全表搜索
let tableData = ref<any[]>([]);
const list = ref<any>([]);
const filterName = ref("");
const searchField = ref("");
const searchEvent = () => {
  const filterVal = String(searchField.value).trim().toLowerCase();
  if (filterVal) {
    const filterRE = new RegExp(filterVal, "gi");
    const searchProps = ["mtrlcode", "mtrlname"];
    const rest = tableData.value.filter(item => searchProps.some(key => String(item[key]).toLowerCase().indexOf(filterVal) > -1));
    list.value = rest.map(row => {
      const item = Object.assign({}, row);
      searchProps.forEach(key => {
        item[key] = String(item[key]).replace(filterRE, match => `<span class="keyword-lighten">${match}</span>`);
      });
      return item;
    });
  } else {
    list.value = tableData.value;
  }
};
// 节流
const disshow = throttle((val: any) => {
  console.log("val :>> ", val);
  searchField.value = val;
  searchEvent();
}, 500);

// 获取表格数据
const getData = async () => {
  try {
    extraLoading.value = true;
    const data = await getMtrldefList(initParam);
    console.log("getData data :>> ", data);
    if (data?.mtrldefList) {
      let list = Object.freeze<any>(data.mtrldefList);
      tableData.value = list;
    }
    extraLoading.value = false;
    searchEvent();
  } catch (error) {
    extraLoading.value = false;
    console.error(error);
  }
};

const show = (params: any) => {
  drawerVisible.value = true;
  !tableData.value?.length && getData();
};

const initParam = reactive({ mtrltypeid: -1 });

const { vxeTableRef, columns } = useMtrldef(t);

const openColSetting = () => {
  vxeTableRef.value?.openColSetting();
};

const LjFoldLayoutRef = ref();

const getMtrlType = async () => {
  const data = await getL1MtrlType({ RecurionType: 1 });
  console.log("getL1MtrlType data :>> ", data);
  return data.RecurionList;
};

const changeTreeFilter = (val: number) => {
  console.log("val :>> ", val);
  initParam.mtrltypeid = val;
  getData();
};

// 确认按钮
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>

<style lang="scss">
$prefix-cls: "#{$namespace}-saletask-selector";

.#{$prefix-cls} {
  .el-dialog__body {
    flex: 1;
  }
  .footer-tips {
    .tips-item {
      span {
        margin-right: $space-a1;
        display: inline-block;
        width: $space-a2;
        height: $space-a2;
        border-radius: $br-xs;
        border: 2px solid $color-gray-1;
        box-shadow: $shadow-1-down;

        &.purple {
          background-color: var(--lj-color-golden-purple-6);
        }
        &.danger {
          background-color: var(--lj-color-dust-red-2);
        }
      }
      & + .tips-item {
        margin-left: $space-b4;
      }
    }
  }
}
</style>
