<template>
  <div class="box-main">
    <MomTable
      ref="MomTable"
      row-key="id"
      :row-selection="rowSelection"
      :columns="tableColumns"
      :data-source="tableData"
      :query-param="search"
      :query-param-item="formItemConfig"
      :action-buttons="actionButtons"
      :page.sync="page"
      :total="total"
      @copy="handleCopy"
      @edit="handleEdit"
      @delete="handleDelete"
      @search="searchPageData"
    >
      <div slot="toolbar">
        <!-- 新增 -->
        <a-button
          v-if="hasAuth('DYNAMIC_SUB_ATTRIBUTE:ADD')"
          @click="handleOpenDrawer('add')"
        >
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <a-button
          v-if="hasAuth('DYNAMIC_SUB_ATTRIBUTE:BATCH_DELETE')"
          type="danger"
          icon="delete"
          @click="handDelete"
        >
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </div>
      <template slot="condition" slot-scope="text, record">
        <span v-for="item in record.conditions" :key="item.id">
          [{{ paramMap[item.paramName] }}:{{ item.paramValue }}]
        </span>
      </template>
      <template slot="result" slot-scope="text, record">
        <span v-for="item in record.results" :key="item.id">
          [{{ paramMap[item.paramName] || item.paramName }}:{{
            item.paramValue
          }}]
        </span>
      </template>
    </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_ID')" prop="labelCode">
            <i-table-select
              v-model="formData.labelCode"
              :options-props="{ label: 'labelCode', value: 'labelCode' }"
              :options="formItemConfig.labelCode.options"
            />
          </a-form-model-item>
          <!-- 条件 -->
          <a-form-model-item :label="$t('CONDITION')" class="mb-0">
            <div
              class="subFormRef"
              style="max-height: 200px; overflow-x: hidden; overflow-y: auto"
            >
              <div
                v-for="(condition, index) in formData.conditions"
                :key="index"
                class="condition_item"
              >
                <a-form-model :ref="`subFormRef${index}`" :model="condition">
                  <a-row type="flex" style="margin-bottom: 0; margin-left: 0">
                    <a-col :span="8">
                      <a-form-model-item
                        prop="paramName"
                        style="margin-bottom: 0"
                      >
                        <i-table-select
                          v-model="condition.paramName"
                          :options="paramNames"
                        />
                      </a-form-model-item>
                    </a-col>
                    <a-col :span="8" :offset="1">
                      <a-form-model-item
                        prop="paramValue"
                        style="margin-bottom: 0"
                      >
                        <!-- 请输入限制值 -->
                        <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="deleteConditionForm(index)"
                      />
                      <a-icon
                        v-show="index === formData.conditions.length - 1"
                        type="plus"
                        @click="addConditionForm(index)"
                      />
                    </a-col>
                  </a-row>
                </a-form-model>
              </div>
            </div>
          </a-form-model-item>
          <!-- 结果 -->
          <a-form-model-item :label="$t('RESULT')">
            <div
              class="subFormRef"
              style="width: 100%; max-height: 200px; overflow-y: auto"
            >
              <div v-for="(result, index) in formData.results" :key="index">
                <a-form-model
                  :ref="`subFormRef${index}`"
                  label-position="top"
                  :model="result"
                  size="medium"
                >
                  <a-row type="flex" style="width: 100%">
                    <a-col :span="8">
                      <a-form-model-item prop="paramName">
                        <i-table-select
                          v-model="result.paramName"
                          :options="paramNames"
                        />
                      </a-form-model-item>
                    </a-col>
                    <a-col :span="8" :offset="1">
                      <a-form-model-item prop="paramValue">
                        <!-- 请输入限制值 -->
                        <a-input
                          v-model="result.paramValue"
                          :placeholder="$t('INPUT_CONDITIONS')"
                          :disabled="!result.paramName"
                        />
                      </a-form-model-item>
                    </a-col>
                    <a-col :span="5" class="btns">
                      <a-icon
                        v-show="formData.results.length >= 1"
                        type="delete"
                        @click="deleteResultForm(index)"
                      />
                      <a-icon
                        v-show="index === formData.results.length - 1"
                        type="plus"
                        @click="addResultForm(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 { PS_SYSTEM, PS_PARAM } from "../constant";

export default {
  name: "LabDynaAttr",
  components: {
    MegaDrawer,
    Icon,
  },
  data() {
    return {
      drawerTitle: "",
      sortParams: null,
      // 查询表单数据
      search: {
        labelCode: null,
      },
      paramNames: [],
      tableData: [],
      total: 0,
      page: 1,
      drawer: false,
      drawerType: "add",
      formData: {},
      actionButtons: [
        this.hasAuth(`DYNAMIC_SUB_ATTRIBUTE:COPY`) && "copy",
        this.hasAuth(`DYNAMIC_SUB_ATTRIBUTE:EDIT`) && "edit",
        this.hasAuth(`DYNAMIC_SUB_ATTRIBUTE:DELETE`) && "delete",
      ],
      selectedRowKeys: [],
    };
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    rules() {
      return {
        labelCode: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
      };
    },
    // 参数key=>value对象
    paramMap() {
      const obj = {};
      this.paramNames.forEach((item) => {
        obj[item.value] = item.label;
      });
      return obj;
    },
    formItemConfig() {
      // 查询表单配置
      return this.$observable("formItemConfig", {
        // 标签号
        labelCode: {
          label: () => this.$t("LABEL_ID"),
          itemType: "select",
          options: [],
          optionsProps: {
            label: "labelCode",
            value: "labelCode",
          },
        },
      });
    },
    // 表格配置
    tableColumns() {
      return [
        // 标签号
        {
          dataIndex: "labelCode",
          title: () => this.$t("LABEL_ID"),
          width: 260,
        },
        // 条件
        {
          dataIndex: "condition",
          ellipsis: true,
          title: () => this.$t("CONDITION"),
          scopedSlots: { customRender: "condition" },
          minWidth: 200,
          sorter: false,
        },
        // 结果
        {
          dataIndex: "result",
          ellipsis: true,
          title: () => this.$t("RESULT"),
          scopedSlots: { customRender: "result" },
          minWidth: 330,
          sorter: false,
        },
        // 更新人员
        {
          dataIndex: "updateBy",
          title: () => this.$t("UPDATE_BY"),
          width: 120,
          sorter: false,
        },
        // 更新时间
        {
          dataIndex: "updateTime",
          title: () => this.$t("UPDATE_TIME"),
          width: 200,
          sorter: false,
        },
      ];
    },
  },
  activated() {
    // 标签属性页会跳转过来
    if (this.search.labelCode !== this.$route.query.labelCode) {
      this.$set(this.search, "labelCode", this.$route.query.labelCode);
      const req = this.getSearchParams();
      this.searchPageData({ ...req, ...this.sortParams });
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    // 初始化选项
    init() {
      // 获取参数
      this.getDictByCode(PS_PARAM).then((res) => {
        this.paramNames = res.data.data;
      });
      // 获取所有标签
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/print/label/all`)
        .then((res) => {
          this.formItemConfig.labelCode.options = uniqBy(
            res.data.data,
            "labelCode"
          );
        });
    },
    // 分页查询
    searchPageData(data) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/print/dyna-attribute/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: "",
            },
          ];
        }
        if (!this.formData.results || this.formData.results.length === 0) {
          this.formData.results = [
            {
              paramName: "",
              paramValue: "",
            },
          ];
        }
      } else if (type === "add") {
        this.drawerTitle = this.$t("ADD");
        this.$set(this, "formData", {
          labelCode: this.search.labelCode,
          conditions: [
            {
              paramName: "",
              paramValue: "",
            },
          ],
          results: [
            {
              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/dyna-attribute/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/dyna-attribute/${row.id}`
            )
            .then((res) => {
              this.$refs.MomTable?.query();
              this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
            });
        },
      });
    },
    // 保存&修改 防抖
    save() {
      // 将未选择条件的子数据删除
      const data = { ...this.formData };
      data.conditions = data.conditions.filter((item) => item.paramName);
      data.results = data.results.filter((item) => item.paramName);
      // 组请求
      if (this.drawerType === "edit") {
        this.$axios
          .put(`${ApiConstant.PREFIX_CORE}/api/print/dyna-attribute`, 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/dyna-attribute`, 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.clearValidate();
      this.$refs.formRef.resetFields();
      this.drawer = false;
    },
    // 增加条件
    addConditionForm(index) {
      this.formData.conditions.push({
        paramName: "",
        paramValue: "",
      });
    },
    // 删除条件
    deleteConditionForm(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: "",
              },
            ];
          }
        },
      });
    },
    // 增加条件
    addResultForm(index) {
      this.formData.results.push({
        paramName: "",
        paramValue: "",
      });
    },
    // 删除条件
    deleteResultForm(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.results.splice(index, 1);
          this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
          if (this.formData.results.length === 0) {
            this.formData.results = [
              {
                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;
}
.subFormRef {
  .condition_item {
    width: 100%;
  }
}
</style>
