<template>
  <el-dialog
    :class="`${prefixCls}`"
    width="60%"
    draggable
    v-model="drawerVisible"
    align-center
    :modal="false"
    append-to-body
    destroy-on-close
    @closed="onClosed"
    :z-index="1000"
  >
    <template #header>
      <div class="flx-justify-between">
        <div class="title flx-shrink">
          {{ $t("business.selector.company.title") }}
          <span class="text-disable text-f-stext-f-s">({{ tableData.length }})</span>
        </div>
        <div class="flx-end mr-32">
          <el-checkbox v-model="checkedSel" label="仅看已选" @change="checkboxChange" class="mr-16" />
          <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" />
        </div>
      </div>
    </template>
    <LjVxeTable
      ref="SaletaskMxTableRef"
      :data="list"
      :columns="columns"
      :init-param="initParam"
      table-cls="flx-1"
      :table-props="tableProps"
      :request-auto="false"
      :extraLoading="extraLoading"
      :table-events="tableEvents"
    >
      <template #toolButton><span></span></template>
    </LjVxeTable>
    <template #footer>
      <div class="flx-justify-between">
        <div class="flx-start"></div>
        <div class="dialog-footer">
          <el-button @click="drawerVisible = false">{{ $t("common.cancelText") }}</el-button>
          <el-button type="primary" @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="SelectorPrintTemplate">
import { ref, reactive, nextTick } from "vue";
import { useDesign } from "@/hooks/useDesign";
// import { getCompany } from "@/api/modules/login";
import { LjVxeTableInstance, ColumnProps, HeaderRenderScope } from "@/components/LjVxeTable/interface";
import LjVxeTable from "@/components/LjVxeTable/index.vue";
import { Refresh, Operation, EditPen, View } from "@element-plus/icons-vue";
import { ElMessage, ElButton } from "element-plus";
import { useI18n } from "vue-i18n";
import { throttle } from "lodash-es";
import { dateFormatEnum } from "@/utils/serviceDict";
import { useUserStore } from "@/stores/modules/user";
import dayjs from "dayjs";
// import { fx_company } from "@/typings/business";

interface CompanyProps {
  checkRowKeys?: any;
}

const props = withDefaults(defineProps<CompanyProps>(), {
  checkRowKeys: []
});

const { prefixCls } = useDesign("print-template-selector");
const { t } = useI18n();
// const dwname = "web_fx_saletaskmx_sel";
const extraLoading = ref(false);
const drawerVisible = ref(false);
const checkedSel = ref(false);
const SaletaskMxTableRef = ref();
const newDate = dayjs().format("YYYY-MM-DD HH:mm:ss");
const emit = defineEmits(["confirm", "newtemplate", "edittemplate"]);
const userStore = useUserStore();
// const { comid, ifERPUser } = userStore.userInfo;

const selectList = ref<any>([]);
/**
 * @description 参数
 */
let initParam = reactive({});

const clearChecked = (list: any) => {
  tableData.value.forEach((col: any) => {
    if (list.length && list.includes(col.comid)) {
      col.checked = true;
    } else {
      col.checked = false;
    }
  });
};

const handleCheckboxChange = (data: any) => {
  console.log("handleCheckboxChange data :>> ", data);
  if (data.hasOwnProperty("checked")) {
    if (data.checked) {
      // add
      selectList.value.push(data.row);
    } else {
      // remove
      for (let i = 0; i < selectList.value.length; i++) {
        if (selectList.value[i].comid == data.row.comid) {
          selectList.value.splice(i, 1);
          break;
        }
      }
    }
    let keyArr = [];
    for (const itm of selectList.value) {
      keyArr.push(itm.comid);
    }
    clearChecked(keyArr);
  } else {
    let keyArr = [];
    for (const itm of data.records) {
      keyArr.push(itm.comid);
    }
    clearChecked(keyArr);
    selectList.value = data.records;
  }
  console.log("tableData.value :>> ", tableData.value);
};

const handleCheckboxAll = (data: any) => {
  console.log("handleCheckboxAll data :>> ", data);
  let keyArr = [];
  for (const itm of data.records) {
    keyArr.push(itm.comid);
  }
  clearChecked(keyArr);
  selectList.value = data.records;
  console.log("tableData.value :>> ", tableData.value);
};

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

const columns: ColumnProps[] = [
  { type: "seq", title: "#", width: 80 },
  { type: "checkbox", width: 80 },
  {
    field: "comid",
    title: "编码",
    table: "fx_company"
  },
  {
    field: "relcode",
    title: "编码",
    table: "fx_company"
  },
  {
    field: "comname",
    title: "公司名称",
    table: "fx_company",
    type: "html"
  },
  {
    field: "simplename",
    title: "公司简称",
    table: "fx_company",
    type: "html"
  },
  {
    field: "tele",
    title: "联系电话",
    table: "fx_company",
    type: "html"
  },
  {
    field: "address",
    title: "公司地址",
    table: "fx_company",
    type: "html"
  },
  {
    field: "fx_title_erp",
    title: "ERP标题",
    table: "fx_company"
  }
];

// const rowClsNameFunc = (data: any) => {
//   const { row, rowIndex, $rowIndex } = data;
//   if (row.date_confirm_flag == 0) {
//     return "vxecol-bg-danger";
//   }
//   if (row.earliestSendDate > newDate) {
//     return "vxecol-purple";
//   }
//   return "";
// };
/**
 * @description vxetable props
 */
const tableProps = {
  height: "auto",
  minHeight: "300px",
  columnConfig: { resizable: true, useKey: true },
  rowConfig: { keyField: "comid", isCurrent: true, isHover: true, useKey: true },
  checkboxConfig: {
    checkField: "checked",
    trigger: "row",
    highlight: true,
    range: true
    // checkMethod: ({ row }: any) => {
    //   return row.date_confirm_flag > 0;
    // }
  }
  // rowClassName: rowClsNameFunc
};

// 全表搜索
const tableData = ref<any[]>([]);
const list = ref<any>([]);
const filterName = ref("");
const searchField = ref("");
const searchEvent = () => {
  const filterVal = String(searchField.value).trim().toLowerCase();
  console.log("checkedSel.value :>> ", checkedSel.value);
  if (filterVal) {
    let _list = [];
    if (checkedSel.value) {
      _list = tableData.value.filter(item => item.checked);
    } else {
      _list = tableData.value;
    }
    const filterRE = new RegExp(filterVal, "gi");
    const searchProps = ["comname", "simplename", "tele", "address"];
    const rest = _list.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 {
    if (checkedSel.value) {
      list.value = tableData.value.filter(item => item.checked);
    } 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 getCompany({ uesrid: userStore.userInfo.userid });
    // console.log("getData data :>> ", data);
    // if (data?.companies) {
    //   let list = Object.freeze<any>(data.companies);
    //   list.forEach((col: any) => {
    //     col.checked = false;
    //   });
    //   tableData.value = list;
    // }

    extraLoading.value = false;
    searchEvent();
  } catch (error) {
    extraLoading.value = false;
    console.error(error);
  }
};

/**
 * @description 设置当前已勾选状态
 */
const defaultChecked = (checkedRow: any) => {
  const $table = SaletaskMxTableRef.value?.element;
  $table.clearCheckboxRow();
  checkedRow.length && $table.setCheckboxRow(checkedRow, true);
  selectList.value = checkedRow;
  console.log("selectList.value :>> ", selectList.value);
  searchEvent();
};

/**
 * 打开组件
 * @param params 参数
 */
const open = (params: any, checked: boolean, callback?: any) => {
  drawerVisible.value = true;
  initParam = params;
  console.log("show initParam :>> ", initParam);
  checkedSel.value = checked;

  nextTick(() => {
    // !tableData.value?.length ? getData() : _refresh && searchEvent();
    if (!tableData.value?.length) {
      getData().then(() => {
        callback && callback(tableData.value);
      });
    } else {
      callback && callback(tableData.value);
    }
    //   SaletaskMxTableRef.value?.getTableList();
    //   console.log("SaletaskMxTableRef.value?.tableData :>> ", SaletaskMxTableRef.value?.tableData);
  });
};

const sumNum = (list: any[], field: string) => {
  let count = 0;
  list.forEach(item => {
    count += isNaN(Number(item[field])) ? 0 : Number(item[field]);
  });
  return count;
};

// // 获取选中列
// const getSelectEvent = () => {
//   const $table = SaletaskMxTableRef.value?.element;
//   if ($table) {
//     const selectRecords = $table.getCheckboxRecords();
//     console.log("object :>> ", selectRecords);
//   }
// };

// 确认按钮
const confirm = () => {
  // let selectRecords = [];
  // const $table = SaletaskMxTableRef.value?.element;
  // if ($table) {
  //   selectRecords = $table.getCheckboxRecords();
  // }
  emit("confirm", selectList.value, () => {
    drawerVisible.value = false;
  });
};

const checkboxChange = () => {
  console.log("checkedSel.value :>> ", checkedSel.value);
  searchEvent();
};

const onClosed = () => {
  searchField.value = "";
  filterName.value = "";
};

defineExpose({
  open,
  defaultChecked
});
</script>

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

.#{$prefix-cls} {
  .el-dialog__body {
    padding: $space-b1 $space-b3;
  }
}
</style>
