<template>
  <el-dialog
    :class="`${prefixCls}`"
    width="50%"
    draggable
    v-model="drawerVisible"
    align-center
    :modal="false"
    append-to-body
    @closed="autoClosedWidget"
  >
    <!-- :z-index="3000" -->
    <template #header>
      <div class="flx-justify-between">
        <div class="title flx-shrink">
          <span class="text-h4-m">
            {{ $t("business.selector.printTemplate.title") }}
          </span>
          <el-divider direction="vertical" />
          <span class="text-h4-m mr-12 text-secondary-text">
            {{ dwnameTitle }}
          </span>
        </div>
        <div class="flx-end mr-32">
          <el-button :icon="Refresh" circle @click="getData" />
        </div>
      </div>
    </template>
    <LjVxeTable
      ref="tableRef"
      :data="list"
      :columns="columns"
      :init-param="initParam"
      table-cls="flx-1"
      :table-props="tableProps"
      :request-auto="false"
      :extraLoading="extraLoading"
      :table-events="tableEvents"
      :header-cell-class-name="headerCellClassName"
    >
      <template #toolButton><span></span></template>
      <!-- 表格操作 -->
      <!-- <template #directPrint="{ row }">
        <el-switch v-model="row.directPrint" @change="val => handleSwitchDirectPrint(val, row)" />
      </template> -->
      <template #printer="{ row }">
        <el-select
          v-model="row.printer"
          :placeholder="$t('sys.print.defaultPrinter')"
          class="w-full"
          :empty-values="[null, undefined]"
          :value-on-clear="null"
          clearable
          placement="bottom-start"
          @change="(val: any) => showDirectPrintMenu(val, row)"
        >
          <el-option v-for="item in printerList" :key="item.name" :label="item.displayName" :value="item.name" />
        </el-select>
      </template>
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="toPreview(scope.row)">{{
          $t("business.printEditor.preview")
        }}</el-button>
        <template v-if="userInfo.empid == 0">
          <el-tooltip effect="dark" :content="$t('common.editText')" placement="bottom" :enterable="false" :hide-after="0">
            <el-button type="info" link :icon="EditPen" @click="toEdit(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" :content="$t('common.delText')" placement="bottom" :enterable="false" :hide-after="0">
            <el-button
              type="danger"
              link
              :icon="Delete"
              :disabled="scope.row.isdefault == 1"
              @click="toDel(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" :content="$t('common.saveAsText')" placement="bottom" :enterable="false" :hide-after="0">
            <el-button
              type="info"
              link
              :icon="CopyDocument"
              @click="toEdit(JSON.parse(JSON.stringify(scope.row)), true)"
            ></el-button>
          </el-tooltip>
        </template>
      </template>
    </LjVxeTable>
    <template #footer>
      <div class="flx-justify-between">
        <div class="footer-tips flx-start">
          <el-button v-if="userInfo.empid == 0" @click="toAdd" :loading="addLoading" :disabled="addLoading">{{
            $t("common.add")
          }}</el-button>
        </div>
        <div class="dialog-footer">
          <el-button @click="drawerVisible = false">{{ $t("common.cancelText") }}</el-button>
          <el-button type="primary" @click="confirm">
            {{ $t("common.table.print") }}
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="tsx" name="SelectorPrintTemplate">
import { ref, reactive, inject, nextTick } from "vue";
import { useDesign } from "@/hooks/useDesign";
import { getPrintTemplate, savePrintTemplate, delPrintTemplate } from "@/api/modules/print";
import { LjVxeTableInstance, ColumnProps, HeaderRenderScope } from "@/components/LjVxeTable/interface";
import LjVxeTable from "@/components/LjVxeTable/index.vue";
import { Refresh, Delete, EditPen, View, Finished, CollectionTag, CopyDocument } from "@element-plus/icons-vue";
import { ElMessage, ElButton, ElMessageBox } from "element-plus";
import { useI18n } from "vue-i18n";
import { throttle } from "lodash-es";
import { useUserStore } from "@/stores/modules/user";
// import dayjs from "dayjs";
import { pick } from "lodash-es";
import { useHiprinterStore } from "@/stores/modules/hiprinter";
import { useHiPrintPlugin } from "@/hooks/useHiPrintPlugin";
import { HiprintState } from "@/stores/interface/index";
import { PRINT_KEY_ATTR } from "@/config/index";
import { PrintTemplate } from "@/api/interface/index";

const { prefixCls } = useDesign("print-template-selector");
const { t } = useI18n();
const dwnameTitle = ref("");
const extraLoading = ref(false);
const drawerVisible = ref(false);
const tableRef = ref();
const emit = defineEmits(["confirm", "newtemplate", "edittemplate", "preview", "closed"]);
const userStore = useUserStore();
const userInfo = userStore.userInfo;
const comid = ref(0);
const columns = ref<ColumnProps[]>([]);
// const defaultTid = ref(0);
/**
 * @description 当前已选公司列表
 */
const curTemplate = ref();
const curCompanies = ref<number[]>([]);
// const selectList = ref([]);
/**
 * @description 参数
 */
let initParam = reactive<PrintTemplate.ReqGetPrintTemplate>({
  dwname: ""
});

/**
 * @description 是否开启直接打印
 */
const directPrintEnabled = ref(false);
const hiprinterStore = useHiprinterStore();
const hiprintKey = ref("");

const { printerList } = useHiPrintPlugin(t);

/**
 * @description 打印机列表
 */
const currentDirectPrinter = ref<HiprintState.printerParams>({});
const defaultPrinter = {
  printer: "",
  copies: 1
};

/**
 * @description 打开打印机设置弹窗
 */
const showDirectPrintMenu = (value: any, row: any) => {
  console.log("showDirectPrintMenu value :>> ", value, row);

  hiprinterStore.setPrinter(hiprintKey.value, row.printid, row.printer);
};

/**
 * @description 设置打印份数，开关
 */
// const handleSwitchDirectPrint = (val: any, row: any) => {
//   console.log("handleSwitchDirectPrint row :>> ", row);
//   if (val) {
//     hiprinterStore.setPrinter(hiprintKey.value, row.printid, row.printer);
//     ElMessage.success(t("sys.print.open") + ":" + row.printer?.printer);
//   } else {
//     hiprinterStore.delPrinter(hiprintKey.value, row.printid);
//     ElMessage.success(t("sys.print.close"));
//   }
// };

// /**
//  * @description 设置打印份数，保存本地
//  */
// const handleSavePrinter = () => {
//   hiprinterStore.setPrinter(hiprintKey.value, currentDirectPrinter.value);
//   printerSettingDropdownRef.value.handleClose();

//   ElMessage.success(t("sys.api.operationSuccess") + ":" + currentDirectPrinter.value.printer);
// };

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

const handleEditClosed = ({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }: any) => {
  if (column.field == "copies") {
    console.log("handleEditClosed row :>> ", row);
    hiprinterStore.setPrinter(hiprintKey.value, row.printid, row.printer, Number(row.copies));
  }
};

const tableEvents = {
  // "checkbox-change": handleCheckboxChange,
  // "checkbox-all": handleCheckboxChange,
  // "checkbox-range-change": handleCheckboxChange
  "edit-closed": handleEditClosed
};

let columns_base: ColumnProps[] = [
  { type: "seq", title: "#", width: 80 },
  // { type: "expand", width: 80 },
  {
    field: "aliase",
    title: "模板别名",
    table: "sys_print_template",
    render: scope => {
      return scope.row.aliase || scope.row.printid;
    }
  },
  {
    field: "printid",
    title: "模板ID",
    table: "sys_print_template",
    width: 120
  },
  {
    field: "dwname",
    title: "所属窗口",
    table: "sys_print_template"
  },
  // {
  //   field: "directPrint",
  //   title: "快速打印",
  //   table: "sys_print_template"
  // },
  {
    field: "printer",
    title: "打印机",
    table: "sys_print_template",
    titlePrefix: { message: "设置默认打印机后，即开启快速打印", icon: "vxe-icon-question-circle-fill" }
  },
  {
    field: "copies",
    title: "打印次数",
    table: "sys_print_template",
    width: 120,
    editRender: {
      name: "$input",
      props: {
        type: "number"
      }
    },
    titlePrefix: { message: "仅快速打印时生效", icon: "vxe-icon-question-circle-fill" }
  }
];
let col_op: ColumnProps = { field: "operation", title: "操作", width: 220, fixed: "right" };

// 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 "";
// };

// 修改表头样式
const headerCellClassName = ({ column }: any) => {
  if (column?.editRender || column.field == "printer") {
    return "vxecol-edit";
  }
  return null;
};

/**
 * @description vxetable props
 */
const tableProps = {
  height: "auto",
  minHeight: "300px",
  columnConfig: { resizable: true, useKey: true },
  editConfig: { trigger: "click", mode: "row", showIcon: false },
  checkboxConfig: {
    // checkField: "checked",
    // trigger: "row",
    // highlight: true
    // range: true
    // checkMethod: ({ row }: any) => {
    //   return row.date_confirm_flag > 0;
    // }
  },
  editRules: {
    copies: [
      {
        type: "number",
        min: 1,
        message: t("business.error.print.minCopies")
      }
    ]
  }
  // 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 (params?: any, successCallback?: any, failCallback?: any) => {
  try {
    extraLoading.value = true;
    let _params = params ?? initParam;
    const data = await getPrintTemplate(_params);
    console.log("getData data :>> ", data);
    extraLoading.value = false;
    tableData.value = data?.list ?? [];
    let currentArr = hiprinterStore.getPrinter(_params.dwname, _params?.printid);

    console.log("currentArr :>> ", currentArr, _params);

    if (data?.list.length) {
      for (let i = 0; i < data.list.length; i++) {
        let _current = currentArr.find((item: any) => item.printid == data.list[i].printid);
        console.log("_current :>> ", _current);
        if (_current) {
          data.list[i].copies = _current?.printer?.copies ?? 1;
          data.list[i].printer = _current?.printer?.printer;
        } else {
          data.list[i].copies = 1;
          data.list[i].printer = "";
        }
      }

      console.log("data :>> ", data);
      searchEvent();
      successCallback && successCallback(data);
    } else {
      failCallback && failCallback();
    }
  } catch (error) {
    extraLoading.value = false;
    console.error(error);
  }
};

/**
 * 打开组件
 * @param params 参数
 */
const open = (params: PrintTemplate.ReqGetPrintTemplate, callback?: any) => {
  hiprintKey.value = params.dwname;

  // if (JSON.stringify(current) == "{}") {
  //   current = defaultPrinter;
  //   directPrintEnabled.value = false;
  // } else {
  //   directPrintEnabled.value = true;
  // }
  // currentDirectPrinter.value = current;

  // let ori = JSON.parse(JSON.stringify(initParam));
  initParam = params;
  console.log("show initParam :>> ", initParam);
  // let _dwname = params.dwname.indexOf("_print_template") > -1 ? params.dwname.replace("_print_template", "") : params.dwname;
  dwnameTitle.value = t(`business.dwname.${params.dwname}`);

  columns.value = columns_base;
  columns.value.push(col_op);

  getData(
    params,
    () => {
      drawerVisible.value = true;
    },
    () => {
      if (userInfo.empid == 0) {
        drawerVisible.value = true;
      } else {
        ElMessage.warning("请管理员先设置打印模版");
      }
    }
  );
  nextTick(() => {
    callback && callback();
    //   tableRef.value?.getTableList();
    //   console.log("tableRef.value?.tableData :>> ", tableRef.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;
// };

/**
 * @description 获取打印模板
 */
const checkTemplateFunc = async (data: any) => {
  if (data.hasOwnProperty("content") && data.content != "") {
    console.log("checkTemplateFunc data :>> ", data);
    return data;
  }

  // extraLoading.value = true;
  // // const res = await getPrintTemplate({
  // //   tid: data.tid
  // // });
  // const res: any = {};
  // extraLoading.value = false;
  // if (res.templateList.length > 0) {
  //   // 获取新模板数据
  //   for (const itm of tableData.value) {
  //     if (itm.tid === data.tid) {
  //       itm.dwSyntax = res.templateList[0].dwSyntax;
  //       break;
  //     }
  //   }
  //   return res.templateList[0];
  // } else {
  //   return data;
  // }
};

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

// 确认按钮
const confirm = () => {
  let selectRecords = null;
  const $table = tableRef.value?.element;
  if ($table) {
    selectRecords = $table.getCurrentRecord();
  }
  if (!selectRecords) {
    ElMessage.warning(t("business.selector.printTemplate.empty"));
    return;
  }
  console.log("selectRecords :>> ", selectRecords);

  checkTemplateFunc(selectRecords).then(val => {
    emit("confirm", val, () => {
      drawerVisible.value = false;
    });
  });
};

const addLoading = ref(false);
// 新建模版
const toAdd = () => {
  addLoading.value = true;
  emit("newtemplate", null, () => {
    addLoading.value = false;
  });
};

// 修改
const toEdit = (data: any, isNew: boolean = false) => {
  let _data = data;
  if (isNew) {
    delete _data.printid;
  }
  checkTemplateFunc(_data).then(val => {
    console.log("to Edit checkTemplateFunc val :>> ", val);
    emit("edittemplate", val);
  });
};

// 删除
const toDel = (data: any) => {
  ElMessageBox.confirm(`${t("business.selector.printTemplate.delConfirm")}:《${data?.aliase}》`, t("sys.app.logoutTip"), {
    confirmButtonText: t("common.delText"),
    cancelButtonText: t("common.cancelText"),
    type: "error"
  }).then(async () => {
    try {
      extraLoading.value = true;
      await delPrintTemplate({ dwname: data.dwname, printid: data.printid });

      hiprinterStore.delPrinter(hiprintKey.value, data.printid);

      ElMessage.success(t("sys.api.sueccessToDel"));
      getData();
    } catch (error) {
      extraLoading.value = false;
      console.error(error);
    }
  });
};

// 预览
const toPreview = (data: any) => {
  console.log("toPreview data :>> ", data);
  checkTemplateFunc(data).then(val => {
    console.log("toPreview checkTemplateFunc val :>> ", val);
    emit("preview", val);
  });
};

// 打印模板: 新增指定供应商
const toAddOpCompany = (data: any, callback?: any) => {
  if (!data.length) {
    if (curCompanies.value.length) {
      ElMessageBox.confirm(
        `${curTemplate.value?.aliase}:${t("business.selector.printTemplate.clearConfirm")}`,
        t("sys.app.logoutTip"),
        {
          confirmButtonText: t("common.empty"),
          cancelButtonText: t("common.cancelText"),
          type: "warning"
        }
      ).then(() => {
        toClearOp(data);
        callback && callback();
      });
    } else {
      ElMessage.warning(t("business.selector.company.empty"));
    }
    return;
  }
  toSaveOption(data, callback);
};
// 打印模板: 保存设置
const toSaveOption = async (data: any, callback: any) => {
  try {
    extraLoading.value = true;
    let comidList = [];
    for (const itm of data) {
      comidList.push(itm.comid);
    }
    // await savePrintOption({ tid: curTemplate.value.tid, clearOpposide: true, addOpposideList: comidList });
    ElMessage.success(t("sys.api.operationSuccess"));
    callback && callback();
    getData();
  } catch (error) {
    extraLoading.value = false;
    console.error(error);
  }
};
// 打印模板: 清空设置
const toClearOp = async (data: any) => {
  try {
    extraLoading.value = true;
    // await savePrintOption({ tid: data.tid, clearOpposide: true });
    ElMessage.success(t("common.table.successCleared"));
    getData();
  } catch (error) {
    extraLoading.value = false;
    console.error(error);
  }
};
// 打印模板: 设置默认模板
const toAddOpDefault = async (data: any) => {
  try {
    extraLoading.value = true;
    // await savePrintOption({ tid: data.tid, setDefault: true });
    ElMessage.success(t("sys.api.operationSuccess"));
    getData();
  } catch (error) {
    extraLoading.value = false;
    console.error(error);
  }
};

const autoClosedWidget = () => {
  emit("closed");
};

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

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

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