<template>
  <LjSelector
    ref="LjSelectorRef"
    :title="$t('business.selector.cust.title')"
    v-model:value="selectList"
    :action="action"
    v-bind="$attrs"
    :item-layout="selectedLayout"
    item-key="cusid"
    @change-value="autoUpdateTableCheckbox"
  >
    <!-- :multipleLimit="3" -->
    <template #aside>
      <el-collapse-item title="物料分类" name="mtrl">
        <TreeFilter
          id="value"
          label="text"
          wrapper-cls=""
          :expand-on-click-node="true"
          :request-api="getCusarea"
          @change="changeTreeFilter"
        />
      </el-collapse-item>
    </template>
    <template #default>
      <LjVxeTable
        ref="LjTableRef"
        row-key="cusid"
        :columns="selColumns"
        :request-api="getData"
        :data-callback="dataCallback"
        :init-param="initParams"
        :dwname="DwnameEnum.custCrm"
        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"
      >
      </LjVxeTable>
    </template>
  </LjSelector>
</template>

<script lang="tsx" setup name="SelectorCustDialog">
import { reactive, toRefs, ref, onMounted, nextTick, inject, watch, computed } from "vue";
// import LjDialog from "@/components/LjDialog/index.vue";
// import LjFoldLayoutDouble from "@/components/LjFoldLayoutDouble/index.vue";
import LjVxeTable from "@/components/LjVxeTable/index.vue";
// 注意: 需要按需引入使用到的第三方UI组件
// import { ElDialog, ElButton } from "element-plus";

import { getL1Cusarea } from "@/api/modules/saletask";
import TreeFilter from "@/components/TreeFilter/index.vue";
// import { useCust } from "@/views/saletask/cust/hooks/index";
import { useI18n } from "vue-i18n";
import { DwnameEnum } from "@/enums/dwnameEnum";
import { cloneDeep, pick, defaultsDeep } from "lodash-es";
import { CommonDynamicSelect } from "@/api/modules/common";
// import LjHeaderMenu from "@/components/LjHeaderMenu/index.vue";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { detailAction } from "@/components/LjDetail/interface";

import LjSelector from "@/components/LjSelector/index.vue";
// import variables from "@/styles/js.module.scss";

// const props = withDefaults(defineProps<{}>(), {});

const { t } = useI18n();
// const { columns } = useCust(t);
const columns = {};
const selColumns: any = computed(() => {
  // let selCol: any = { type: "checkbox", width: 50, fixed: "left" };
  let selCol: any = { type: "radio", width: 50, fixed: "left" };
  let _columns = cloneDeep(columns);
  // console.log(" _columns.unshift(selCol); :>> ", _columns.unshift(selCol));
  _columns.unshift(selCol);
  console.log("_columns :>> ", _columns);
  return _columns;
});

/**
 * @description 已选列表
 */
const selectList = ref<any>([]);

const LjSelectorRef = ref();
const LjTableRef = ref();
// const _variables: any = variables;
const { CheckPower, CheckOption, buttonNew, buttonDefault } = useAuthButtons(t);

const initParams = ref({ cusareaid: -1, cusareaidarry: [] });
const tableSearchCol = { xs: 4, sm: 5, md: 6, lg: 6, xl: 8 };
const tableProps = {
  height: "auto",
  editConfig: { trigger: "click", mode: "cell" },
  rowConfig: { isCurrent: true, isHover: true, useKey: true, keyField: "cusid" }
};

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

/**
 * @description 鼠标双击表格
 */
const handleDBlClickTable = async ({ row, column, rowIndex }: any) => {
  const $table = LjTableRef.value.element;
  if ($table) {
    selectList.value = [row];
    $table.setRadioRow(row);

    LjSelectorRef.value.funcSubmit();
  }
};

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

/**
 * @description 修改时，按钮展示
 */
const action: detailAction[] = [
  // buttonDefault({
  //   label: t("common.cancelText"),
  //   icon: "iconchevron-left",
  //   clickFunc: item => {
  //     // if (route.path.indexOf("/new") > -1) {
  //     //   tabRemove(route.fullPath);
  //     //   router.replace("/saletask/sale/saletaskCrm");
  //     // } else {
  //     //   router.replace(
  //     //     `/saletask/sale/saletaskCrm/detail?scid=${LjDetailRef.value._mainData.scid}&taskid=${LjDetailRef.value._mainData.taskid}&code=${LjDetailRef.value._mainData.taskcode}`
  //     //   );
  //     // }
  //   }
  // }),
  // buttonDefault({
  //   label: t("common.saveText"),
  //   icon: "iconsave-01",
  //   path: "/saletask/sale/saletaskCrm/new"
  // })
];

const selectedLayout = ref<any>({
  icon: "iconmove",
  header: [
    {
      value: "name",
      // icon: "iconuser-01",
      textClassName: "text-ellipsis-one2"
    },
    {
      value: "cuscode",
      // label: "描述",
      icon: "iconcode",
      textClassName: "text-ellipsis-one2"
    }
  ]
  // aside: {
  //   value: "cuscode"
  // }
});

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 getData = (params: any) => {
  console.log("getData params :>> ", params);
  let newParams: any = {};
  params.pageNum && (newParams.pageindex = params.pageNum);
  params.pageSize && (newParams.pagesize = params.pageSize);
  // // inusescid = 0;
  // params.quoteid = params.lastOutware[0];
  // params.inuse = 4;
  // params.cusareaid = [1, 2, 3];

  // params.cusareaidarry = [23];
  delete params.lastOutware;
  delete params.pageNum;
  delete params.pageSize;
  newParams.queryParams = params;
  console.log("params :>> ", params);
  newParams.dsname = "web_cust_crm_index";

  return CommonDynamicSelect(newParams, DwnameEnum.custCrm);
};

const getCusarea = async () => {
  const data = await getL1Cusarea({ RecurionType: 1 });
  return data.RecurionList;
};

const getChildNode = (nodes: any) => {
  let arr: any = [];
  nodes.value && arr.push(nodes.value);
  if (nodes.children) {
    console.log("nodes.children :>> ", nodes.children);
    nodes.children.map((item: any) => {
      if (item.children) {
        let arr1 = getChildNode(item);
        arr = arr.concat(arr1);
      } else {
        arr.push(item.value);
      }
    });
  }
  return arr;
};

const changeTreeFilter = (val: any) => {
  console.log("val :>> ", val);
  // alert(getCheckedNodes());
  //proTable.value!.pageable.pageNum = 1;
  // cusareaid.value = val.children ?? [];
  initParams.value.cusareaid = val.value ?? -1;
  // 访问当前选中节点的下级节点数值
  initParams.value.cusareaidarry = getChildNode(val);
  // childrenValues.value.push(val.value);
  console.log("val :>>Children Values:", initParams.value);
};

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

/**
 * @description 打开组件
 * @param params 入参
 */
const show = (params: any) => {
  selectList.value = [];
  initParams.value = defaultsDeep(params, initParams.value);
  LjSelectorRef.value.show(initParams.value, "mtrl");
};

defineExpose({
  show
});
</script>
