<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"
        @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('ADVANCED_PIPELINE:ADD')" @click="handleAdd">
            <a-icon type="plus" />
            {{ $t("ADD") }}
          </a-button>
          <a-button
            v-if="hasAuth('ADVANCED_PIPELINE: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>
        <template slot="enableFlag" slot-scope="text">
          <span :class="text === 'Y' ? 'text-success' : 'text-error'">
            {{ getAttrValue(stateList, text) }}
          </span>
        </template>
      </MomTable>
    </div>
    <MegaDrawer
      :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_ID')" prop="labelCode">
            <a-select
              v-model="formData.labelCode"
              :placeholder="$t('PLACESELECT')"
              @change="handChange"
            >
              <a-select-option
                v-for="(item, index) in queryFormItem.labelCode.options"
                :key="index"
                :value="item.labelCode"
              >
                {{ item.labelCode }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <!-- 属性名 -->
          <a-form-model-item :label="$t('ATTRIBUTE_NAME')" prop="paramName">
            <i-table-select
              v-model="formData.paramName"
              :options="selectData.parameterNames"
              :options-props="{
                label: 'paramName',
                value: 'paramName',
              }"
              @change="parameterChange"
            />
          </a-form-model-item>
          <!-- 厂区 -->
          <a-form-model-item :label="$t('PLANT_AREA')" prop="siteCode">
            <a-input v-model="formData.siteCode" />
          </a-form-model-item>
          <!-- 起始值 -->
          <a-form-model-item :label="$t('START_VALUE')" prop="rangeFrom">
            <a-input-number
              v-model="formData.rangeFrom"
              :min="1"
              style="width: 100%"
              :max="formData.rangeTo ? formData.rangeTo : rangeMax"
            />
          </a-form-model-item>
          <!-- 结束值 -->
          <a-form-model-item :label="$t('END_VALUE')" prop="rangeTo">
            <a-input-number
              v-model="formData.rangeTo"
              style="width: 100%"
              :min="formData.rangeFrom ? formData.rangeFrom : 1"
              :max="rangeMax"
            />
          </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";

export default {
  name: "LabCounRange",
  components: {
    MegaDrawer,
    Icon,
  },
  data() {
    return {
      drawerTitle: "",
      // 查询sort
      sortParams: null,
      // 查询表单数据
      queryForm: {
        labelCode: null,
        paramName: null,
      },
      selectData: {
        parameterNames: [],
      },
      tableData: [],
      total: 0,
      page: 1,
      drawer: false,
      drawerType: "add",
      formData: {},
      stateList: [],
      rangeMax: 99999, // 流水码区间最大值
      actionButtons: [
        this.hasAuth(`ADVANCED_PIPELINE:COPY`) && "copy",
        this.hasAuth(`ADVANCED_PIPELINE:EDIT`) && "edit",
        this.hasAuth(`ADVANCED_PIPELINE: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",
          },
        ],
        paramName: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        siteCode: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        rangeFrom: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        rangeTo: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
      };
    },
    // 表格配置
    tableColumns() {
      return [
        // 标签号
        {
          dataIndex: "labelCode",
          title: () => this.$t("LABEL_ID"),
          width: 200,
        },
        // 属性名
        {
          dataIndex: "paramName",
          title: () => this.$t("ATTRIBUTE_NAME"),
          width: 200,
          sorter: false,
        },
        // 厂区
        {
          dataIndex: "siteCode",
          title: () => this.$t("PLANT_AREA"),
          width: 200,
        },
        // 起始值
        {
          dataIndex: "rangeFrom",
          title: () => this.$t("START_VALUE"),
          width: 200,
          sorter: false,
        },
        // 结束值
        {
          dataIndex: "rangeTo",
          title: () => this.$t("END_VALUE"),
          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,
        },
      ];
    },
    queryFormItem() {
      return this.$observable("queryFormItem", {
        // 标签号
        labelCode: {
          label: () => this.$t("LABEL_ID"),
          itemType: "select",
          options: [],
          optionsProps: {
            label: "labelCode",
            value: "labelCode",
          },
        },
        // 属性名
        paramName: {
          label: () => this.$t("ATTRIBUTE_NAME"),
          itemType: "select",
          options: [],
          optionsProps: {
            label: "paramName",
            value: "paramName",
          },
        },
      });
    },
  },
  watch: {
    // 查询中标签号变化时，查询新的属性
    "queryForm.labelCode": function (newVal, oldVal) {
      this.queryFormItem.paramName.options = [];
      if (newVal) {
        this.$axios
          .get(
            `${ApiConstant.PREFIX_CORE}/api/print/attribute/label-id/${newVal}`
          )
          .then((res) => {
            this.queryFormItem.paramName.options = res.data.data;
          });
      }
    },
  },
  activated() {
    // 标签属性页会跳转过来
    if (
      this.$route.query.labelCode !== this.queryForm.labelCode ||
      this.$route.query.paramName !== this.queryForm.paramName
    ) {
      this.$set(this.queryForm, "labelCode", this.$route.query.labelId);
      this.$set(this.queryForm, "paramName", this.$route.query.paramName);
      const params = {
        page: this.page,
        size: this.$store.state.pagination.pageSize,
        ...this.queryForm,
        ...this.sortParams,
      };
      this.searchPageData(params);
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    handChange(val) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/print/attribute/label-id/${val}`)
        .then((res) => {
          this.selectData.parameterNames = res.data.data;
          // 如果已选择的标签号不在选项中，则置空
          const data = this.selectData.parameterNames.filter((item) => {
            return item.paramName === this.formData.paramName;
          });
          if (data.length === 0) {
            this.formData.paramName = "";
          }
        });
    },
    // 启用、禁用
    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/count/enable/${id}/${status}`
            )
            .then((res) => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    formatData(data, status) {
      const result = data.find((item) => item.value === status?.toString());
      return result ? result.label : "";
    },
    // 查后台分页查询
    searchPageData(data) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/print/count/search`, {
          params: data,
        })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = res.data.data.total;
        });
    },
    // 初始化选项
    init() {
      // 获取所有标签
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/print/label/all`)
        .then((res) => {
          this.queryFormItem.labelCode.options = uniqBy(
            res.data.data,
            "labelCode"
          );
        });
      this.getDictByCode("DIC:COMMON:ENABLE_FLAG").then((res) => {
        this.stateList = res?.data?.data || [];
      });
    },
    // 点击新增
    handleAdd() {
      this.drawer = true;
      this.$set(this, "formData", {
        labelCode: "",
        paramName: "",
        siteCode: "",
        rangeFrom: 1,
        rangeTo: 999,
      });
      this.drawerTitle = this.$t("ADD");
      this.handleOpenDrawer("add");
      // 根据选择获取区间最大值
      setTimeout(() => {
        this.parameterChange(this.queryForm.paramName, false);
      }, 500);
    },
    // 复制
    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", { ...row });
        this.$axios
          .get(
            `${ApiConstant.PREFIX_CORE}/api/print/attribute/label-id/${this.formData.labelCode}`
          )
          .then((res) => {
            this.selectData.parameterNames = res.data.data;
            // 如果已选择的标签号不在选项中，则置空
            const data = this.selectData.parameterNames.filter((item) => {
              return item.paramName === this.formData.paramName;
            });
            if (data.length === 0) {
              this.formData.paramName = "";
            }
          });
        // 根据选择获取区间最大值
        setTimeout(() => {
          this.parameterChange(row.paramName, true);
        }, 500);
      } else if (type === "add") {
        this.$set(this, "formData", {
          labelCode: "",
          paramName: "",
          siteCode: "",
          rangeFrom: 1,
          rangeTo: 999,
        });
        // 根据选择获取区间最大值
        setTimeout(() => {
          this.parameterChange(this.queryForm.paramName, false);
        }, 500);
      }
    },
    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/count/batch-delete`,
                {
                  params: {
                    ids: this.selectedRowKeys.join(","),
                  },
                }
              )
              .then((res) => {
                this.$refs.MomTable?.query();
                this.$message.success(this.$t("DELETE_SUCCESS"));
              });
          },
        });
      } 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/count/${row.id}`)
            .then((res) => {
              this.$refs.MomTable?.query();
              this.$message.success(this.$t("DELETE_SUCCESS"));
            });
        },
      });
    },
    // 保存&修改 防抖
    save() {
      if (this.drawerType === "copy") {
        delete this.formData.id;
      }
      // 组请求
      if (this.drawerType === "edit") {
        this.$axios
          .put(`${ApiConstant.PREFIX_CORE}/api/print/count`, this.formData)
          .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/count`, this.formData)
          .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;
      this.formatData.labelCode = "";
    },
    // 选择属性后，重置区间
    parameterChange(val, skipSetRange) {
      // 未选择或置空时直接返回
      if (!val) {
        return;
      }
      const obj = this.selectData.parameterNames.find((item) => {
        return item.paramName === val;
      });
      if (!obj) {
        return;
      }
      this.rangeMax = obj.max;
      // 设置区间默认值
      if (!skipSetRange) {
        this.formData.rangeFrom = 1;
        this.formData.rangeTo = obj.max;
      }
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.drawer-footer {
  position: absolute;
  bottom: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}
</style>
