<template>
  <div class="box-main">
    <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'
          )
      "
    >
      <a-row slot="toolbar">
        <a-button
          v-if="hasAuth('LABEL_DESIGNATION:ADD')"
          @click="handleOpenDrawer('add')"
        >
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <a-button
          v-if="hasAuth('LABEL_DESIGNATION:BATCH_DELETE')"
          type="danger"
          icon="delete"
          @click="handDelete"
        >
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </a-row>
      <template slot="labelType" slot-scope="text, record">
        <span>{{ formatData(labelTypeList, record.labelType) }}</span>
      </template>
      <template slot="condition" slot-scope="text, record">
        <span v-for="item in record.conditions" :key="item.id">
          [{{ paramMap[item.paramName] }}:{{ item.paramValue }}]
        </span>
        <span>{{ record.condition }}</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>
    <MegaDrawer
      :visible.sync="drawer"
      :title="drawerTitle"
      width="520"
      @close="handleCancel"
    >
      <div slot="main">
        <a-form-model
          ref="formRef"
          class="i-form"
          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>
          <!-- 标签号 -->
          <a-form-model-item :label="$t('LABEL_ID')" prop="labelCode">
            <i-table-select
              v-model="formData.labelCode"
              :options="selectData.formLabelIds"
              :options-props="{ label: 'labelCode', value: 'labelCode' }"
            />
          </a-form-model-item>
          <!-- 权重 -->
          <a-form-model-item :label="$t('WEIGHT')">
            <a-input-number
              v-model="formData.weight"
              :min="0"
              style="width: 100%"
            />
          </a-form-model-item>
          <!-- 条件 -->
          <a-form-model-item :label="$t('CONDITION')">
            <div style="width: 100%; max-height: 300px; overflow-y: auto">
              <div
                v-for="(condition, index) in formData.conditions"
                :key="index"
              >
                <a-form-model
                  :ref="`subFormRef${index}`"
                  :model="condition"
                  :label-col="{ span: 6 }"
                  :wrapper-col="{ span: 18 }"
                >
                  <a-row type="flex" style="width: 100%">
                    <a-col :span="8">
                      <a-form-model-item prop="paramName">
                        <a-select
                          v-model="condition.paramName"
                          show-search
                          :filter-option="filterOption"
                        >
                          <a-select-option
                            v-for="item in paramNames"
                            :key="item.value"
                          >
                            {{ item.label }}
                          </a-select-option>
                        </a-select>
                      </a-form-model-item>
                    </a-col>
                    <a-col :span="8" :offset="1">
                      <a-form-model-item prop="paramValue">
                        <!-- 请输出限制值 -->
                        <a-input
                          v-model="condition.paramValue"
                          :placeholder="$t('INPUT_CONDITIONS')"
                          :disabled="!condition.paramName"
                        />
                      </a-form-model-item>
                    </a-col>
                    <a-col :span="5" class="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 uniqBy from "lodash/uniqBy";
import { Drawer as MegaDrawer, Icon } from "@mega-design/ui-vue";
import Settings from "@/config/settings";
import ApiConstant from "@/api/ApiConstant";
import { LABEL_STATUS_PASS } from "../constant";

export default {
  name: "LabSett",
  components: {
    MegaDrawer,
    Icon,
  },
  data() {
    return {
      drawerTitle: "",
      sortParams: null,
      // 查询表单数据
      queryForm: {
        labelType: null,
        labelCode: null,
      },
      paramNames: [],
      tableData: [],
      selectData: {
        labelIds: [], // 原始标签号集合
        formLabelIds: [], // 根据标签类型筛选后标签号集合
      },
      total: 0,
      page: 1,
      stateList: [],
      drawer: false,
      drawerType: "add",
      formData: {},
      actionButtons: [
        this.hasAuth(`LABEL_DESIGNATION:COPY`) && "copy",
        this.hasAuth(`LABEL_DESIGNATION:EDIT`) && "edit",
        this.hasAuth(`LABEL_DESIGNATION: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",
          },
        ],
        labelCode: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            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",
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
        },
        // 标签号
        labelCode: {
          label: () => this.$t("LABEL_ID"),
          itemType: "select",
          options: [],
          optionsProps: {
            label: "labelCode",
            value: "labelCode",
          },
        },
      });
    },
    // 表格配置
    tableColumns() {
      return [
        // 标签类型
        {
          dataIndex: "labelType",
          title: () => this.$t("LABEL_TYPE"),
          scopedSlots: { customRender: "labelType" },
          width: 200,
        },
        // 标签号
        {
          dataIndex: "labelCode",
          title: () => this.$t("LABEL_ID"),
          width: 200,
        },
        // 权重
        {
          dataIndex: "weight",
          title: () => this.$t("WEIGHT"),
          width: 180,
        },
        // 条件
        {
          dataIndex: "condition",
          title: () => this.$t("CONDITION"),
          scopedSlots: { customRender: "condition" },
          sorter: false,
          minWidth: 300,
        },
        {
          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,
        },
      ];
    },
  },
  watch: {
    "queryForm.labelType": function (newVal, oldVal) {
      if (newVal) {
        this.queryForm.labelCode = "";
        this.queryFormItem.labelCode.options = uniqBy(
          this.selectData.labelIds.filter((item) => {
            return item.labelType === newVal;
          }),
          "labelCode"
        );
      } else {
        this.queryFormItem.labelCode.options = uniqBy(
          this.selectData.labelIds,
          "labelCode"
        );
      }
    },
    "formData.labelType": function (newVal, oldVal) {
      if (newVal) {
        this.selectData.formLabelIds = uniqBy(
          this.selectData.labelIds.filter((item) => {
            return item.labelType === newVal;
          }),
          "labelCode"
        );
      } else {
        this.selectData.formLabelIds = uniqBy(
          this.selectData.labelIds,
          "labelCode"
        );
      }
      // 如果已选择的标签号不在选项中，则置空
      const res = this.selectData.formLabelIds.filter((item) => {
        return item.labelCode === this.formData.labelCode;
      });
      if (res.length === 0) {
        this.formData.labelCode = "";
      }
    },
  },
  mounted() {},
  methods: {
    filterOption(input, option) {
      return option.componentOptions.children[0].text
        .toLowerCase()
        .includes(input.toLowerCase());
    },
    formatData(data, status) {
      const result = data.find((item) => item.value === status?.toString());
      return result ? result.label : "";
    },
    // 初始化选项
    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 || [];
      });
      // 获取所有标签
      this.getAllLabels();
    },
    // 启用、禁用
    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/setting/enable/${id}/${status}`
            )
            .then((res) => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 分页查询
    searchPageData(data) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/print/setting/search`, {
          params: data,
        })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = res.data.data.total;
        });
    },
    // 编辑
    handleEdit(row) {
      this.drawerTitle = this.$t("EDIT");
      this.handleOpenDrawer("edit", row);
    },
    // 复制按钮点击事件
    handleCopy(row) {
      this.drawerTitle = this.$t("COPY");
      this.handleOpenDrawer("copy", 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.drawerTitle = this.$t("ADD");
        this.$set(this, "formData", {
          labelType: this.queryForm.labelType,
          labelCode: this.queryForm.labelCode,
          weight: 0,
          conditions: [
            {
              paramName: "",
              paramValue: "",
            },
          ],
        });
      }
      // 获取所有标签
      this.getAllLabels();
    },
    getAllLabels() {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/print/label/all`, {
          params: { labelStatus: LABEL_STATUS_PASS },
        })
        .then((res) => {
          this.selectData.labelIds = res.data.data;
          this.queryFormItem.labelCode.options = uniqBy(
            res.data.data,
            "labelCode"
          );
        });
    },
    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/setting/batch-delete`,
                {
                  params: {
                    ids: this.selectedRowKeys.join(","),
                  },
                }
              )
              .then((res) => {
                this.$refs.MomTable?.query();
                this.$message.success(this.$t("EDIT_SUCCESS"));
                // 获取所有标签
                this.getAllLabels();
              });
          },
        });
      } 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/setting/${row.id}`)
            .then((res) => {
              this.$refs.MomTable?.query();
              this.$message.success(this.$t("EDIT_SUCCESS"));
              // 获取所有标签
              this.getAllLabels();
            });
        },
      });
    },
    // 保存&修改 防抖
    save() {
      // 将未选择条件的子数据删除
      const data = { ...this.formData };
      data.conditions = data.conditions.filter((item) => item.paramName);
      // 组请求
      if (this.drawerType === "edit") {
        this.$axios
          .put(`${ApiConstant.PREFIX_CORE}/api/print/setting`, 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/setting`, 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();
      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);
          this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
          if (this.formData.conditions.length === 0) {
            this.formData.conditions = [
              {
                paramName: "",
                paramValue: "",
              },
            ];
          }
        },
      });
    },
  },
};
</script>
<style lang="less" scoped>
.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;
  }
}

.button-top-table {
  margin-bottom: 12px;
}
</style>
