<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('CHECK_CONTENT')}${$t('CODE')}`"
                  prop="itemCode"
                >
                  <a-input
                    v-model="form.itemCode"
                    :placeholder="`${$t('SYSTEM_DEFAULT_CODE')}DJX+${$t(
                      'NUMBER'
                    )}`"
                    @change="form.itemCode = form.itemCode.slice(0, 50).trim()"
                  />
                </a-form-model-item>
              </a-col>
              <a-col v-if="form.hasOwnProperty('itemName')" :span="8">
                <a-form-model-item
                  :label="`${$t('CHECK_CONTENT')}${$t('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 v-if="form.hasOwnProperty('pcCategoryId')" :span="8">
                <a-form-model-item
                  :label="$t('CHECK_TYPE')"
                  prop="pcCategoryId"
                >
                  <SelectCheckType
                    :pc-category-id="form.pcCategoryId"
                    :pc-category-name="form.pcCategoryName"
                    @change="onSelectSearchChange"
                  >
                  </SelectCheckType>
                </a-form-model-item>
              </a-col>
              <a-col v-if="form.hasOwnProperty('imgFlag')" :span="8">
                <a-form-model-item :label="$t('IMG_FLAG')" prop="imgFlag">
                  <a-radio-group v-model="form.imgFlag">
                    <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-row>
          </a-collapse-panel>
        </a-collapse>
        <!-- 点检方式 -->
        <a-collapse
          default-active-key="b"
          expand-icon-position="right"
          class="collapse-header-divide"
        >
          <a-collapse-panel key="b" :header="$t('EQP_CHECK_METHOD')">
            <a-row :gutter="24" type="flex">
              <a-col v-if="form.hasOwnProperty('checkStyle')" :span="24">
                <div class="method-box flex">
                  <div
                    v-for="(item, index) in chechStyleList"
                    :key="index"
                    class="method-card flex items-center justify-center"
                    :class="{ 'method-active': form.checkStyle === item.value }"
                    @click="onMethodChange(item.value)"
                  >
                    <div
                      v-if="item.value === 'BOOL'"
                      class="method-icon iconfont icon-OKNG"
                    ></div>
                    <div
                      v-if="item.value === 'NUMBER'"
                      class="method-icon iconfont icon-shuzhi"
                    ></div>
                    <div
                      v-if="item.value === 'TEXT'"
                      class="method-icon iconfont icon-shuzhiOKNG"
                    ></div>
                    <div>
                      {{ item.label }}
                      <div
                        v-show="form.checkStyle === item.value"
                        class="icon-box"
                      >
                        <div class="iconfont icon-gougou"></div>
                      </div>
                    </div>
                  </div>
                </div>
              </a-col>
              <a-col
                v-if="
                  form.hasOwnProperty('itemType') &&
                  form.checkStyle === 'NUMBER'
                "
                :span="8"
              >
                <a-form-model-item :label="$t('PROJECT_TYPE')" prop="itemType">
                  <a-select
                    v-model="form.itemType"
                    :placeholder="$t('PLACESELECT')"
                  >
                    <a-select-option
                      v-for="(item, index) in itemTypeList"
                      :key="index"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col
                v-if="
                  form.hasOwnProperty('autoMatchKey') &&
                  form.checkStyle === 'NUMBER' &&
                  form.itemType === 'AUTO'
                "
                :span="8"
              >
                <a-form-model-item
                  :label="$t('AUTO_MATCH_KEY')"
                  prop="autoMatchKey"
                >
                  <a-input
                    v-model="form.autoMatchKey"
                    :placeholder="$t('PLACEENTER')"
                    @change="
                      form.autoMatchKey = form.autoMatchKey.slice(0, 32).trim()
                    "
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24" type="flex">
              <a-col
                v-if="
                  form.hasOwnProperty('compareType') &&
                  form.checkStyle === 'NUMBER'
                "
                :span="8"
              >
                <a-form-model-item
                  :label="$t('COMPARISON_MODE')"
                  prop="compareType"
                >
                  <a-select
                    v-model="form.compareType"
                    :placeholder="$t('PLACESELECT')"
                    @change="onChangeCompare"
                  >
                    <a-select-option
                      v-for="(item, index) in compareTypeList"
                      :key="index"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col
                v-if="
                  form.hasOwnProperty('lowerLimit') &&
                  form.checkStyle === 'NUMBER' &&
                  form.compareType &&
                  !noShowLow
                "
                :span="8"
              >
                <a-form-model-item
                  :label="$t('STANDARD_LOWER_LIMIT')"
                  prop="lowerLimit"
                >
                  <a-input-number
                    v-model="form.lowerLimit"
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col>
              <a-col
                v-if="
                  form.hasOwnProperty('upperLimit') &&
                  form.checkStyle === 'NUMBER' &&
                  form.compareType &&
                  !noShowUp
                "
                :span="8"
              >
                <a-form-model-item
                  :label="$t('STANDARD_UPPER_LIMIT')"
                  prop="upperLimit"
                >
                  <a-input-number
                    v-model="form.upperLimit"
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24" type="flex">
              <a-col
                v-if="
                  form.hasOwnProperty('textValue') && form.checkStyle === 'TEXT'
                "
                :span="8"
              >
                <a-form-model-item
                  :label="$t('STANDARD_VALUE')"
                  prop="textValue"
                >
                  <a-input
                    v-model="form.textValue"
                    :placeholder="$t('PLACEENTER')"
                    @change="
                      form.textValue = form.textValue.slice(0, 255).trim()
                    "
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <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-col v-if="form.hasOwnProperty('opUrl')" :span="8">
                <a-form-model-item
                  prop="opUrl"
                  :label="`${$t('OPERATION')}${$t('GUIDE')}${$t(
                    'CORE_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"
        :loading="confirmLoading"
        @click="handleSave('save')"
      >
        <i class="iconfont icon-baocun"></i>
        {{ $t("SAVE") }}
      </a-button>
      <a-button
        type="primary"
        :loading="confirmLoading"
        @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>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";
import ApiConstant from "@/api/ApiConstant";
// import FieldAuth from "@/components/FieldAuth";
import FieldExtendMixin from "@/mixins/fieldExtend";
import breadcrumb from "@/components/breadcrumb";
import SelectCheckType from "@/components/SelectCheckType";
import SingleUpload from "@/components/uploadPicture/singleUpload";

export default {
  components: {
    // FieldAuth,
    breadcrumb,
    SelectCheckType,
    SingleUpload,
  },
  mixins: [FieldExtendMixin],
  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
    isView: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      breadcrumbData: [
        {
          name: this.$t("CHECK_CONTENT"),
          url: "/eam/eqp_check/check_content",
        },
        { name: this.$t("ADD"), url: "" },
      ],
      tableNameList: [
        {
          key: "epm_pc_item",
          tab: "点检项目",
        },
      ],
      confirmLoading: false,
      chechStyleList: [],
      itemTypeList: [],
      noShowLow: false,
      noShowUp: false,
      compareTypeList: [],
      yesNoList: [],
      dataAttr: {
        form: "form",
      },
      activeKey: "a",
      fileUrl: `${ApiConstant.PREFIX_CORE}/api/sys/file`,
      form: {
        itemCode: "", // 点检项目编码
        itemName: "", // 点检项目名称
        opDescription: "", // 操作说明
        checkStyle: "BOOL", // 点检方式
        itemType: "NORMAL", // 点检项类型
        upperLimit: "", // 上线
        lowerLimit: "", // 下线
        compareType: "", // 比较方式
        autoMatchKey: "", // 自动匹配的Key
        textValue: "", // 标准值
        pcCategoryId: "", // 点检分类
        opUrl: "", // 设备图片地址
        imgFlag: "N", // 是否上传点检图片：是(Y);否(N)
      },
      formOld: {
        itemCode: "", // 点检项目编码
        itemName: "", // 点检项目名称
        opDescription: "", // 操作说明
        checkStyle: "BOOL", // 点检方式
        itemType: "NORMAL", // 点检项类型
        upperLimit: "", // 上线
        lowerLimit: "", // 下线
        compareType: "", // 比较方式
        autoMatchKey: "", // 自动匹配的Key
        textValue: "", // 标准值
        pcCategoryId: "", // 点检分类
        opUrl: "", // 设备图片地址
        imgFlag: "N", // 是否上传点检图片：是(Y);否(N)
      },
    };
  },
  computed: {
    ...mapState("setting", ["multiPage"]),
    ...mapGetters(["modules"]),
    ...mapState({
      showRedBorder: (state) => state.pagination.showRedBorder,
    }),
    rules() {
      return {
        itemName: [
          {
            required: true,
            max: 50,
            message: this.$t("PLACEENTER") + 50 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        upperLimit: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        lowerLimit: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        imgFlag: [
          {
            required: true,
          },
        ],
      };
    },
  },
  mounted() {
    const { id } = this.$route.query;
    if (id) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/pcm/pc-item/get-by-id/${id}`)
        .then((res) => {
          this.form = this.fieldExResDataFn(res.data?.data);
          this.form.id = "";
          this.form.itemCode = "";
          this.formOld.id = "";
          this.formOld.itemCode = "";
          this.formOld = {
            ...this.form,
            ...this.formOld,
          };
          this.noShowLow = false;
          this.noShowUp = false;
          switch (this.form.compareType) {
            case "<": // <: "点检值<上限"
              this.noShowLow = true;
              break;
            case ">": // >: "点检值>下限"
              this.noShowUp = true;
              break;
            default:
              break;
          }
          this.queryFieldExtend().then(() => {
            // this.$refs.fieldAuthRef.init();
          });
        });
    } else {
      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:EPM:PC_CHECK_STYLE`
        ), // 点检方式
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:PC_ITEM_TYPE`
        ), // 点检项类型
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:PC_COMPARE_TYPE`
        ), // 点检项比较方式
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:COMMON:WHETHER_CHAR`
        ), // 是否
      ]).then(([chechStyleRes, itemTypeRes, compareTypeRes, yesNoRes]) => {
        this.chechStyleList = chechStyleRes.data.data;
        this.itemTypeList = itemTypeRes.data.data;
        this.compareTypeList = compareTypeRes.data.data;
        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();
        this.$forceUpdate();
      });
    },
    onSelectSearchChange(pcCategoryId, pcCategoryName) {
      this.form.pcCategoryId = pcCategoryId;
      this.form.pcCategoryName = pcCategoryName;
    },
    onChangeStatus({ id }) {
      this.form.compareType = id;
      this.$refs.ruleForm.validate();
    },
    onChangeMethod({ id }) {
      this.form.methodTargetId = id;
      this.$refs.ruleForm.validate();
    },
    onChangeCompare(e) {
      this.noShowLow = false;
      this.noShowUp = false;
      switch (e) {
        case "<": // <: "点检值<上限"
          this.noShowLow = true;
          break;
        case ">": // >: "点检值>下限"
          this.noShowUp = true;
          break;
        default:
          break;
      }
    },
    onMethodChange(e) {
      this.form.checkStyle = e;
    },
    // 监听保存点击事件
    handleSave(type) {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.form.checkStyle === "NUMBER") {
            if (this.form.compareType === "<=>=") {
              if (this.form.lowerLimit > this.form.upperLimit) {
                this.$message.success(this.$t("CHECK_COMPARE_TIPS1"));
                return;
              }
            } else if (this.form.compareType === "<=>") {
              if (this.form.lowerLimit >= this.form.upperLimit) {
                this.$message.success(this.$t("CHECK_COMPARE_TIPS2"));
                return;
              }
            } else if (this.form.compareType === "<>=") {
              if (this.form.lowerLimit >= this.form.upperLimit) {
                this.$message.success(this.$t("CHECK_COMPARE_TIPS2"));
                return;
              }
            } else if (this.form.compareType === "<>") {
              if (this.form.lowerLimit >= this.form.upperLimit) {
                this.$message.success(this.$t("CHECK_COMPARE_TIPS2"));
                return;
              }
              // if (this.form.upperLimit - this.form.lowerLimit < 2) {
              //   this.$message.success(this.$t("CHECK_COMPARE_TIPS3"));
              //   return;
              // }
            } else if (this.form.compareType === "=") {
              if (this.form.lowerLimit !== this.form.upperLimit) {
                this.$message.success(this.$t("CHECK_COMPARE_TIPS4"));
                return;
              }
            }
          }
          const req = this.fieldExReqDataFn(this.form);
          delete req.id;
          this.confirmLoading = true;
          this.$axios
            .post(`${ApiConstant.PREFIX_CORE}/api/epm/pcm/pc-item`, req)
            .then(() => {
              this.$message.success(this.$t("ADD_SUCCESS"));
              this.confirmLoading = false;
              if (type === "saveAndAdd") {
                // this.form = {
                //   itemCode: "", // 点检项目编码
                //   itemName: "", // 点检项目名称
                //   opDescription: "", // 操作说明
                //   checkStyle: "BOOL", // 点检方式
                //   itemType: "NORMAL", // 点检项类型
                //   upperLimit: "", // 上线
                //   lowerLimit: "", // 下线
                //   compareType: "", // 比较方式
                //   autoMatchKey: "", // 自动匹配的Key
                //   textValue: "", // 标准值
                //   pcCategoryId: "", // 点检分类
                //   opUrl: "", // 设备图片地址
                //   imgFlag: "N", // 是否上传点检图片：是(Y);否(N)
                // };
                // this.formOld = {
                //   itemCode: "", // 点检项目编码
                //   itemName: "", // 点检项目名称
                //   opDescription: "", // 操作说明
                //   checkStyle: "BOOL", // 点检方式
                //   itemType: "NORMAL", // 点检项类型
                //   upperLimit: "", // 上线
                //   lowerLimit: "", // 下线
                //   compareType: "", // 比较方式
                //   autoMatchKey: "", // 自动匹配的Key
                //   textValue: "", // 标准值
                //   pcCategoryId: "", // 点检分类
                //   opUrl: "", // 设备图片地址
                //   imgFlag: "N", // 是否上传点检图片：是(Y);否(N)
                // };
              } else {
                this.handleCancel();
              }
            })
            .catch((e) => {
              this.confirmLoading = false;
            });
        }
      });
    },
    // 监听返回点击事件
    handleCancel() {
      this.$store.dispatch("tagsView/jumpBeforeView", {
        to: { path: "/eam/eqp_check/check_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>
