<template>
  <div class="box-main">
    <div class="box-body">
      <MomTable
        ref="MomTable"
        row-key="id"
        :row-selection="rowSelection"
        :columns="tableColumns"
        :data-source="tableData"
        :query-param="queryForm"
        :query-param-item="queryFormItem"
        :action-buttons="actionButtons"
        :page.sync="page"
        :total="total"
        :show-enable-flag="true"
        @beforeSearch="beforeSearch"
        @copy="handleCopy"
        @edit="handleEdit"
        @delete="handleDelete"
        @search="searchPageData"
        @enable="
          (record) =>
            handleStatus(
              { status: 'Y', id: record.id },
              'ENABLED',
              'ENABLED_DATA_INFO',
              'ENABLE_SUCCESS'
            )
        "
        @disable="
          (record) =>
            handleStatus(
              { status: 'N', id: record.id },
              'DISABLED',
              'DISABLED_DATA_INFO',
              'DISABLE_SUCCESS'
            )
        "
      >
        <div slot="toolbar">
          <!-- 新增 -->
          <a-button v-if="hasAuth('PRINTER_SETTING:ADD')" @click="handleAdd">
            <a-icon type="plus" />
            {{ $t("ADD") }}
          </a-button>
          <a-button
            v-if="hasAuth('PRINTER_SETTING:BATCH_DELETE')"
            type="danger"
            icon="delete"
            @click="handDelete"
          >
            {{ $t("BATCH_DELETE") }}
          </a-button>
        </div>
        <template slot="labelType" slot-scope="text, record">
          <span>{{ formatData(labelTypeList, record.labelType) }}</span>
        </template>
        <div slot="enableFlag" slot-scope="text, record">
          <span v-if="record.enableFlag == 'Y'" style="color: #0fd19c">{{
            formatData(stateList, record.enableFlag)
          }}</span>
          <span v-else style="color: #d45f5f">{{
            formatData(stateList, record.enableFlag)
          }}</span>
        </div>
      </MomTable>
    </div>
    <MegaDrawer
      :append-to-body="true"
      :visible.sync="drawer"
      :title="drawerTitle"
      width="520"
      @close="handleCancel"
    >
      <div slot="main">
        <a-form-model
          ref="formRef"
          layout="vertical"
          :model="formData"
          :rules="rules"
        >
          <!-- 标签类型 -->
          <a-form-model-item :label="$t('LABEL_TYPE')" prop="labelType">
            <i-table-select
              v-model="formData.labelType"
              :options="queryFormItem.labelType.options"
            />
          </a-form-model-item>
          <!-- elabel移动打印机IP地址 -->
          <a-form-model-item
            :label="$t('ELABEL_MOBILE_IP_ADDRESS')"
            prop="mobilePrinterIp"
          >
            <a-input v-model="formData.mobilePrinterIp"></a-input>
          </a-form-model-item>
          <!-- 服务Ip 连接获取打印机名称 -->
          <a-form-model-item :label="$t('SERVICE_ADDRESS')" prop="serverIp">
            <a-row>
              <a-col :span="21">
                <a-input v-model="formData.serverIp" />
              </a-col>
              <a-col :span="2">
                <a-button
                  type="primary"
                  :disabled="!formData.labelType || !formData.serverIp"
                  class="service_input"
                  @click="handleConnect"
                >
                  {{ $t("CONNECT") }}
                </a-button>
              </a-col>
            </a-row>
          </a-form-model-item>
          <div class="line mt-20 mb-20" />
          <!-- 打印机名称 -->
          <a-form-model-item :label="$t('PRINTER_NAME')" prop="printerName">
            <i-table-select
              v-model="formData.printerName"
              :options="printerList"
            />
          </a-form-model-item>
          <!-- 权重 -->
          <a-form-model-item :label="$t('WEIGHT')">
            <a-input-number
              v-model="formData.weight"
              style="width: 100%"
              :min="1"
            />
          </a-form-model-item>
          <!-- 条件 -->
          <a-form-model-item :label="$t('CONDITION')">
            <div
              class="heightLimted"
              style="max-height: 300px; overflow-x: hidden; overflow-y: auto"
            >
              <div
                v-for="(condition, index) in formData.conditions"
                :key="index"
              >
                <a-form-model
                  :ref="`subFormRef${index}`"
                  style="margin-top: -10px"
                  :model="condition"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 18 }"
                >
                  <a-row type="flex" style="margin-right: 0">
                    <a-col :span="8" class="mt-10">
                      <a-form-model-item prop="paramName">
                        <i-table-select
                          v-model="condition.paramName"
                          :options="paramNames"
                        />
                      </a-form-model-item>
                    </a-col>
                    <a-col :span="8" :offset="1" class="mt-10">
                      <a-form-model-item prop="paramValue">
                        <!-- 请输入限制值 -->
                        <a-input
                          v-model="condition.paramValue"
                          :placeholder="$t('PLACEENTER')"
                          :disabled="!condition.paramName"
                        />
                      </a-form-model-item>
                    </a-col>
                    <a-col :span="4" class="mt-10 btns">
                      <a-icon
                        v-show="formData.conditions.length >= 1"
                        type="delete"
                        @click="deleteSubForm(index)"
                      />
                      <a-icon
                        v-show="index === formData.conditions.length - 1"
                        type="plus"
                        @click="addSubForm(index)"
                      />
                    </a-col>
                  </a-row>
                </a-form-model>
              </div>
            </div>
          </a-form-model-item>
        </a-form-model>
      </div>
      <template slot="footer">
        <a-button type="primary" @click="handleSave('formRef')">
          <Icon type="icon-cur-save_1" :size="18" /> {{ $t("SAVE") }}
        </a-button>
        <a-button @click="handleCancel">
          <Icon type="icon-dir-f-rollback" :size="18" /> {{ $t("CANCEL") }}
        </a-button>
      </template>
    </MegaDrawer>
  </div>
</template>

<script>
import debounce from "lodash/debounce";
import { Drawer as MegaDrawer, Icon } from "@mega-design/ui-vue";
import Settings from "@/config/settings";
import ApiConstant from "@/api/ApiConstant";
import { PS_LABEL_TYPE, PS_SYSTEM, PS_PARAM } from "../constant";
import { ELabel } from "../utils/eLabel";

export default {
  name: "LabDest",
  components: {
    MegaDrawer,
    Icon,
  },
  data() {
    return {
      drawerTitle: "",
      // 查询sort
      sortParams: null,
      // 查询表单数据
      queryForm: {
        labelType: null,
      },
      paramNames: [],
      tableData: [],
      stateList: [],
      total: 0,
      page: 1,
      drawer: false,
      drawerType: "add",
      formData: {},
      printerList: [], // 打印机列表
      eLabel: null,
      actionButtons: [
        this.hasAuth(`PRINTER_SETTING:COPY`) && "copy",
        this.hasAuth(`PRINTER_SETTING:EDIT`) && "edit",
        this.hasAuth(`PRINTER_SETTING:DELETE`) && "delete",
      ],
      labelTypeList: [],
      selectedRowKeys: [],
    };
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    rules() {
      return {
        labelType: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        serverIp: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        printerName: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        mobilePrinterIp: [
          {
            max: 32,
            message: this.$t("PLACEENTER") + 32 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
      };
    },
    // 标签类型key=>value对象
    labelTypeMap() {
      const obj = {};
      this.queryFormItem.labelType.options.forEach((item) => {
        obj[item.value] = item.label;
      });
      return obj;
    },
    // 参数key=>value对象
    paramMap() {
      const obj = {};
      this.paramNames.forEach((item) => {
        obj[item.value] = item.label;
      });
      return obj;
    },
    queryFormItem() {
      return this.$observable("queryFormItem", {
        // 标签类型
        labelType: {
          label: () => this.$t("LABEL_TYPE"),
          itemType: "select",
          optionsProps: {
            label: "label",
            value: "value",
          },
          options: [],
        },
      });
    },
    tableColumns() {
      return [
        // 标签类型
        {
          dataIndex: "labelType",
          title: () => this.$t("LABEL_TYPE"),
          scopedSlots: { customRender: "labelType" },
          width: 210,
          sorter: false,
        },
        // 服务IP
        {
          dataIndex: "serverIp",
          title: () => this.$t("SERVICE_ADDRESS"),
          width: 240,
          sorter: false,
        },
        // 打印机名称
        {
          dataIndex: "printerName",
          title: () => this.$t("PRINTER_NAME"),
          minWidth: 240,
          sorter: false,
        },
        // elabel移动打印机IP地址
        {
          dataIndex: "mobilePrinterIp",
          title: () => this.$t("ELABEL_MOBILE_IP_ADDRESS"),
          minWidth: 240,
          sorter: false,
        },
        // 权重
        {
          dataIndex: "weight",
          title: () => this.$t("WEIGHT"),
          width: 200,
          sorter: false,
        },
        {
          dataIndex: "enableFlag",
          sorter: false,
          width: 80,
          title: () => this.$t("STATUS"), // 状态
          scopedSlots: { customRender: "enableFlag" },
        },
        // 更新人员
        {
          dataIndex: "updateBy",
          title: () => this.$t("UPDATE_BY"),
          width: 120,
          sorter: false,
        },
        // 更新时间
        {
          dataIndex: "updateTime",
          title: () => this.$t("UPDATE_TIME"),
          width: 200,
          sorter: false,
        },
      ];
    },
  },
  mounted() {},
  methods: {
    formatData(data, status) {
      const result = data.find((item) => item.value === status.toString());
      return result ? result.label : "";
    },
    // 后台分页查询
    searchPageData(params) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/print/destination/search`, {
          params,
        })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = res.data.data.total;
        });
    },
    // 初始化选项
    beforeSearch() {
      // 获取标签
      this.getDictByCode("DIC:CORE:PS_LABEL_TYPE").then((res) => {
        this.queryFormItem.labelType.options = res.data.data;
        this.labelTypeList = res.data.data;
      });
      // 获取参数
      this.getDictByCode("DIC:CORE:PS_PARAM").then((res) => {
        this.paramNames = res.data.data;
      });
      this.getDictByCode("DIC:COMMON:ENABLE_FLAG").then((res) => {
        this.stateList = res?.data?.data || [];
      });
    },
    // 启用、禁用
    handleStatus(record, titleText, contentText, tips) {
      this.$confirm({
        title: this.$t(titleText),
        content: this.$t(contentText),
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "exclamation-circle",
        onOk: () => {
          const { id, status } = record;
          this.$axios
            .put(
              `${ApiConstant.PREFIX_CORE}/api/print/destination/enable/${id}/${status}`
            )
            .then((res) => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 点击新增
    handleAdd() {
      this.$set(this, "formData", {
        labelType: this.queryForm.labelType,
        serverIp: "",
        printerName: "",
        mobilePrinterIp: "",
        weight: 0,
        conditions: [
          {
            paramName: "",
            paramValue: "",
          },
        ],
      });
      this.drawerType = "add";
      this.drawerTitle = this.$t("ADD");
      this.drawer = true;
    },
    // 复制
    handleCopy(row) {
      this.drawerTitle = this.$t("COPY");
      this.handleOpenDrawer("copy", row);
    },
    // 编辑
    handleEdit(row) {
      this.drawerTitle = this.$t("EDIT");
      this.handleOpenDrawer("edit", row);
    },
    // 新增或者编辑
    handleOpenDrawer(type, row) {
      this.drawerType = type;
      this.drawer = true;
      if (type === "edit" || type === "copy") {
        this.$set(this, "formData", JSON.parse(JSON.stringify(row)));
        if (
          !this.formData.conditions ||
          this.formData.conditions.length === 0
        ) {
          this.formData.conditions = [
            {
              paramName: "",
              paramValue: "",
            },
          ];
        }
      } else if (type === "add") {
        this.$set(this, "formData", {
          labelType: this.queryForm.labelType,
          serverIp: "",
          printerName: "",
          mobilePrinterIp: "",
          weight: 0,
          conditions: [
            {
              paramName: "",
              paramValue: "",
            },
          ],
        });
      }
    },
    handDelete() {
      if (this.selectedRowKeys.length > 0) {
        this.$confirm({
          title: this.$t("DELETE"),
          content: this.$t("DELETE_INFO"),
          okType: "warning",
          okText: this.$t("CONFIRM"),
          cancelText: this.$t("CANCEL"),
          centered: false,
          icon: "close-circle",
          onOk: () => {
            this.$axios
              .delete(
                `${ApiConstant.PREFIX_CORE}/api/print/destination/batch-delete`,
                {
                  params: {
                    ids: this.selectedRowKeys.join(","),
                  },
                }
              )
              .then((res) => {
                this.$refs.MomTable?.query();
                this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
              });
          },
        });
      } else {
        this.$message.error(this.$t("SELECT_ONE_DATA"));
      }
    },
    // 删除
    handleDelete(row) {
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okType: "warning",
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios
            .delete(
              `${ApiConstant.PREFIX_CORE}/api/print/destination/${row.id}`
            )
            .then((res) => {
              this.$refs.MomTable?.query();
              this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
            });
        },
      });
    },
    // 保存&修改 防抖
    save() {
      if (this.drawerType === "copy") {
        delete this.formData.id;
      }
      // 将未选择条件的子数据删除
      const data = { ...this.formData };
      data.conditions = data.conditions.filter((item) => item.paramName);
      // 组请求
      if (this.drawerType === "edit") {
        this.$axios
          .put(`${ApiConstant.PREFIX_CORE}/api/print/destination`, data)
          .then((res) => {
            this.$message.success(this.$t("EDIT_SUCCESS"));
            this.$refs.MomTable?.query();
            this.drawer = false;
          });
      } else {
        this.$axios
          .post(`${ApiConstant.PREFIX_CORE}/api/print/destination`, data)
          .then((res) => {
            this.$message.success(this.$t("ADD_SUCCESS"));
            this.$refs.MomTable?.query();
            this.drawer = false;
          });
      }
    },
    delaySave: debounce(function () {
      this.save();
    }, Settings.DO_FUNC_DELAY_TIME),
    handleSave(ref) {
      this.$refs[ref].validate((valid) => {
        if (valid) {
          this.delaySave();
        }
      });
    },
    // 对话框取消
    handleCancel() {
      this.$refs.formRef.resetFields();
      // 断开与ELabel连接
      if (this.eLabel) {
        this.eLabel.disconnect();
      }
      this.eLabel = null;
      this.printerList = [];
      this.drawer = false;
    },
    // 增加条件
    addSubForm(index) {
      this.formData.conditions.push({
        paramName: "",
        paramValue: "",
      });
    },
    // 删除条件
    deleteSubForm(index) {
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okType: "warning",
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.formData.conditions.splice(index, 1);
          if (this.formData.conditions.length === 0) {
            this.formData.conditions = [
              {
                paramName: "",
                paramValue: "",
              },
            ];
          }
        },
      });
    },
    handleConnect() {
      // 如果未创建则新增
      if (!this.eLabel) {
        this.eLabel = new ELabel();
        this.eLabel.onData = (res) => {
          const obj = JSON.parse(res);
          // eslint-disable-next-line
          switch (obj.CMD) {
            case this.eLabel.ACTIONS.GETPRINTERLIST:
              this.printerList = obj.DATA.map((v) => {
                return {
                  label: v,
                  value: v,
                };
              });
              break;
            case this.eLabel.ACTIONS.ERROR:
              this.$message.error(obj.MSG);
              break;
          }
        };
        this.eLabel.onConnectSuccess = () => {
          this.$message.success(this.$t("CONNECT_SUCCESS"));
        };
      }
      // 建立连接
      this.eLabel.ipAddress = this.formData.serverIp;
      this.eLabel.connect(this.$t("PRINTER_CONNECTION_FAILED"));
      // 获取打印机列表
      setTimeout(this.eLabel.getPrinters, 500);
    },
  },
};
</script>
<style lang="less" scoped>
.line {
  width: 100%;
  height: 1px;
  border-bottom: 1px dashed #999;
}
.mt-10 {
  margin-top: 10px;
}
.btns {
  position: relative;
  display: inline-block;
  min-width: 71px;
  text-align: right;
  .anticon-delete {
    position: absolute;
    color: #1890ff;
    font-size: 18px !important;
    cursor: pointer;
    top: 10px;
    right: 35px;
  }
  .anticon-plus {
    position: absolute;
    color: #1890ff;
    font-size: 18px !important;
    cursor: pointer;
    top: 10px;
    right: 0;
  }
}
</style>
