<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,
      }"
      @beforeSearch="beforeSearch"
      @search="search"
      @reset="handleReset"
    >
      <div slot="toolbar" class="button-top-table">
        <a-button
          v-show="false"
          :disabled="selectedRowKeys.length !== 1"
          @click="handleRepair(selectedRows[0])"
        >
          <Icon type="icon-fill-m--shebeiweixiu" /> {{ $t("EPMS_FIX") }}
        </a-button>
        <a-button
          v-if="hasAuth('EPMS:MOLD_REPAIR:REPAIR')"
          type="primary"
          :disabled="selectedRepairRows.length !== 1"
          @click="handleRepair(selectedRows[0])"
        >
          <Icon type="icon-fill-m--shebeiweixiu" /> {{ $t("EPMS_FIX") }}
        </a-button>
      </div>
      <template slot="status" slot-scope="text, record">
        <span
          class="status-box"
          :class="{
            red: record.status === 'WAIT_REPAIR',
            green: record.status === 'ALREADY_REPAIR',
          }"
          >{{ getAttrValue(statusList, record.status) }}</span
        >
      </template>
    </MomTable>

    <!-- 编辑抽屉 -->
    <MegaDrawer
      width="460"
      :title="$t('MOLD_REPAIR')"
      :visible="drawerVisible"
      :confirm-loading="confirmLoading"
      @close="handleCancel"
      @cancel="handleCancel"
    >
      <a-form-model
        slot="main"
        ref="ruleForm"
        layout="vertical"
        :model="form"
        :rules="rules"
      >
        <div class="eqp_box flex">
          <div
            v-if="mold_detail.imgUrl"
            class="eqp_img"
            :style="{
              backgroundImage: 'url(' + mold_detail.imgUrl + ')',
            }"
          ></div>
          <div v-else class="eqp_img">
            <img :src="defaultImg" alt="" />
          </div>
          <div class="eqp_con">
            <div class="eqp_name flex items-center mt-2">
              <span>{{ mold_detail.moldName }}</span>
            </div>
            <div class="eqp_no mt-10 mb-10">
              {{ $t("MOLD_CODE") }}：{{ mold_detail.moldCode }}
            </div>
            <div class="eqp_type">
              {{ $t("MOLD_TYPE") }}：{{ mold_detail.moldTypeName }}
            </div>
          </div>
        </div>
        <a-form-model-item :label="$t('FIX_MODE')" prop="repairType">
          <a-radio-group
            v-model="form.repairType"
            @change="handleChangeRepairType"
          >
            <a-radio
              v-for="item in typeList"
              :key="item.value"
              :value="item.value"
              >{{ item.label }}</a-radio
            >
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item
          v-show="form.repairType === 'INNER'"
          :label="$t('EPMS_REPAIR_PERSONNEL')"
          prop="repairUserName"
        >
          <template>
            <div style="position: relative">
              <select-user
                ref="selectUser"
                v-model="form.repairUserName"
                :multiple="false"
                show-key="name"
                :default-selected-rows="selectedUser"
                @confirm="getReturnData"
              />
            </div>
          </template>
        </a-form-model-item>
        <a-form-model-item
          v-if="form.repairType === 'OUTER'"
          :label="$t('REPAIR_SUPPLIER')"
          prop="partnerId"
        >
          <SelectSearch
            :show-multiple="false"
            request-api="/api/mdm/partner/search"
            option-label="partnerName"
            :default-selected-keys="form.partnerId"
            :default-selected-names="form.partnerName"
            @change="onSelectSearchChangeSupplier"
          >
          </SelectSearch>
        </a-form-model-item>
        <a-form-model-item
          v-show="form.repairType === 'OUTER'"
          :label="$t('EPMS_REPAIR_PERSONNEL')"
          prop="repairUserName"
        >
          <a-input
            v-model="form.repairUserName"
            allow-clear
            onkeyup="value=value.slice(0, 30)"
          />
        </a-form-model-item>
        <a-form-model-item :label="$t('REPAIR_TIME')" prop="repairTime">
          <a-date-picker
            v-model="form.repairTime"
            show-time
            style="width: 100%"
            :placeholder="$t('PLACESELECT')"
          />
        </a-form-model-item>
        <a-form-model-item :label="$t('REMARK')" prop="repairRemark">
          <a-input
            v-model="form.repairRemark"
            :rows="3"
            :placeholder="$t('PLACEENTER')"
            allow-clear
            type="textarea"
            onkeyup="value=value.slice(0, 300)"
          />
        </a-form-model-item>
      </a-form-model>
      <template slot="footer">
        <a-button type="primary" @click="handleSave">
          <i class="iconfont icon-baocun"></i>
          {{ $t("SAVE") }}
        </a-button>
        <a-button @click="handleCancel">
          <i class="iconfont icon-quxiao"></i> {{ $t("CANCEL") }}
        </a-button>
      </template>
    </MegaDrawer>
  </div>
</template>

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

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

export default {
  components: {
    Icon,
    MegaDrawer,
    // eslint-disable-next-line vue/no-unused-components
    MomImportButton,
    // eslint-disable-next-line vue/no-unused-components
    MomCopyButton,
    // eslint-disable-next-line vue/no-unused-components
    MomEditButton,
    SelectUser,
  },
  data() {
    return {
      // eslint-disable-next-line
      defaultImg: require("@/assets/img/eqp_01.png"),
      drawerVisible: false,
      isEdit: false,
      isView: false,
      editId: null,
      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: {
        moldIdList: "",
        moldTypeIdList: "",
      },
      columns: [
        {
          dataIndex: "moldCode", // 编码
          title: () => this.$t("MOLD_CODE"),
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "moldName", // 名称
          title: () => this.$t("MOLD") + this.$t("NAME"),
          ellipsis: true,
          sorter: false,
          width: 200,
        },
        {
          dataIndex: "moldTypeName", // 模具类型名称
          title: () => this.$t("MOLD_TYPE") + this.$t("NAME"),
          sorter: false,
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "status", // 维修状态
          title: () => this.$t("REPAIR_STATUS"),
          scopedSlots: { customRender: "status" },
        },
        {
          dataIndex: "repairNum", // 维修次数
          title: () => this.$t("REPAIR_TIMES"),
          ellipsis: true,
        },
        {
          dataIndex: "lastRepairTime", // 最近维修时间
          title: () => this.$t("LAST_REPAIR_TIME"),
          ellipsis: true,
        },
      ],
      total: 0,
      page: 1,
      actionButtons: [
        (h, { record, index }) =>
          this.hasAuth("EPMS:MOLD_REPAIR:REPAIR") &&
          record.status === "WAIT_REPAIR" && (
            <span
              class="cursor-pointer btn_operate"
              title={this.$t("EPMS_FIX")}
              onClick={() => this.handleRepair(record)}
            >
              {this.$t("EPMS_FIX")}
            </span>
          ),
        (h, { record, index }) =>
          this.hasAuth("EPMS:MOLD_REPAIR:VIEW") &&
          record.repairNum > 0 && (
            <span
              class="cursor-pointer btn_operate"
              title={this.$t("PREVIEW")}
              onClick={() => this.handleView(record)}
            >
              {this.$t("PREVIEW")}
            </span>
          ),
      ],
      dataSource: [],
      typeList: [],
      statusList: [],
      selectedRowKeys: [], // 选中行 key 数据
      selectedRows: [], // 选中行 数据
      mold_detail: {}, // 模具详情
      form: {
        repairType: "INNER", // 维修方式
        repairUserId: "", // 维修人员id
        repairUserName: "", // 维修人员名称
        repairTime: "", // 维修备注
        repairRemark: "", // 备注
        partnerId: "",
      },
      selectedUser: [],
      searchParams: {
        page: 1,
        size: 10,
        partnerType: "SUPPLIER",
      },
      selectedRepairRows: [],
      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"}
                showRedBorder={this.showRedBorder}
                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"}
                showRedBorder={this.showRedBorder}
                needDisabled={false}
                onChange={this.onSelectSearchChangeMoldType}
              ></SelectSearch>
            );
          },
        },
      });
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRepairRows = [];
          this.selectedRowKeys = selectedRowKeys;
          if (this.selectedRowKeys.length) {
            this.selectedRows = uniqBy(this.selectedRows.concat(selectedRows));
            if (
              selectedRowKeys.length === 1 &&
              !["ALREADY_REPAIR"].includes(selectedRows[0].status)
            ) {
              this.selectedRepairRows = selectedRows;
            }
          } else {
            this.selectedRows = selectedRows;
          }
        },
      };
    },
    rules() {
      return {
        repairType: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        repairUserName: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        repairTime: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
        partnerId: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
      };
    },
  },
  created() {
    this.init();
  },
  methods: {
    // 监听维修方式切换事件
    handleChangeRepairType() {
      this.form.selectedUser = [];
      this.form.repairUserId = "";
      this.form.repairUserName = "";
      this.form.partnerId = "";
      this.form.partnerName = "";
      this.$forceUpdate();
    },
    // 获取返回数据，供应商
    onSelectSearchChangeSupplier(e) {
      this.form.partnerId = e;
    },
    // 获取选择用户组件返回数据
    getReturnData(selectedKeys, selectedRows) {
      this.form.repairUserId = selectedRows[0]?.id;
      this.form.repairUserName = selectedRows[0]?.name;
      this.selectedUser = selectedRows;
    },
    // 重置搜索监听事件
    handleReset() {
      this.queryParam.moldIdList = "";
      this.queryParam.moldTypeIdList = "";
      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:COMMON_REPAIR_TYPE`
        ), // 禁用启用
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:COMMON_REPAIR_STATUS`
        ), // 禁用启用
      ]).then(([typeRes, enableStatus]) => {
        this.typeList = typeRes.data.data;
        this.statusList = enableStatus.data.data;
      });
    },
    beforeSearch() {},
    // 监听搜索事件
    search(params) {
      this.selectedRowKeys = [];
      this.selectedRows = [];
      this.loading = true;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/mam/mold-repair/search`, {
          params,
        })
        .then((res) => {
          const { records, total } = { ...res?.data?.data };
          this.dataSource = records;
          this.total = total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 监听维修点击事件
    handleRepair(item) {
      if (item.imgUrl) {
        item.imgUrl = fetchFileUrl(item.imgUrl, this); // eslint-disable-line
      } else {
        // eslint-disable-next-line no-param-reassign
        item.imgUrl = undefined;
      }
      this.form = {
        repairType: "INNER", // 维修方式
        repairUserId: "", // 维修人员id
        repairUserName: "", // 维修人员名称
        repairTime: "", // 维修备注
        repairRemark: "", // 备注
        partnerId: "",
      };
      this.selectedUser = [];
      this.mold_detail = { ...item };
      this.drawerVisible = true;
    },
    // 监听明细点击事件
    handleView({ moldId }) {
      this.$router.push({
        path: "/eam/mold_management/mold_repair/view",
        query: {
          id: moldId,
        },
      });
    },
    // 监听保存点击事件
    handleSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          const { moldId, moldCode } = this.mold_detail;
          const params = {
            moldId,
            moldCode,
            ...this.form,
          };
          params.repairTime = moment(this.form.repairTime).format(
            "YYYY-MM-DD HH:mm:ss"
          );
          this.$axios
            .post(`${ApiConstant.PREFIX_CORE}/api/epm/mam/mold-repair`, params)
            .then(() => {
              this.confirmLoading = false;
              this.$message.success(this.$t("EPMS_FIX") + this.$t("SUCCEEDED"));
              this.$refs.MomTable?.query();
              this.drawerVisible = false;
            })
            .catch(() => {
              this.confirmLoading = false;
            });
        }
      });
    },
    // 监听取消点击事件
    handleCancel() {
      this.drawerVisible = false;
      this.$refs.MomTable?.query();
    },
  },
};
</script>
<style lang="less">
@import "@/assets/css/status_epms.less";
.btn_operate {
  color: @primary-color;
}
.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%;
      }
    }
  }
}
.eqp_box {
  height: 130px;
  border-bottom: 6px solid #eaeaea;
  margin-bottom: 24px;
  padding-bottom: 24px;
  .eqp_img {
    width: 113px;
    height: 113px;
    opacity: 1;
    border-radius: 4px;
    margin-right: 20px;
    overflow: hidden;
    background-size: cover;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .eqp_con {
    font-size: 14px;
    color: #999;
  }
  .eqp_name {
    height: 18px;
    font-size: 16px;
    color: #333;
    margin-top: 2px;
  }
  .eqp_no {
    margin: 10px 0;
  }
  .eqp_status {
    padding: 0 5px;
    height: 18px;
    border-radius: 4px;
    font-size: 12px;
    color: #fff;
    margin-right: 8px;
  }
}
.status-box {
  &.red {
    .status-box-color(@error-color);
  }
  &.green {
    .status-box-color(@success-color);
  }
}
</style>
