<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:MOLD_TYPE:ENABLED')"
      :enable-flag="enableFlag"
      @beforeSearch="beforeSearch"
      @copy="handleCopy"
      @search="search"
      @edit="handleEdit"
      @delete="handleDelete"
      @reset="handleReset"
      @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:MOLD_TYPE:ADD')" @click="handleAdd">
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <MomCopyButton
          v-if="hasAuth('EPMS:MOLD_TYPE:ADD')"
          :disabled="selectedRowKeys.length !== 1"
          :keys="selectedRowKeys"
          :data="dataSource"
          @copy="handleCopy"
        />
        <MomEditButton
          v-if="hasAuth('EPMS:MOLD_TYPE:EDIT')"
          :disabled="selectedRowKeys.length !== 1"
          :keys="selectedRowKeys"
          :data="dataSource"
          @edit="handleEdit"
        />
        <MomImportButton object-name="MOLD_LEDGER" />
        <a-button
          v-if="hasAuth('EPMS:MOLD_TYPE: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:MOLD_TYPE: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:MOLD_TYPE:BATCH_DELETE')"
          :disabled="selectedRowKeys.length === 0"
          type="danger"
          ghost
          @click="handleBatchDelete"
        >
          <a-icon type="delete" />
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </div>
      <!-- <div slot="moldTypeCode" slot-scope="text, record">
        <span class="eqpTypeSty" @click="handleView(record)">
          {{ record.moldTypeCode }}
        </span>
      </div> -->
      <div slot="moldName" slot-scope="text, record">
        <span class="eqpTypeSty" @click="handleView(record)">
          {{ record.moldName }}
        </span>
      </div>
      <div slot="manageType" slot-scope="text">
        {{ getAttrValue(typeList, text) }}
      </div>
      <div slot="initValue" slot-scope="text, record">
        {{ text }}<span v-if="record.manageType === 'TIME'">min</span>
        <span v-else>{{ $t("FREQUENCY") }}</span>
      </div>
      <div slot="totalInitValue" slot-scope="text, record">
        {{ text }}<span v-if="record.manageType === 'TIME'">min</span>
        <span v-else>{{ $t("FREQUENCY") }}</span>
      </div>
      <template slot="enableFlag" slot-scope="text, record">
        <span class="status-box" :class="'able' + text">{{
          getAttrValue(stateList, record.enableFlag)
        }}</span>
      </template>
      <template slot="moldStatus" slot-scope="text, record">
        <span class="status-box" :class="text">{{
          getAttrValue(statusList, record.moldStatus)
        }}</span>
      </template>
    </MomTable>
  </div>
</template>

<script>
import { uniqBy } from "lodash";
import { mapState } from "vuex";
import ApiConstant from "@/api/ApiConstant";
import MomCopyButton from "@/components/MomCopyButton";
import MomEditButton from "@/components/MomEditButton";
import MomImportButton from "@/components/MomImportButton";

import SelectSearch from "@/components/epms/SelectSearch";

export default {
  components: {
    MomImportButton,
    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,
      // 查询的表单的配置项
      queryParam: {
        moldIdList: "",
        moldTypeIdList: "",
      },
      columns: [
        {
          dataIndex: "moldCode", // 编码
          title: () => this.$t("MOLD_CODE"),
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "moldName", // 名称
          title: () => this.$t("MOLD_NAME"),
          ellipsis: true,
          scopedSlots: { customRender: "moldName" },
        },
        {
          dataIndex: "moldTypeName", // 模具类型名称
          title: () => this.$t("MOLD_TYPE") + this.$t("NAME"),
          ellipsis: true,
        },
        {
          dataIndex: "moldHoleNum", // 模具穴数
          title: () => this.$t("NUMBER_OF_ACUPOINTS"),
          ellipsis: true,
        },
        {
          dataIndex: "manageType",
          align: "left",
          width: 150,
          ellipsis: true,
          title: () => this.$t("MOLD_CONTROL_MODE"), // 管控方式
          scopedSlots: { customRender: "manageType" },
        },
        {
          dataIndex: "initValue", // 当次初始时间/次数
          title: () => this.$t("INITIAL_VALUE_OF_CURRENT_USE"),
          sorter: false,
          ellipsis: true,
          scopedSlots: { customRender: "initValue" },
        },
        {
          dataIndex: "totalInitValue", // 历次累积时间/次数
          title: () => this.$t("INITIAL_VALUE_OF_PREVIOUS_USE"),
          sorter: false,
          ellipsis: true,
          scopedSlots: { customRender: "totalInitValue" },
        },
        {
          dataIndex: "moldStatus",
          align: "center",
          width: 150,
          title: () => this.$t("MOLD") + this.$t("STATUS"), // 状态
          scopedSlots: { customRender: "moldStatus" },
        },
        {
          dataIndex: "enableFlag",
          align: "center",
          width: 150,
          title: () => this.$t("STATUS"), // 状态
          scopedSlots: { customRender: "enableFlag" },
        },
        {
          dataIndex: "updateBy", // 更新人员
          ellipsis: true,
          title: () => this.$t("UPDATE_BY"),
          width: 200,
        },
        {
          dataIndex: "updateTime", // 更新时间
          ellipsis: true,
          title: () => this.$t("UPDATE_TIME"),
          width: 200,
        },
      ],
      total: 0,
      page: 1,
      actionButtons: [
        this.hasAuth("EPMS:MOLD_TYPE:ADD") && "copy",
        this.hasAuth("EPMS:MOLD_TYPE:EDIT") && "edit",
        this.hasAuth("EPMS:MOLD_TYPE:DELETE") && "delete",
      ],
      dataSource: [],
      stateList: [],
      statusList: [],
      typeList: [],
      selectedRowKeys: [], // 选中行 key 数据
      selectedRows: [], // 选中行 数据
      isReset: false, // 是否重置SelectSearch组件value
    };
  },
  computed: {
    // 表格搜索配置
    queryParamItem() {
      return this.$observable("queryParamItem", {
        moldIdList: {
          itemType: "custom",
          label: () => this.$t("MOLD") + this.$t("NAME"),
          customRender: () => {
            return (
              <SelectSearch
                isReset={this.isReset}
                queryListKey="moldName"
                requestApi={"/api/epm/mam/mold/search"}
                option-label={"moldName"}
                option-value={"id"}
                needDisabled={false}
                onChange={this.onSelectSearchChange}
              ></SelectSearch>
            );
          },
        },
        moldTypeIdList: {
          itemType: "custom",
          label: () => this.$t("MOLD_TYPE") + this.$t("NAME"),
          customRender: () => {
            return (
              <SelectSearch
                isReset={this.isReset}
                queryListKey="moldTypeName"
                requestApi={"/api/epm/mam/mold-type/search"}
                option-label={"moldTypeName"}
                option-value={"id"}
                needDisabled={false}
                onChange={this.onSelectSearchChangeMoldType}
              ></SelectSearch>
            );
          },
        },
      });
    },
    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: {
    // 重置搜索监听事件
    handleReset() {
      this.isReset = true;
      this.$refs.MomTable?.search();
    },
    onSelectSearchChange(e, ids) {
      this.isReset = false;
      this.queryParam.moldIdList = ids.join(",");
    },
    onSelectSearchChangeMoldType(e, ids) {
      this.isReset = false;
      this.queryParam.moldTypeIdList = ids.join(",");
    },
    // 初始化数据
    init() {
      return Promise.all([
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:MOLD_MANAGE_TYPE`
        ), // 管控方式
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:ENABLE_STATUS`
        ), // 禁用启用
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:MOLD_STATUS`
        ), // 模具状态
      ]).then(([typeRes, enableStatus, statusRes]) => {
        this.typeList = typeRes.data.data;
        this.stateList = enableStatus.data.data;
        this.statusList = statusRes.data.data;
      });
    },
    beforeSearch() {},
    // 监听搜索事件
    search(params) {
      this.selectedRowKeys = [];
      this.selectedRows = [];
      this.loading = true;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/mam/mold/search`, {
          params,
        })
        .then((res) => {
          const { records, total } = { ...res?.data?.data };
          this.dataSource = records;
          this.total = total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 监听新增点击事件
    handleAdd() {
      this.$router.push({
        path: "/eam/mold_management/mold_account/add",
      });
    },
    // 监听编辑点击事件
    handleCopy({ id }) {
      this.$router.push({
        path: "/eam/mold_management/mold_account/add",
        query: {
          id,
        },
      });
    },
    handleView({ id }) {
      this.$router.push({
        path: "/eam/mold_management/mold_account/view",
        query: {
          id,
        },
      });
    },
    // 点击表格行内的编辑
    handleEdit({ id }) {
      this.$router.push({
        path: "/eam/mold_management/mold_account/edit",
        query: {
          id,
        },
      });
    },
    // 监听删除点击事件
    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/mam/mold/${row.id}`)
            .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/mam/mold/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/mam/mold/enable-batch`,
              params
            )
            .then(() => {
              this.$message.success(this.$t(tips));
              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"),
        icon: "close-circle",
        centered: true,
        onOk: () => {
          this.$axios
            .delete(
              `${ApiConstant.PREFIX_CORE}/api/epm/mam/mold/delete-batch`,
              {
                data: params,
              }
            )
            .then(() => {
              this.$message.success(this.$t("DELETE_SUCCESS"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
  },
};
</script>
<style lang="less">
@import "@/assets/css/status_epms.less";
.eqpTypeSty {
  color: rgba(14, 168, 208, 1);
  cursor: pointer;
  display: block;
}
.wrapClass .ant-modal {
  top: 0;
  padding-bottom: 0;
  .ant-modal-content {
    min-height: 100vh;
    border-left: 8px solid #f0f2f5;
    border-right: 8px solid #f0f2f5;
    .ant-modal-header {
      background: #fff;
      margin: 0 -8px;
      border-radius: 0;
    }
    .ant-modal-body {
      padding: 0;
      border-top: 8px solid #f0f2f5;
      .page-bottom-op {
        width: 100%;
      }
    }
  }
}
</style>
