<template>
  <LjSelector
    ref="LjSelectorRef"
    :title="`${t('business.selector.mtrlprice.title')}`"
    v-model:value="selectList"
    v-bind="$attrs"
    :item-key="TABLE_KEY"
  >
    <!-- @change-value="autoUpdateTableCheckbox" -->
    <!-- <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 #aside>
      <el-collapse-item name="mtrl">
        <template #title>
          {{ $t("common.table.searchBtn") }}
          <el-icon class="ml-4"><Search /></el-icon>
        </template>
        <el-form v-model="initParams" class="pl-4">
          <el-form-item :label="$t('business.selector.saletask.keyword')">
            <template #label>
              <div class="flx-center">
                <span>
                  {{ $t("business.selector.saletask.keyword") }}
                </span>
                <el-tooltip :content="$t('business.selector.saletask.keywordTips')">
                  <el-icon><QuestionFilled /></el-icon>
                </el-tooltip>
              </div>
            </template>
            <el-input
              v-model.trim="initParams.keyword"
              :title="$t('business.selector.saletask.keyword')"
              :placeholder="$t('business.selector.saletask.keywordTips')"
              clearable
              @input="disshow(initParams.keyword)"
            ></el-input>
          </el-form-item>
          <el-form-item :label="$t('table.u_mtrldef.mtrlorigin')">
            <el-select
              v-model="initParams.mtrlorigin"
              clearable
              :placeholder="$t('common.all') + $t('table.u_mtrldef.mtrlorigin')"
              :title="$t('table.u_mtrldef.mtrlorigin')"
              @change="getData"
            >
              <el-option v-for="item in mtrloriginOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('table.u_mtrldef.mtrlprp')">
            <el-select
              v-model="initParams.mtrlprp"
              clearable
              :placeholder="$t('common.all') + $t('table.u_mtrldef.mtrlprp')"
              :title="$t('table.u_mtrldef.mtrlprp')"
              @change="getData"
            >
              <el-option v-for="item in mtrlprpOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('table.u_mtrldef.mtrltype')">
            <!-- <el-cascader :props="mtrlTypeProps" /> -->
            <CascaderFilter
              v-model:value="initParams.mtrltypeid"
              label="text"
              :request-api="getMtrlType"
              filterable
              @change="changeTreeFilter"
            />
          </el-form-item>
        </el-form>
      </el-collapse-item>
    </template>
    <template #default>
      <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="[]"
          pagination
        > -->
        <LjVxeTable
          ref="vxeTableRef"
          table-cls=""
          :columns="columns"
          :request-api="getData"
          :data-callback="dataCallback"
          :init-param="initParams"
          :dwname="dwname"
          pagination
          :table-events="tableEvents"
          :table-props="tableProps"
          :tool-button="[]"
          :auto-load-layout="false"
          collapse-buttons
        >
        </LjVxeTable>
      </div>
    </template>
  </LjSelector>
</template>

<script setup lang="tsx" name="SelectorMtrldef">
import { ref, reactive, inject, nextTick, watch } from "vue";
import { useDesign } from "@/hooks/useDesign";
import { GetERPMtrldefList, GetERPMtrlTypeList } from "@/api/modules/common";
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 { useHooks } from "./hooks/index";
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";

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 TABLE_KEY = "mtrlid";

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

// const tableEvents = {
//   "checkbox-change": handleCheckboxChange,
//   "checkbox-all": handleCheckboxChange,
//   "checkbox-range-change": handleCheckboxChange
// };
/**
 * @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.mtrldefList,
    // 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 selectedLayout = ref<any>({
  icon: "iconmove",
  header: [
    {
      value: "mtrlname",
      // icon: "iconuser-01",
      textClassName: "text-ellipsis-one2"
    },
    {
      value: "mtrlcode",
      // label: "描述",
      icon: "iconcode",
      textClassName: "text-ellipsis-one2"
    }
  ]
  // aside: {
  //   value: "cuscode"
  // }
});

// 全表搜索
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);
  initParams.value.keyword = val;
  // getData();
  // val ? searchEvent() : getData();
}, 500);

// 获取表格数据
// const getData = async () => {
//   try {
//     extraLoading.value = true;
//     const data = await GetERPMtrldefList(initParams.value);
//     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 getData = (params: any) => {
  // console.log("getData params :>> ", params);
  let newParams: any = params;
  params.pageNum && (newParams.pageindex = params.pageNum);
  params.pageSize && (newParams.pagesize = params.pageSize);

  delete params.pageNum;
  delete params.pageSize;
  console.log("GetERPMtrldefList newParams :>> ", newParams);
  // newParams.queryParams = initParams.value;
  // console.log("params :>> ", newParams);
  // newParams.dsname = "web_mtrl_choose";
  return GetERPMtrldefList(newParams);
};

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

  selectList.value = [];

  console.log("show bfff initParams.value :>> ", initParams.value, params);
  // initParams.value = defaultsDeep(params, initParams.value);
  for (const key in params) {
    initParams.value[key] = params[key];
  }

  // initParams.value.pageindex = 1;
  // initParams.value.pagesize = 100;
  console.log("show afff initParams.value :>> ", initParams.value);
  LjSelectorRef.value.show(initParams.value, "mtrl");
  // getData();
};

const LjSelectorRef = ref();
// const initParam = reactive({ mtrltypeid: -1, keyword: "" });
const initParams = ref<any>({});

const { vxeTableRef, columns, mtrloriginOptions, mtrlprpOptions } = useHooks();

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

const LjFoldLayoutRef = ref();

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

const changeTreeFilter = (val: number) => {
  console.log("val :>> ", val);
  initParams.value.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>
