<template>
  <LjSelector
    ref="LjSelectorRef"
    :title="`${t('business.selector.mtrlprice.title')}`"
    v-model:value="selectList"
    v-bind="$attrs"
    :item-key="TABLE_KEY"
  >
    <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')">
            <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"
          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="SelectorErpMtrlPrice">
import { ref, reactive, inject, nextTick, watch } from "vue";
import { useDesign } from "@/hooks/useDesign";
import { GetERPMtrlPriceList, 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 dayjs from "dayjs";
import { useHooks } from "./hooks/index";
import CascaderFilter from "@/components/TreeFilter/cascader.vue";
import LjSelector from "@/components/LjSelector/index.vue";
import { transformTreeData, traverseNode } from "@/utils/index";
import { throttle } from "lodash-es";

const { prefixCls } = useDesign("saletask-selector");
const { t } = useI18n();
const dwname = "web_erpmtrl_price_sel";
const drawerVisible = ref(false);
const selectList = ref([]);
const TABLE_KEY = "mtrlid";

/**
 * @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
};

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

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

  delete params.pageNum;
  delete params.pageSize;
  return GetERPMtrlPriceList(newParams);
};

const show = (params: any) => {
  selectList.value = [];
  for (const key in params) {
    initParams.value[key] = params[key];
  }

  LjSelectorRef.value.show(initParams.value, "mtrl");
};

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

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

const getMtrlType = async () => {
  const data = await GetERPMtrlTypeList();
  let arr = data.reList;
  arr.unshift({
    value: -1,
    text: "全部",
    data: {
      mtrltypeid: -1,
      mtrltype: "全部",
      inuse: 1,
      parentid: 0
    }
  });
  return transformTreeData(data.reList);
};

const changeTreeFilter = (val: any) => {
  console.log("val :>> ", val);
  // initParams.value.mtrltypeid = val.mtrltypeid;
  let mtrltypeids = [] as Number[];
  traverseNode(val, (node: any) => node?.mtrltypeid >= 0 && mtrltypeids.push(parseInt(node.mtrltypeid)));
  initParams.value.mtrltypeids = mtrltypeids.length > 0 ? mtrltypeids : undefined;
};

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