<template>
  <el-dialog
    :title="$t('business.selector.saletaskmx.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.saletaskmx.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>
    <LjVxeTable
      ref="SaletaskMxTableRef"
      :data="list"
      :columns="columns"
      :init-param="initParam"
      :dwname="dwname"
      table-cls="h-full"
      :table-props="tableProps"
      :request-auto="false"
      :extraLoading="extraLoading"
      :table-events="tableEvents"
    >
      <template #toolButton><span></span></template>
      <!-- <template #toolButton="{ openColSetting, settingBtnLoading }">
        <div class="flx-end">
          <vxe-input
            class="mb-15 mr-12"
            v-model="filterName"
            type="search"
            placeholder="试试搜索(物料名称\编号\配置)"
            @keyup="searchEvent"
            clearable
          ></vxe-input>
          <el-button :icon="Refresh" circle @click="getData" />
          <el-button :icon="Operation" circle :loading="settingBtnLoading" @click="openColSetting" />
        </div>
      </template> -->
    </LjVxeTable>
    <template #footer>
      <div class="flx-justify-between">
        <div class="footer-tips flx-start">
          <div class="tips-item flx-center text-h5-m text-secondary-text" v-for="item in tipsList" :key="item.type">
            <span :class="item.type"></span>
            {{ item.label }}
          </div>
        </div>
        <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="SelectorSaletaskMx">
import { ref, reactive, inject, nextTick } from "vue";
import { useDesign } from "@/hooks/useDesign";
// import { getSaletaskmxSelect } from "@/api/modules/saletask";
import { LjVxeTableInstance, ColumnProps, HeaderRenderScope } from "@/components/LjVxeTable/interface";
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 { fx_saletaskmx } from "@/typings/business";
import { dateFormatEnum } from "@/utils/serviceDict";
import dayjs from "dayjs";

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

const selectList = ref([]);

const tipsList = [
  {
    type: "purple",
    label: t("business.tips.saletaskmx.earliestSendDate")
  },
  {
    type: "danger",
    label: t("business.tips.saletaskmx.dateConfirmFlag0")
  }
];

const handleCheckboxChange = (data: any) => {
  selectList.value = data.records;
  // const $table = SaletaskMxTableRef.value?.element;
  // if ($table) {
  //   let selectRecords = [];
  //   selectRecords = $table.getCheckboxRecords();
  //   console.log("selectRecords :>> ", selectRecords);
  // }
};

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

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",
  columnConfig: { resizable: true, useKey: true },
  checkboxConfig: {
    checkField: "checked",
    trigger: "row",
    highlight: true,
    range: true,
    checkMethod: ({ row }: any) => {
      return row.date_confirm_flag > 0;
    }
  },
  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 = ["mxcode", "mtrlcode", "mtrlname", "woodcode", "status"];
    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 getSaletaskmxSelect(initParam);
    // console.log("getData data :>> ", data);
    // if (data?.mxs) {
    //   let list = Object.freeze<any>(data.mxs);
    //   list.forEach((col: fx_saletaskmx) => {
    //     col.checked = false;
    //   });
    //   tableData.value = list;
    // }
    extraLoading.value = false;
    searchEvent();
  } catch (error) {
    extraLoading.value = false;
    console.error(error);
  }
};

const show = (params: any) => {
  drawerVisible.value = true;
  console.log("show params :>> ", params);
  initParam.cuscomid = params.cuscomid;

  console.log("show initParam :>> ", initParam);
  !tableData.value?.length && getData();

  // nextTick(() => {
  //   SaletaskMxTableRef.value?.getTableList();
  //   console.log("SaletaskMxTableRef.value?.tableData :>> ", SaletaskMxTableRef.value?.tableData);
  // });
};

const initParam = reactive({ cuscomid: 0 });

const dataCallback = (data: any) => {
  return data.mxs;
};
// console.log(
//   "getSaletaskmxSelect({ cuscomid: baseMsgFormRef.value?.searchParam.cuscomid }) :>> ",
//   getSaletaskmxSelect({ cuscomid: baseMsgFormRef.value?.searchParam.cuscomid })
// );

const columns: ColumnProps[] = [
  { type: "seq", title: "#", width: 80 },
  { type: "checkbox", width: 80 },
  {
    field: "tid",
    title: "云端订单编号",
    dataSources: "fx_saletask.tid",
    table: "fx_saletask"
  },
  {
    field: "mtrlcuscode",
    title: "销售订单相关号",
    dataSources: "fx_saletaskmx.mtrlcuscode",
    table: "fx_saletaskmx"
  },
  {
    field: "date_confirm_flag",
    title: "交期确定",
    dataSources: "fx_saletaskmx.date_confirm_flag",
    table: "fx_saletaskmx",
    filters: [
      {
        label: "确定",
        value: 1
      },
      {
        label: "未确定",
        value: 0
      }
    ],
    render: scope => {
      switch (scope.row.date_confirm_flag) {
        case 1:
          return <el-checkbox class={"el-checkbox__disabled-checked"} checked={true} disabled={true} />;
        default: // 0
          return "";
      }
    }
  },
  {
    field: "advanceday",
    title: "提前天数",
    dataSources: "advanceday",
    table: "fx_saletaskmx"
  },
  {
    field: "mtrlcode",
    title: "物料编码",
    dataSources: "fx_saletaskmx.mtrlcode",
    table: "fx_saletaskmx",
    type: "html"
  },
  {
    field: "mtrlname",
    title: "物料名称",
    dataSources: "fx_saletaskmx.mtrlname",
    table: "fx_saletaskmx",
    type: "html"
  },
  {
    field: "mtrlmode",
    title: "物料规格",
    dataSources: "fx_saletaskmx.mtrlmode",
    table: "fx_saletaskmx"
  },
  {
    field: "qty",
    title: "数量",
    dataSources: "fx_saletaskmx.qty",
    table: "fx_saletaskmx"
  },
  {
    field: "outQty",
    title: "待发货数",
    dataSources: "outqty",
    table: "fx_saletaskmx"
  },
  {
    field: "requiredate",
    title: "要求交期",
    dataSources: "fx_saletaskmx.requiredate",
    table: "fx_saletaskmx",
    format: "yyyy-MM-dd",
    formatEnum: dateFormatEnum
  },
  {
    field: "mxdscrp",
    title: "明细备注",
    dataSources: "fx_saletaskmx.mxdscrp",
    table: "fx_saletaskmx"
  },
  {
    field: "earliestSendDate",
    title: "最早送货时间",
    dataSources: "earliestSendDate",
    table: "fx_saletaskmx",
    format: "yyyy-MM-dd",
    formatEnum: dateFormatEnum,
    sortable: true
  },
  {
    field: "cus_mtrldef_senddays",
    title: "最早送货提前天数",
    dataSources: "cus_mtrldef_senddays",
    table: "fx_saletaskmx"
  },
  {
    field: "cus_receiveqty",
    title: "客户确认收货数",
    dataSources: "fx_saletaskmx.cus_receiveqty",
    table: "fx_saletaskmx"
  },
  {
    field: "unit",
    title: "单位",
    dataSources: "fx_mtrldef.unit",
    table: "fx_saletaskmx"
  },
  {
    field: "price",
    title: "单价",
    dataSources: "fx_saletaskmx.price",
    table: "fx_saletaskmx"
  },
  {
    field: "mxcode",
    title: "明细唯一码",
    dataSources: "fx_saletaskmx.mxcode",
    table: "fx_saletaskmx",
    type: "html"
  },
  {
    field: "mxdscrp2",
    title: "明细备注2",
    dataSources: "fx_saletaskmx.mxdscrp2",
    table: "fx_saletaskmx"
  },
  {
    field: "taskcode",
    title: "ERP订单编号",
    dataSources: "fx_saletask.taskcode",
    table: "fx_saletask"
  },
  {
    field: "status",
    title: "物料配置",
    dataSources: "fx_saletaskmx.status",
    table: "fx_saletaskmx",
    type: "html"
  },
  {
    field: "woodcode",
    title: "物料配置1",
    dataSources: "fx_saletaskmx.woodcode",
    table: "fx_saletaskmx",
    type: "html"
  },
  {
    field: "pcode",
    title: "物料配置2",
    dataSources: "fx_saletaskmx.pcode",
    table: "fx_saletaskmx",
    type: "html"
  },
  {
    field: "plancode",
    title: "生产批号",
    dataSources: "fx_saletaskmx.plancode",
    table: "fx_saletaskmx"
  },
  {
    field: "saletask_mxid",
    title: "销售订单明细序号",
    dataSources: "fx_saletaskmx.saletask_mxid",
    table: "fx_saletaskmx"
  },
  {
    field: "billtype",
    title: "单据类型",
    dataSources: "fx_saletask.billtype",
    table: "fx_saletaskmx"
  },
  {
    field: "storagename",
    title: "收货仓库",
    dataSources: "fx_saletaskmx.storagename",
    table: "fx_saletaskmx"
  },
  {
    field: "relcodestr",
    title: "生产计划相关号",
    dataSources: "fx_saletaskmx.relcodestr",
    table: "fx_saletaskmx"
  },
  {
    field: "taskcodestr",
    title: "相关销售订单号",
    dataSources: "fx_saletaskmx.taskcodestr",
    table: "fx_saletaskmx"
  }
];

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

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

// 确认按钮
const emit = defineEmits(["confirm"]);
const confirm = () => {
  let selectRecords = [];
  const $table = SaletaskMxTableRef.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>
