<template>
  <div>
    <MomTable
      ref="MomTable"
      row-key="id"
      :row-selection="rowSelection"
      :query-param="queryParam"
      :query-param-item="queryParamItem"
      :columns="columns"
      :data-source="dataSource"
      :total="total"
      :page.sync="page"
      :action-buttons="actionButtons"
      :mega-extend="{
        rowIndex: false,
      }"
      :show-enable-flag="hasAuth('EPMS:SCADA_BOX:ENABLED')"
      :enable-flag="enableFlag"
      @search="search"
      @edit="handleEdit"
      @delete="handleDelete"
      @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" class="button-top-table">
        <a-button v-if="hasAuth('EPMS:SCADA_BOX:ADD')" @click="handleAdd">
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <MomEditButton
          v-if="hasAuth('EPMS:SCADA_BOX:EDIT')"
          :disabled="selectedRowKeys.length !== 1"
          :keys="selectedRowKeys"
          :data="dataSource"
          @edit="handleEdit"
        />
        <span style="margin: 0 8px">
          <MomImportButton object-name="IOT_BOX" />
        </span>
        <a-button
          v-if="hasAuth('EPMS:SCADA_BOX:BATCH_ENABLED')"
          :disabled="selectedRowKeys.length === 0"
          @click="
            handleBatchDisabled(
              'Y',
              'ENABLED',
              'ENABLED_DATAS_INFO',
              'ENABLE_SUCCESS'
            )
          "
        >
          <i class="iconfont icon-queren text-success"></i>
          {{ $t("BATCH_ENABLED") }}
        </a-button>
        <a-button
          v-if="hasAuth('EPMS:SCADA_BOX:BATCH_DISABLED')"
          :disabled="selectedRowKeys.length === 0"
          @click="
            handleBatchDisabled(
              'N',
              'DISABLED',
              'DISABLED_DATAS_INFO',
              'DISABLE_SUCCESS'
            )
          "
        >
          <i class="iconfont icon-Group- text-error"></i>
          {{ $t("BATCH_DISABLED") }}
        </a-button>
        <a-button
          v-if="hasAuth('EPMS:SCADA_BOX:BATCH_DELETE')"
          :disabled="selectedRowKeys.length === 0"
          type="danger"
          ghost
          @click="handleBatchDelete"
        >
          <a-icon type="delete" />
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </div>
      <template slot="enableFlag" slot-scope="text, record">
        <span class="status-box" :class="'able' + text">{{
          formatData(stateList, record.enableFlag)
        }}</span>
      </template>
    </MomTable>
    <MegaDrawer
      width="520"
      :title="
        form.id ? $t('SCADA_BOX') + $t('EDIT') : $t('SCADA_BOX') + $t('ADD')
      "
      :visible="drawerVisible"
      :confirm-loading="confirmLoading"
      @close="handleCancel"
      @cancel="handleCancel"
      @ok="handleSave"
    >
      <a-form-model
        slot="main"
        ref="ruleForm"
        layout="vertical"
        :model="form"
        :rules="rules"
      >
        <a-form-model-item :label="$t('IOT_BOX_CODE')" prop="boxCode">
          <a-input
            v-model="form.boxCode"
            :placeholder="$t('PLACEENTER')"
            @change="form.boxCode = form.boxCode.slice(0, 50).trim()"
          />
        </a-form-model-item>
        <a-form-model-item :label="$t('IOT_BOX_NAME')" prop="boxName">
          <a-input
            v-model="form.boxName"
            :placeholder="$t('PLACEENTER')"
            @change="form.boxName = form.boxName.slice(0, 50).trim()"
          />
        </a-form-model-item>
      </a-form-model>
    </MegaDrawer>
  </div>
</template>

<script>
import { uniqBy } from "lodash";
import { Drawer as MegaDrawer } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import MomEditButton from "@/components/MomEditButton";
import MomImportButton from "@/components/MomImportButton";

export default {
  components: { MegaDrawer, MomEditButton, MomImportButton },
  data() {
    return {
      enableFlag: {
        prop: "enableFlag",
        defaultValue: "Y",
        enableValue: "Y",
        options: [
          { label: "全部", value: "" },
          { label: "启用", value: "Y" },
          { label: "禁用", value: "N" },
        ],
        optionsProps: {
          label: "label",
          value: "value",
        },
      },
      loading: false, // 表格loading
      confirmLoading: false,
      // 查询的表单的配置项
      queryParam: {
        boxCode: "",
        boxName: "",
      },
      columns: [
        {
          dataIndex: "boxCode", // 分类编码
          title: () => this.$t("IOT_BOX_CODE"),
          sorter: false,
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "boxName", // 分类名称
          title: () => this.$t("IOT_BOX_NAME"),
          sorter: false,
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "enableFlag",
          align: "left",
          sorter: false,
          ellipsis: true,
          width: 200,
          title: () => this.$t("STATUS"), // 状态
          scopedSlots: { customRender: "enableFlag" },
        },
        {
          dataIndex: "updateBy", // 更新人员
          sorter: false,
          ellipsis: true,
          title: () => this.$t("UPDATE_BY"),
        },
        {
          dataIndex: "updateTime", // 更新时间
          ellipsis: true,
          title: () => this.$t("UPDATE_TIME"),
        },
      ],
      total: 0,
      page: 1,
      actionButtons: [
        this.hasAuth("EPMS:SCADA_BOX:EDIT") && "edit",
        this.hasAuth("EPMS:SCADA_BOX:DELETE") && "delete",
      ],
      dataSource: [],
      drawerVisible: false,
      form: {
        id: null,
        boxCode: "",
        boxName: "",
      },
      stateList: [],
      selectedRowKeys: [], // 选中行 key 数据
      selectedRows: [], // 选中行 数据
    };
  },
  computed: {
    rules() {
      return {
        boxCode: [
          {
            required: true,
            max: 50,
            message: this.$t("PLACEENTER") + 50 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        boxName: [
          {
            required: true,
            max: 50,
            message: this.$t("PLACEENTER") + 50 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
      };
    },
    // 表格搜索配置
    queryParamItem() {
      return this.$observable("queryParamItem", {
        boxCode: {
          label: () => this.$t("IOT_BOX_CODE"),
        },
        boxName: {
          label: () => this.$t("IOT_BOX_NAME"),
        },
      });
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
          if (this.selectedRowKeys.length) {
            this.selectedRows = uniqBy(this.selectedRows.concat(selectedRows));
          } else {
            this.selectedRows = selectedRows;
          }
        },
      };
    },
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      return Promise.all([
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:ENABLE_STATUS`
        ), // 禁用启用
      ]).then(([enableStatus]) => {
        this.stateList = enableStatus.data?.data;
      });
    },
    formatData(data, status) {
      const result = data.find((item) => item.value === status.toString());
      return result ? result.label : "";
    },
    search(params) {
      this.selectedRowKeys = [];
      this.selectedRows = [];
      const searchParams = {
        ...params,
      };
      this.loading = true;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/iot/iot-box/search`, {
          params: searchParams,
        })
        .then((res) => {
          this.dataSource = res.data.data.records;
          this.total = res.data.data.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    handleEdit({ id, boxCode, boxName }) {
      this.form = {
        id,
        boxCode,
        boxName,
      };
      this.drawerVisible = true;
    },
    handleAdd() {
      this.form.id = null;
      this.form.boxCode = "";
      this.form.boxName = "";
      this.drawerVisible = true;
    },
    handleDelete(row) {
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okText: this.$t("DELETE"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios
            .delete(`${ApiConstant.PREFIX_CORE}/api/epm/iot/iot-box/${row.id}`)
            .then(() => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    handleBatchDelete() {
      if (this.selectedRowKeys.length < 1) {
        this.$message.warning(this.$t("SELECT_ONE_DATA"));
        return;
      }
      const params = {
        ids: this.selectedRowKeys,
      };
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okText: this.$t("DELETE"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios
            .delete(
              `${ApiConstant.PREFIX_CORE}/api/epm/iot/iot-box/delete-batch`,
              {
                data: params,
              }
            )
            .then(() => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.selectedRowKeys = [];
              this.selectedRows = [];
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    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/epm/iot/iot-box/enable/${id}/${status}`
            )
            .then((res) => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    handleBatchDisabled(status, titleText, contentText, tips) {
      if (this.selectedRowKeys.length < 1) {
        this.$message.warning(this.$t("SELECT_ONE_DATA"));
        return;
      }
      const tempArr = [];
      this.dataSource.forEach((item) => {
        this.selectedRowKeys.forEach((ele) => {
          if (item.id === ele && item.enableFlag !== status) {
            tempArr.push(item);
          }
        });
      });
      if (tempArr.length < 1) {
        const content =
          status === "Y" ? "NO_DATA_TO_ENABLE" : "NO_DATA_TO_DISABLE";
        this.$confirm({
          title: this.$t(titleText),
          content: this.$t(content),
          okText: this.$t("CONFIRM"),
          cancelText: this.$t("CANCEL"),
          centered: false,
          icon: "exclamation-circle",
          onOk: () => {},
        });
        return;
      }
      const params = {
        status,
        ids: this.selectedRowKeys,
      };
      this.$confirm({
        title: this.$t(titleText),
        content: this.$t(contentText),
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "exclamation-circle",
        onOk: () => {
          this.$axios
            .put(
              `${ApiConstant.PREFIX_CORE}/api/epm/iot/iot-box/enable-batch`,
              params
            )
            .then(() => {
              this.$message.success(this.$t(tips));
              this.selectedRowKeys = [];
              this.selectedRows = [];
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    handleSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          if (this.form.id) {
            this.$axios
              .put(`${ApiConstant.PREFIX_CORE}/api/epm/iot/iot-box`, this.form)
              .then(() => {
                this.$message.success(this.$t("EDIT_SUCCESS"));
                this.$refs.MomTable?.query();
                this.handleCancel();
              })
              .catch((e) => {
                this.confirmLoading = false;
              });
          } else {
            this.$axios
              .post(`${ApiConstant.PREFIX_CORE}/api/epm/iot/iot-box`, this.form)
              .then(() => {
                this.$message.success(this.$t("ADD_SUCCESS"));
                this.$refs.MomTable?.query();
                this.handleCancel();
              })
              .catch((e) => {
                this.confirmLoading = false;
              });
          }
        }
      });
    },
    handleCancel() {
      this.confirmLoading = false;
      this.$refs.ruleForm.clearValidate();
      this.drawerVisible = false;
    },
  },
};
</script>
<style lang="less" scoped>
@import "@/assets/css/status_epms.less";
/deep/ .error-type .ant-form-item-children {
  display: flex;
}
.tips-icon {
  width: 50px;
  text-align: center;
  font-size: 20px;
  color: #ff9041;
}
</style>
