<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: 7 }"
        :wrapper-col="{ span: 17 }"
      >
        <a-collapse
          v-model="activeKey"
          expand-icon-position="right"
          class="collapse-header-divide"
        >
          <a-collapse-panel key="a" :header="$t('BASE_INFO')">
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('MAINTENANCE_FORM_CODE')"
                  prop="pmFrmCode"
                  allow-clear
                >
                  <a-input
                    v-model="form.pmFrmCode"
                    disabled
                    :placeholder="$t('PLACEENTER')"
                    @change="
                      form.pmFrmCode = form.pmFrmCode.slice(0, 50).trim()
                    "
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  :label="$t('FORM_NAME')"
                  prop="pmFrmName"
                  allow-clear
                >
                  <a-input
                    v-model="form.pmFrmName"
                    disabled
                    :placeholder="$t('PLACEENTER')"
                    @change="
                      form.pmFrmName = form.pmFrmName.slice(0, 50).trim()
                    "
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item :label="$t('EQP_TYPE')" prop="eqpTypeId">
                  <SelectSearch
                    :disabled="true"
                    :show-multiple="false"
                    request-api="/api/epm/eam/eqp-type/search"
                    option-label="eqpTypeName"
                    query-list-key="eqpTypeName"
                    :default-selected-keys="form.eqpTypeId"
                    :default-selected-names="form.eqpTypeName"
                    @change="onSelectSearchChange"
                  >
                  </SelectSearch>
                </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 :label="$t('MAINTENANCE_SOP')" prop="opUrl">
                  <SingleUploadFile v-model="form.opUrl" :disabled="true" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
        <a-collapse
          v-model="activeKeyB"
          expand-icon-position="right"
          class="collapse-header-divide"
        >
          <a-collapse-panel key="b" :header="$t('MAINTENANCE_MODE')">
            <MomTable
              ref="MomTable"
              row-key="itemName"
              :columns="columns"
              :data-source="pmFrmItemList"
              :pagination="false"
              :mega-extend="{
                rowAction: false,
              }"
            >
              <div slot="uploadFlag" slot-scope="text, record">
                <span>{{ getAttrValue(yesNoList, record.uploadFlag) }}</span>
              </div>
            </MomTable>
          </a-collapse-panel>
        </a-collapse>
        <!-- 扩展字段 -->
        {{
          fieldExRenderFn($createElement, {
            layout: "grid",
            itemSpan: 8,
            disabled: true,
          })
        }}
        <slot name="RenderFieldExtendDom"></slot>
      </a-form-model>
    </div>
    <div class="page-bottom-op">
      <a-button @click="handleCancel">
        <i class="iconfont icon-quxiao"></i>
        {{ $t("BACK") }}
      </a-button>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { uniqBy } from "lodash";
import ApiConstant from "@/api/ApiConstant";
import FieldExtendMixin from "@/mixins/fieldExtend";
import breadcrumb from "@/components/breadcrumb";

import SelectSearch from "@/components/epms/SelectSearch";
import SingleUploadFile from "@/components/uploadFile/singleUpload";

export default {
  components: {
    breadcrumb,
    SelectSearch,
    SingleUploadFile,
  },
  mixins: [FieldExtendMixin],
  data() {
    return {
      breadcrumbData: [
        {
          name: this.$t("CHECK_FORM"),
          url: "/eam/eqp_check/check_form",
        },
        { name: this.$t("CHECK_FORM_ADD"), url: "" },
      ],
      tableNameList: [
        {
          key: "epm_pm_frm",
          tab: "保养表单",
        },
      ],
      dataAttr: {
        form: "form",
      },
      activeKey: "a",
      activeKeyB: "b",
      isShowButton: true,
      dataSource: [],
      form: {
        id: "",
        pmFrmCode: "", // 保养表单编码
        pmFrmName: "", // 保养表单名称
        eqpTypeId: "", // 设备类型
        opUrl: "", // 图片或视频地址
      },
      pmItemCategoryName: "",
      isEdit: false,
      editIndex: 0,
      pmFrmItemList: [],
      itemObj: {
        itemName: "", // 	点检项名称
        itemType: "", // 点检项类型
        checkStyle: "", // 点检方式
        compareType: "", // 比较方式
        lowerLimit: "", // 标准下限
        textValue: "", // 文本标准值
        autoMatchKey: "", // 自动匹配的Key
        opDescription: "", // 操作说明
        opUrl: "", // 操作说明地址：图片或视频
        imgFlag: "Y", // 是否上传点检图片
        noShowLow: true,
        noShowUp: true,
        fieldExtendList: [],
      },
      yesNoList: [], // 是否列表
      fieldExtendList: [], // 字段扩展列表
      dynamicFieldList: [], // 字段扩展列表动态
      defaultList: [
        {
          dataIndex: "itemName", // 保养项目
          sorter: false,
          ellipsis: true,
          title: () => this.$t("MAINTENANCE_CONTENT"),
        },
        {
          dataIndex: "pmItemCategoryName", // 保养分类名称分类
          title: () => `${this.$t("MAINTENANCE_TYPE")}${this.$t("NAME")}`,
          ellipsis: true,
          sorter: false,
        },
        {
          dataIndex: "uploadFlag",
          align: "left",
          sorter: false,
          ellipsis: true,
          title: () => this.$t("IMG_FLAG"), //
          scopedSlots: { customRender: "uploadFlag" },
        },
        {
          dataIndex: "opDescription", // 操作说明
          sorter: false,
          ellipsis: true,
          title: () => this.$t("OPERATING_INSTRUCTION"),
        },
      ],
      selectedRowKeys: [], // 选中行 key 数据
      selectedRows: [], // 选中行 数据
      columnsItem: {
        dataIndex: "",
        title: "",
        ellipsis: true,
        sorter: false,
      },
      columnsList: [],
    };
  },
  computed: {
    ...mapState("setting", ["multiPage"]),
    ...mapState({
      showRedBorder: (state) => state.pagination.showRedBorder,
    }),
    rules() {
      return {
        pmFrmName: [
          {
            required: true,
            max: 50,
            message: () => this.$t("PLACEENTER") + 50 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
      };
    },
    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;
          }
        },
      };
    },
    columns() {
      return [...this.defaultList, ...this.columnsList];
    },
  },
  watch: {},
  mounted() {
    this.queryFieldExtend().then(() => {});
    // 初始化数据
    this.init();
  },
  methods: {
    // 获取返回数据，设备类型
    onSelectSearchChange(e) {
      this.form.eqpTypeId = e;
    },
    // 初始化数据
    init() {
      const params = {
        tableNameList: "epm_pm_item",
        moduleCode: this.$store.state.activatedModule,
      };
      return Promise.all([
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:COMMON:WHETHER_CHAR`
        ), // 是否
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/epm/pmm/pm-frm/get-by-id/${this.$route.query.id}`
        ), // 点检对象来源配置详情
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/filed-extend-config/detail-batch`,
          {
            params,
          }
        ), // 扩展字段，保养项目
      ]).then(([yesNoRes, detailRes, detailBatchRes]) => {
        this.yesNoList = yesNoRes.data.data;
        /* eslint-disable */
        const { pmFrmItemList } = detailRes.data?.data;
        if (pmFrmItemList && pmFrmItemList.length > 0) {
          this.pmFrmItemList = pmFrmItemList.map((item) => {
            const req = this.fieldExResDataFn(item);
            return req;
          });
          this.handleItemList();
        }
        this.form = { ...detailRes.data?.data };
        this.fieldExtendList =
          detailBatchRes.data?.data?.fieldExtendConfigList[0]?.items.filter(
            (item) => [1, "Y"].includes(item.enableFlag)
          ) || [];
        if (this.fieldExtendList && this.fieldExtendList.length > 0) {
          this.fieldExtendList.forEach((item, index) => {
            if (detailBatchRes.data.data?.fieldHiddenConfigList?.length) {
              // eslint-disable-next-line array-callback-return
              detailBatchRes.data.data.fieldHiddenConfigList.forEach((ele) => {
                if (ele.fieldName === item.fieldName) {
                  this.fieldExtendList.splice(index, 1);
                }
              });
            }
          });
        }
        if (this.fieldExtendList && this.fieldExtendList.length > 0) {
          this.fieldExtendList.forEach((item) => {
            this.itemObj[item.fieldName] = "";
            if (item.type === "DYNAMIC") {
              this.dynamicFieldList.push(item.fieldName);
            }
            // 动态添加表格列
            const columnsItem = { ...this.columnsItem };
            columnsItem.dataIndex = item.fieldName;
            columnsItem.title = () => this.$t(`${item.i18nCode}`);
            if (!["code", "name"].includes(item.fieldName)) {
              this.columnsList.push(columnsItem);
            }
          });
        }
        /* eslint-enable */
      });
    },
    // 点检方式切换
    handleMethodChange(e, index) {
      this.pmFrmItemList[index].checkStyle = e;
      this.$forceUpdate();
    },
    // 监听保养项目列表
    handleItemList() {
      // eslint-disable-next-line array-callback-return
      this.pmFrmItemList.map((item, index) => {
        // eslint-disable-next-line no-param-reassign
        item.fieldExtendList = this.fieldExtendList;
      });
      this.pmFrmItemList = uniqBy(this.pmFrmItemList, "itemName"); // 去重
    },
    // 监听取消按钮点击事件
    handleCancel() {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: {
          path: "/eam/eqp_maintain/maintenance_form",
        },
        vm: this,
      });
    },
  },
};
</script>
<style lang="less" scoped>
@import "@/assets/css/fault_repair.less";
/deep/ .mega-design-business-table .mega-design-pro-table {
  padding: 0 !important;
  margin-bottom: 24px;
}
/deep/ .ant-form-item-label {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>

<style lang="less">
.icon-bianji2 {
  color: @primary-color !important;
}
.status-btn {
  cursor: pointer;
  margin-top: 0;
  margin-left: 6px;
  min-width: 100px;
  height: 36px;
  background: #fff;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  text-align: center;
  line-height: 36px;
  position: relative;
  padding: 0 6px;
}
.statusActive {
  border: 1px solid #ff3250;
}
.icon-box {
  padding: 5px;
  position: absolute;
  right: -1px;
  bottom: -1px;
  border-radius: 4px;
  .icon-gougou {
    color: #fff;
    height: 4px;
    font-size: 12px;
  }
  .icon-gougou::before {
    position: relative;
    top: -16px;
  }
}
</style>
