<template>
  <div class="page-wrapper">
    <breadcrumb v-if="!multiPage" :breadcrumb-data="breadcrumbData" />
    <div class="page-container">
      <!-- 基础信息 -->
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-collapse
          default-active-key="a"
          expand-icon-position="right"
          class="collapse-header-divide"
        >
          <a-collapse-panel key="a" :header="$t('BASE_INFO')">
            <a-row :gutter="24" type="flex">
              <a-col :span="8">
                <a-form-model-item :label="$t('PM_ITEM_CODE')" prop="itemCode">
                  <a-input
                    v-model="form.itemCode"
                    disabled
                    :placeholder="$t('PLACEENTER')"
                    @change="form.itemCode = form.itemCode.slice(0, 50).trim()"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item :label="$t('PM_ITEM_NAME')" prop="itemName">
                  <a-input
                    v-model="form.itemName"
                    :placeholder="$t('PLACEENTER')"
                    @change="form.itemName = form.itemName.slice(0, 50).trim()"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('MAINTENANCE_PROJECT_TYPE')"
                  prop="pmItemCategoryId"
                >
                  <SelectSearch
                    :show-multiple="false"
                    request-api="/api/epm/pmm/pm-item-category/search"
                    query-list-key="pmItemCategoryName"
                    :show-red-border="showRedBorder"
                    :is-show-add="true"
                    option-label="pmItemCategoryName"
                    :default-selected-keys="form.pmItemCategoryId"
                    :default-selected-names="form.pmItemCategoryName"
                    @change="onSelectSearchChange"
                    @add="onAddMaintainType"
                  >
                  </SelectSearch>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item :label="$t('EQP_TYPE')" prop="eqpTypeId">
                  <SelectSearch
                    :show-multiple="false"
                    request-api="/api/epm/eam/eqp-type/search"
                    :show-red-border="showRedBorder"
                    option-label="eqpTypeName"
                    :default-selected-keys="form.eqpTypeId"
                    :default-selected-names="form.eqpTypeName"
                    @change="onSelectEqpTypeChange"
                  >
                  </SelectSearch>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item :label="$t('UPLOAD_IMG')" prop="uploadFlag">
                  <a-radio-group v-model="form.uploadFlag">
                    <a-radio
                      v-for="item in yesNoList"
                      :key="item.value"
                      :value="item.value"
                      >{{ item.label }}</a-radio
                    >
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
              <a-col v-if="form.hasOwnProperty('opDescription')" :span="21">
                <a-form-model-item
                  prop="opDescription"
                  :label="$t('OPERATING_INSTRUCTION')"
                  :label-col="{ span: 3 }"
                  :wrapper-col="{ span: 19 }"
                >
                  <a-input
                    v-model="form.opDescription"
                    :placeholder="$t('PLACEENTER')"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row v-if="form.hasOwnProperty('opUrl')" :gutter="24">
              <a-col :span="8">
                <a-form-model-item prop="opUrl" :label="$t('IMPORT_PICTURE')">
                  <SingleUpload v-model="form.opUrl" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
        <!-- 扩展字段 -->
        {{ fieldExRenderFn($createElement, { layout: "grid", itemSpan: 8 }) }}
        <slot name="RenderFieldExtendDom"></slot>
      </a-form-model>
    </div>
    <div class="page-bottom-op">
      <!-- <slot name="RenderFieldButton"></slot> -->
      <!-- 字段授权 -->
      <!-- <FieldAuth
        ref="fieldAuthRef"
        :form-data="formOld"
        :table-name-list="tableNameList"
        @formBack="onFormBack"
      /> -->
      <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>
    </div>
    <MegaDrawer
      width="520"
      :title="$t('ADD')"
      :visible="dialogVisble"
      @close="dialogVisble = false"
      @cancel="dialogVisble = false"
      @ok="onSave"
    >
      <a-form-model
        slot="main"
        ref="dialogRuleForm"
        layout="vertical"
        :model="dialogForm"
        :rules="dialogRules"
      >
        <a-form-model-item
          :label="$t('CATEGORY_NAME')"
          prop="pmItemCategoryName"
        >
          <a-input
            v-model="dialogForm.pmItemCategoryName"
            :placeholder="$t('PLACEENTER')"
            @change="
              dialogForm.pmItemCategoryName = dialogForm.pmItemCategoryName
                .slice(0, 50)
                .trim()
            "
          />
        </a-form-model-item>
      </a-form-model>
    </MegaDrawer>
  </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";
import { Drawer as MegaDrawer } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
// import FieldAuth from "@/components/FieldAuth";
import FieldExtendMixin from "@/mixins/fieldExtend";
import breadcrumb from "@/components/breadcrumb";

import SelectSearch from "@/components/epms/SelectSearch";
import SingleUpload from "@/components/uploadPicture/singleUpload";

export default {
  components: {
    // FieldAuth,
    breadcrumb,
    SelectSearch,
    SingleUpload,
    MegaDrawer,
  },
  mixins: [FieldExtendMixin],
  data() {
    return {
      breadcrumbData: [
        {
          name: this.$t("MAINTENANCE_CONTENT"),
          url: "/eam/eqp_check/check_content",
        },
        { name: this.$t("MAINTENANCE_CONTENT_EDIT"), url: "" },
      ],
      tableNameList: [
        {
          key: "epm_pm_item",
          tab: "保养项目",
        },
      ],
      confirmLoading: false,
      dialogVisble: false,
      yesNoList: [],
      dataAttr: {
        form: "form",
      },
      curIndex: 0,
      activeKey: "a",
      fileUrl: `${ApiConstant.PREFIX_CORE}/api/sys/file`,
      formA: {},
      form: {
        itemCode: "", // 保养项目编码
        itemName: "", // 保养项目名称
        opDescription: "", // 操作说明
        pmItemCategoryId: "", // 保养项目分类
        eqpTypeId: "", // 设备类型
        opUrl: "", // 设备图片地址
        uploadFlag: "N", // 是否上传保养图片：是(Y);否(N)
      },
      formOld: {
        itemCode: "", // 保养项目编码
        itemName: "", // 保养项目名称
        opDescription: "", // 操作说明
        pmItemCategoryId: "", // 保养项目分类
        eqpTypeId: "", // 设备类型
        opUrl: "", // 设备图片地址
        uploadFlag: "N", // 是否上传保养图片：是(Y);否(N)
      },
      dialogForm: {
        pmItemCategoryName: "", // 	分类名称
      },
    };
  },
  computed: {
    ...mapState("setting", ["multiPage"]),
    ...mapGetters(["modules"]),
    ...mapState({
      showRedBorder: (state) => state.pagination.showRedBorder,
    }),
    dialogRules() {
      return {
        pmItemCategoryName: [
          {
            required: true,
            max: 50,
            message: this.$t("PLACEENTER") + 50 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
      };
    },
    rules() {
      return {
        itemName: [
          {
            required: true,
            max: 50,
            message: this.$t("PLACEENTER") + 50 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        pmItemCategoryId: [
          {
            required: false,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        uploadFlag: [
          {
            required: true,
          },
        ],
      };
    },
  },
  mounted() {
    const { id } = this.$route.query;
    if (id) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/pmm/pm-item/get-by-id/${id}`)
        .then((res) => {
          this.form = this.fieldExResDataFn(res.data?.data);
          this.formOld = {
            ...this.form,
            ...this.formOld,
          };
          this.queryFieldExtend().then(() => {
            // this.$refs.fieldAuthRef.init();
          });
        });
    }
    this.init();
  },
  methods: {
    init() {
      return Promise.all([
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:COMMON:WHETHER_CHAR`
        ), // 是否
      ]).then(([yesNoRes]) => {
        this.yesNoList = yesNoRes.data.data;
      });
    },
    onFormBack(formBackData) {
      this.$nextTick(() => {
        Object.keys(this.form).forEach((key) => {
          // eslint-disable-next-line no-prototype-builtins
          if (!formBackData.hasOwnProperty(key)) {
            delete this.form[key];
          }
        });
        Object.keys(formBackData).forEach((key1) => {
          // eslint-disable-next-line no-prototype-builtins
          if (!this.form.hasOwnProperty(key1)) {
            this.form[key1] = "";
          }
        });
        this.queryFieldExtend();
        // eslint-disable-next-line prefer-object-spread
        this.form = Object.assign({}, this.form);
      });
    },
    onSelectSearchChange(e) {
      this.form.pmItemCategoryId = e;
    },
    onSelectEqpTypeChange(e) {
      this.form.eqpTypeId = e;
    },
    onAddMaintainType() {
      this.dialogVisble = true;
    },
    onSave(form) {
      this.$refs.dialogRuleForm.validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          this.$axios
            .post(
              `${ApiConstant.PREFIX_CORE}/api/epm/pmm/pm-item-category`,
              this.dialogForm
            )
            .then(({ data }) => {
              this.$message.success(this.$t("ADD_SUCCESS"));
              this.form.pmItemCategoryId = data.data;
              this.form.pmItemCategoryName = this.dialogForm.pmItemCategoryName;
              this.dialogVisble = false;
              this.confirmLoading = false;
            })
            .catch((e) => {
              this.confirmLoading = false;
            });
        }
      });
    },
    handleSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const req = this.fieldExReqDataFn(this.form);
          this.confirmLoading = true;
          this.$axios
            .put(`${ApiConstant.PREFIX_CORE}/api/epm/pmm/pm-item`, req)
            .then(() => {
              this.$message.success(this.$t("EDIT_SUCCESS"));
              this.confirmLoading = false;
              this.handleCancel();
            });
        }
      });
    },
    handleCancel() {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: { path: "/eam/eqp_maintain/maintenance_content" },
        vm: this,
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.el-select-tree {
  width: 100%;
}
.equipment-add {
  /deep/ .el-input-number,
  .el-date-editor {
    min-width: 100%;
  }
}
.method-box {
  margin: 30px 0;
  margin-left: 100px;
}
.method-card {
  position: relative;
  margin-right: 50px;
  width: 200px;
  height: 80px;
  background: #fff;
  color: #c0c4cc;
  border: 1px solid #c0c4cc;
  opacity: 1;
  border-radius: 4px;
}
.method-active {
  border: 1px solid #006896;
  color: #006896;
}
.method-icon {
  font-size: 50px;
  margin-right: 20px;
}
.icon-box {
  padding: 5px;
  position: absolute;
  right: -1px;
  bottom: -1px;
  border-radius: 4px;
  color: #006896;
  background-color: #006896;
  .icon-gougou {
    color: #fff;
    height: 4px;
    font-size: 12px;
  }
  .icon-gougou::before {
    position: relative;
    top: -7px;
  }
}
</style>
