<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"
      @copy="handleCopy"
      @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="selectedRowKeys.length !== 1"
          :keys="selectedRowKeys"
          :data="dataSource"
          @copy="handleCopy"
        />
        <MomEditButton
          v-if="hasAuth('EPMS:CHECK_OBJECT:EDIT')"
          :disabled="selectedRowKeys.length !== 1"
          :keys="selectedRowKeys"
          :data="dataSource"
          @edit="handleEdit"
        />
        <span style="margin: 0 8px">
          <MomImportButton object-name="PC_OBJECT" />
        </span>
        <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="selectedRowKeys.length === 0"
          type="danger"
          ghost
          @click="handleBatchDelete"
        >
          <a-icon type="delete" />
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </div>
      <div slot="name" slot-scope="text, record">
        <span class="name_link" @click="handleView(record)">
          {{ record.name }}
        </span>
      </div>
      <div slot="enableFlag" slot-scope="text, record">
        <span class="status-box" :class="'able' + text">{{
          formatData(stateList, record.enableFlag)
        }}</span>
      </div>
      <div slot="type" slot-scope="text, record">
        <span>{{ formatData(typeList, record.type) }}</span>
      </div>
    </MomTable>
    <MegaDrawer
      width="520"
      :title="
        form.id
          ? $t('CHECK_OBJECT') + $t('EDIT')
          : isView === true
          ? $t('VIEW') + $t('CHECK_OBJECT')
          : $t('CHECK_OBJECT') + $t('ADD')
      "
      :visible="drawerVisible"
      @close="handleCancel"
    >
      <template slot="main">
        <a-form-model
          slot="main"
          ref="ruleForm"
          layout="vertical"
          :model="form"
          :rules="rules"
        >
          <a-form-model-item :label="$t('CHECK_OBJECT_CODE')" prop="code">
            <a-input
              v-model="form.code"
              :placeholder="`${$t('SYSTEM_DEFAULT_CODE')}DJDX+${$t('NUMBER')}`"
              :disabled="form.id || isView === true ? true : false"
              @change="form.name = form.name.slice(0, 50).trim()"
            />
          </a-form-model-item>
          <a-form-model-item :label="$t('CHECK_OBJECT_NAME')" prop="name">
            <a-input
              v-model="form.name"
              :disabled="isView"
              :placeholder="$t('PLACEENTER')"
              @change="form.name = form.name.slice(0, 50).trim()"
            />
          </a-form-model-item>
          <a-form-model-item
            class="error-type"
            :label="$t('CHECK_OBJECT_TYPE')"
            prop="type"
          >
            <a-select v-model="form.type" :disabled="isView">
              <a-select-option
                v-for="(item, index) in typeList"
                :key="index"
                :value="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-form-model>
      </template>
      <footer slot="footer">
        <a-button
          v-if="!isView"
          type="primary"
          :loading="confirmLoading"
          @click="handleSave('save')"
        >
          <i class="iconfont icon-baocun"></i> {{ $t("SAVE") }}
        </a-button>
        <a-button
          v-if="!isView"
          :loading="confirmLoading"
          type="primary"
          @click="handleSave('saveAndAdd')"
        >
          <i class="iconfont icon-baocun"></i>
          {{ $t("SAVE_AND_ADD_NEXT") }}
        </a-button>
        <a-button @click="handleCancel">
          <i class="iconfont icon-quxiao"></i>{{ $t("CANCEL") }}
        </a-button>
      </footer>
    </MegaDrawer>
  </div>
</template>

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

export default {
  components: {
    MegaDrawer,
    MomImportButton,
    MomCopyButton,
    MomEditButton,
  },
  data() {
    return {
      isView: false,
      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: {
        name: "",
      },
      columns: [
        {
          dataIndex: "code", // 点检对象编码
          title: () => this.$t("CHECK_OBJECT_CODE"),
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "name", // 点检对象名称
          title: () => this.$t("CHECK_OBJECT_NAME"),
          ellipsis: true,
          width: 200,
          scopedSlots: { customRender: "name" },
        },
        {
          dataIndex: "type", // 点检对象类型
          title: () => this.$t("CHECK_OBJECT_TYPE"),
          ellipsis: true,
          width: 200,
          scopedSlots: { customRender: "type" },
        },
        {
          dataIndex: "enableFlag",
          sorter: false,
          ellipsis: true,
          width: 120,
          title: () => this.$t("STATUS"), // 状态
          scopedSlots: { customRender: "enableFlag" },
        },
        {
          dataIndex: "updateBy", // 更新人员
          sorter: false,
          ellipsis: true,
          title: () => this.$t("UPDATE_BY"),
        },
        {
          dataIndex: "updateTime", // 更新时间
          ellipsis: true,
          width: 200,
          title: () => this.$t("UPDATE_TIME"),
        },
      ],
      total: 0,
      page: 1,
      actionButtons: [
        this.hasAuth("EPMS:CHECK_OBJECT:ADD") && "copy",
        this.hasAuth("EPMS:CHECK_OBJECT:EDIT") && "edit",
        this.hasAuth("EPMS:CHECK_OBJECT:DELETE") && "delete",
      ],
      dataSource: [],
      drawerVisible: false,
      form: {
        id: null,
        code: "",
        name: "",
        type: "",
      },
      stateList: [],
      typeList: [],
      selectedRowKeys: [], // 选中行 key 数据
      selectedRows: [], // 选中行 数据
    };
  },
  computed: {
    rules() {
      return {
        name: [
          {
            required: true,
            max: 50,
            message: this.$t("PLACEENTER") + 50 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        type: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
      };
    },
    // 表格搜索配置
    queryParamItem() {
      return this.$observable("queryParamItem", {
        name: {
          label: () => this.$t("CHECK_OBJECT_NAME"),
          placeholder: () => this.$t("ENTER_CHECK_OBJECT_NAME_KEYWORD"),
        },
      });
    },
    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() {
      const params = {
        enableFlag: "Y",
      };
      return Promise.all([
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:PC_OBJECT_TYPE`
        ), // 类型数据字典
        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/pc-object/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.form.id = null;
      this.form.type = "";
      this.form.name = "";
      this.form.code = "";
      this.drawerVisible = true;
    },
    // 监听复制点击事件
    handleCopy({ name, type }) {
      this.form = {
        name,
        type,
      };
      this.drawerVisible = true;
    },
    // 监听详情点击事件
    handleView({ id, code, name, type }) {
      this.form = {
        id,
        code,
        name,
        type,
      };
      this.isView = true;
      this.drawerVisible = true;
    },
    // 监听编辑点击事件
    handleEdit({ id, code, name, type }) {
      this.form = {
        id,
        code,
        name,
        type,
      };
      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/pcm/pc-object/${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/pc-object/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/pc-object/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/pc-object/enable-batch`,
              params
            )
            .then(() => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 监听保存点击事件
    handleSave(type) {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          if (this.form.id) {
            this.$axios
              .put(
                `${ApiConstant.PREFIX_CORE}/api/epm/pcm/pc-object`,
                this.form
              )
              .then(() => {
                this.$message.success(this.$t("EDIT_SUCCESS"));
                this.$refs.MomTable?.query();
                this.confirmLoading = false;
                this.$refs.ruleForm.clearValidate();
                if (type === "saveAndAdd") {
                  // this.form = {
                  //   id: null,
                  //   code: "",
                  //   name: "",
                  //   type: "",
                  // };
                } else {
                  this.handleCancel();
                }
              })
              .catch((e) => {
                this.confirmLoading = false;
              });
          } else {
            this.$axios
              .post(
                `${ApiConstant.PREFIX_CORE}/api/epm/pcm/pc-object`,
                this.form
              )
              .then(() => {
                this.$message.success(this.$t("ADD_SUCCESS"));
                this.$refs.MomTable?.query();
                this.confirmLoading = false;
                this.$refs.ruleForm.clearValidate();
                if (type === "saveAndAdd") {
                  // this.form = {
                  //   id: null,
                  //   code: "",
                  //   name: "",
                  //   type: "",
                  // };
                } else {
                  this.handleCancel();
                }
              })
              .catch((e) => {
                this.confirmLoading = false;
              });
          }
        }
      });
    },
    // 监听取消点击事件
    handleCancel() {
      this.isView = false;
      this.drawerVisible = false;
    },
  },
};
</script>
<style lang="less" scoped>
@import "@/assets/css/status_epms.less";
.name_link {
  color: rgba(14, 168, 208, 1);
  cursor: pointer;
  display: block;
}
</style>
