<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:CHECK_OBJECT:ENABLED')"
      :enable-flag="enableFlag"
      @beforeSearch="beforeSearch"
      @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:CHECK_OBJECT:ADD')" @click="handleAdd">
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <MomCopyButton
          v-if="hasAuth('EPMS:CHECK_OBJECT:ADD')"
          :disabled="selectedEditRows.length !== 1"
          :keys="selectedRowKeys"
          :data="dataSource"
          @copy="handleCopy"
        />
        <MomEditButton
          v-if="hasAuth('EPMS:CHECK_OBJECT:EDIT')"
          :disabled="selectedEditRows.length !== 1"
          :keys="selectedRowKeys"
          :data="dataSource"
          @edit="handleEdit"
        />
        <a-button
          v-if="hasAuth('EPMS:CHECK_OBJECT: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:CHECK_OBJECT: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:CHECK_OBJECT:BATCH_DELETE')"
          :disabled="selectedEditRows.length === 0"
          type="danger"
          ghost
          @click="handleBatchDelete"
        >
          <a-icon type="delete" />
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </div>
      <div slot="sourceType" slot-scope="text, record">
        <span>{{ formatData(typeList, record.sourceType) }}</span>
      </div>
      <div slot="sourceName" slot-scope="text, record">
        <span class="name_link" @click="handleView(record)">
          {{ record.sourceName }}
        </span>
      </div>
      <div slot="enableFlag" slot-scope="text, record">
        <span class="status-box" :class="'able' + text">{{
          formatData(stateList, record.enableFlag)
        }}</span>
      </div>
    </MomTable>
  </div>
</template>

<script>
import { uniqBy } from "lodash";
import { Icon } from "ant-design-vue";
import MomCopyButton from "@/components/MomCopyButton";
import MomEditButton from "@/components/MomEditButton";
import ApiConstant from "@/api/ApiConstant";

export default {
  components: { MomCopyButton, MomEditButton },
  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,
      options: {
        allowDuplicateUploads: true,
        target: "/core/api/mom-file/update-one",
        testChunks: true,
        single: true,
        chunkSize: 10 * 1024 * 1024,
      },
      // 查询的表单的配置项
      queryParam: {
        sourceName: "",
      },
      columns: [
        {
          dataIndex: "sourceName", // 点检对象来源名称
          title: () => this.$t("CHECK_OBJECT_SOURCE_NAME"),
          ellipsis: true,
          width: 200,
          scopedSlots: { customRender: "sourceName" },
        },
        {
          dataIndex: "sourceType", // 点检对象来源类型
          title: () => this.$t("CHECK_OBJECT_SOURCE_TYPE"),
          ellipsis: true,
          width: 200,
          scopedSlots: { customRender: "sourceType" },
        },
        {
          dataIndex: "enableFlag",
          align: "left",
          sorter: false,
          ellipsis: true,
          width: 150,
          title: () => this.$t("STATUS"), // 状态
          scopedSlots: { customRender: "enableFlag" },
        },
        {
          dataIndex: "updateBy", // 更新人员
          sorter: false,
          ellipsis: true,
          width: 150,
          title: () => this.$t("UPDATE_BY"),
        },
        {
          dataIndex: "updateTime", // 更新时间
          ellipsis: true,
          title: () => this.$t("UPDATE_TIME"),
        },
      ],
      total: 0,
      page: 1,
      actionButtons: [
        (h, { record, index }) =>
          this.hasAuth("EPMS:CHECK_OBJECT:ADD") &&
          ![
            "epm_eqp",
            "epm_pc_object",
            "mdm_fac_line",
            "mdm_fac_station",
          ].includes(record.tableName) && (
            <Icon
              type="copy"
              title={this.$t("COPY")}
              onClick={() => this.handleCopy(record)}
            />
          ),
        (h, { record, index }) =>
          this.hasAuth("EPMS:CHECK_OBJECT:EDIT") &&
          ![
            "epm_eqp",
            "epm_pc_object",
            "mdm_fac_line",
            "mdm_fac_station",
          ].includes(record.tableName) && (
            <Icon
              type="edit"
              title={this.$t("EDIT")}
              onClick={() => this.handleEdit(record)}
            />
          ),
        (h, { record, index }) =>
          this.hasAuth("EPMS:CHECK_OBJECT:EDIT") &&
          ![
            "epm_eqp",
            "epm_pc_object",
            "mdm_fac_line",
            "mdm_fac_station",
          ].includes(record.tableName) && (
            <Icon
              type="delete"
              title={this.$t("DELETE")}
              onClick={() => this.handleDelete(record)}
            />
          ),
      ],
      dataSource: [],
      drawerVisible: false,
      form: {
        id: null,
        checkObjectCode: "",
        sourceName: "",
        type: "",
      },
      selectedRowKeys: [], // 选中行 key 数据
      selectedRows: [], // 选中行 数据
      selectedEditRows: [], // 选中行 数据
      typeList: [], // 类型列表
      stateList: [],
    };
  },
  computed: {
    rules() {
      return {
        type: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "blur",
          },
        ],
        sourceName: [
          {
            required: true,
            max: 50,
            message: this.$t("PLACEENTER") + 50 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
      };
    },
    // 表格搜索配置
    queryParamItem() {
      return this.$observable("queryParamItem", {
        sourceName: {
          label: () => this.$t("CHECK_OBJECT_SOURCE_NAME"),
          placeholder: () => this.$t("ENTER_CHECK_OBJECT_SOURCE_NAME_KEYWORD"),
        },
      });
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedEditRows = [];
          this.selectedRowKeys = selectedRowKeys;
          if (this.selectedRowKeys.length) {
            this.selectedRows = uniqBy(this.selectedRows.concat(selectedRows));
            if (
              selectedRowKeys.length === 1 &&
              ![
                "epm_eqp",
                "epm_pc_object",
                "mdm_fac_line",
                "mdm_fac_station",
              ].includes(selectedRows[0].tableName)
            ) {
              this.selectedEditRows = selectedRows;
            }
          } else {
            this.selectedRows = selectedRows;
          }
        },
      };
    },
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      const params = {
        enableFlag: "Y",
      };
      return Promise.all([
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:PC_CHECK_OBJECT_SOURCE`
        ), // 来源类型数据字典
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:ENABLE_STATUS`
        ), // 类型数据字典
      ]).then(([typeRes, enableStatus]) => {
        this.typeList = typeRes.data?.data;
        this.stateList = enableStatus.data?.data;
      });
    },
    beforeSearch() {},
    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/pcm/object-source/search`, {
          params: searchParams,
        })
        .then((res) => {
          this.dataSource = res.data.data.records;
          this.total = res.data.data.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 监听新增点击事件
    handleAdd() {
      this.$router.push({
        path: "/eam/basic_setting/check/object_source/add",
      });
    },
    // 监听复制点击事件
    handleCopy(row) {
      this.$router.push({
        path: "/eam/basic_setting/check/object_source/add",
        query: {
          id: row.id,
        },
      });
    },
    // 监听详情点击事件
    handleView({ id }) {
      this.$router.push({
        query: {
          id,
        },
        path: "/eam/basic_setting/check/object_source/view",
      });
    },
    // 监听编辑点击事件
    handleEdit({ id }) {
      this.$router.push({
        query: {
          id,
        },
        path: "/eam/basic_setting/check/object_source/edit",
      });
    },
    // 监听删除点击事件
    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/pcm/object-source/${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/pcm/object-source/delete-batch`,
              {
                data: params,
              }
            )
            .then(() => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              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/pcm/object-source/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/pcm/object-source/enable-batch`,
              params
            )
            .then(() => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
  },
};
</script>
<style lang="less" scoped>
@import "@/assets/css/status_epms.less";
.name_link {
  color: rgba(14, 168, 208, 1);
  cursor: pointer;
  display: block;
}
</style>
