<template>
  <div class="subfield-item-container" :class="classCreate(comChildModuleInfo.comType)" :style="styles" @click="activeSubfieldItem">
    <img src="@/assets/images/consultingAgencyManagement/customForm/icon_drag@2x.png" alt="" class="subfield-module-item-dragg-target-icon">
    <el-form-item class="subfield-module-form-item"
      :class="{'is-required': comChildModuleInfo.formAttribute.required,'is-error' : comChildModuleInfo.formAttribute.isError}"
      :label="comChildModuleInfo.formAttribute.label" :prop="propValue">
      <!-- 单行文本类型 -->
      <el-input v-model="comChildModuleInfo.componentAttribute.value" :placeholder="comChildModuleInfo.componentAttribute.placeholder" clearable
        v-if="comChildModuleInfo.comType == 'text'" :disabled="isDisabled"></el-input>
      <!-- 多行文本类型 -->
      <el-input type="textarea" v-model="comChildModuleInfo.componentAttribute.value" :placeholder="comChildModuleInfo.componentAttribute.placeholder"
        :show-word-limit="false" clearable v-if="comChildModuleInfo.comType == 'textarea'" :disabled="isDisabled"></el-input>
      <!-- 下拉框类型 -->
      <el-select v-model="comChildModuleInfo.componentAttribute.value" :multiple="comChildModuleInfo.formAttribute.isMultiple"
        :collapse-tags="comChildModuleInfo.formAttribute.isMultiple" :placeholder="comChildModuleInfo.componentAttribute.placeholder"
        v-if="comChildModuleInfo.comType == 'select'" :disabled="isDisabled">
        <el-option v-for="(item,index) in comChildModuleInfo.formAttribute.selectOptions" :key="item.id" :label="item.value" :value="item.value">
        </el-option>
      </el-select>
      <!-- 时间类型 -->
      <el-date-picker v-model="comChildModuleInfo.componentAttribute.value" type="datetime" :value-format="'yyyy-MM-dd HH:mm:ss'"
        :placeholder="comChildModuleInfo.componentAttribute.placeholder" :disabled="isDisabled" v-if="comChildModuleInfo.comType == 'date'">
      </el-date-picker>
      <!-- 电话类型 -->
      <el-input v-model="comChildModuleInfo.componentAttribute.value" :placeholder="comChildModuleInfo.componentAttribute.placeholder" clearable
        v-if="comChildModuleInfo.comType == 'phone'" :disabled="isDisabled"></el-input>
      <!-- 电子邮箱类型 -->
      <dsk-email-input v-model="comChildModuleInfo.componentAttribute.value" :placeholder="comChildModuleInfo.componentAttribute.placeholder"
        :clearable="true" :disabled="isDisabled" v-if="comChildModuleInfo.comType == 'email'"></dsk-email-input>
      <!-- 图片类型 -->
      <dsk-photo-input v-model="comChildModuleInfo.componentAttribute.value" :disabled="isDisabled" v-if="comChildModuleInfo.comType == 'photo'"
        :limit="comChildModuleInfo.formAttribute.limit" :presentationModel="true"></dsk-photo-input>
      <!-- 文件类型 -->
      <dsk-file-input v-model="comChildModuleInfo.componentAttribute.value" :disabled="isDisabled" v-if="comChildModuleInfo.comType == 'file'"
        :limit="comChildModuleInfo.formAttribute.limit" :presentationModel="true"></dsk-file-input>
    </el-form-item>

    <img src="@/assets/images/consultingAgencyManagement/customForm/icon_delete@2x.png" alt="" class="remove-subfield-item-icon"
      @click.stop="removeModuleItem">
  </div>
</template>
<script>
import { cloneDeep } from "lodash-es";
import Schema from "async-validator";
import DskEmailInput from "@/components/DskEmailInput";
import DskPhotoInput from "@/components/DskPhotoInput";
import DskFileInput from "@/components/DskFileInput";
export default {
  name: "subfieldItem",
  components: {
    DskEmailInput,
    DskPhotoInput,
    DskFileInput
  },
  props: {
    childModuleInfo: Object,
    parentUid: String,
    activeUid: String,
    childModuleIndex: Number,
    childItemIndex: Number
  },
  watch: {
    childModuleInfo: {
      handler(newValue) {
        this.comChildModuleInfo = cloneDeep(newValue);
        this.comChildModuleInfoOriginData = cloneDeep(newValue);
      },
      deep: true
    },
    comChildModuleInfo: {
      handler(newValue) {
        // console.log(this.comActiveUid !== this.comChildModuleInfo?.uid, "是否不是更改的当前元素");
        if (this.comActiveUid !== this.comChildModuleInfo?.uid) return;
        this.checkValidator(newValue);
        this.$mitt.emit("subfieldItemChange", newValue);
      },
      deep: true
    },
    activeUid: {
      handler(newValue, oldValue) {
        // 当前命中高亮的元素id  不跟当前元素uid相同 移除事件订阅 否者 添加订阅
        this.comActiveUid = newValue;
        this.comOldActiveUid = oldValue;
        this.addSubscription(newValue);
      },
      // 保证首次触发 判断是否订阅
      immediate: true
    },
    childModuleIndex: {
      handler(newValue) {
        this.comChildModuleIndex = newValue;
      },
      immediate: true
    },
    childItemIndex: {
      handler(newValue) {
        this.comChildItemIndex = newValue;
      },
      immediate: true
    }
  },
  data() {
    return {
      comChildModuleInfo: cloneDeep(this.childModuleInfo),
      comChildModuleInfoOriginData: cloneDeep(this.childModuleInfo),
      comActiveUid: this.activeUid,
      comOldActiveUid: this.activeUid,
      comChildModuleIndex: this.childModuleIndex,
      comChildItemIndex: this.childItemIndex,
    };
  },
  //可访问data属性
  created() {
    this.$mitt.on("fieldOptionChange", this.setFieldOption);
  },
  beforeDestroy() {
    this.$mitt.off("fieldOptionChange");
  },
  //计算集
  computed: {
    styles() {
      return {
        width: this.comChildModuleInfo.formAttribute ? `${this.comChildModuleInfo.formAttribute.width}%` : "100%"
      };
    },
    isDisabled() {
      return !(this.comActiveUid === this.comChildModuleInfo?.uid);
    },
    propValue() {
      return `subfieldModuleList[${this.childModuleIndex}].children[${this.childItemIndex}].componentAttribute.value`;
    }
  },
  //方法集
  methods: {
    // 验证
    async checkValidator(item) {
      try {
        const { formAttribute, componentAttribute } = item;
        const validator = new Schema({
          value: formAttribute.rules
        });
        const flag = await validator.validate({ value: componentAttribute.value }, { first: true });
        if (flag) {
          this.$set(this.comChildModuleInfo.formAttribute, "isError", false);
        }
      } catch (error) {
        const { errors, fields } = error;
        // console.log(errors, fields);
        this.$set(this.comChildModuleInfo.formAttribute, "isError", true);
      }
    },
    // 根据命中的id 来添加发布订阅
    addSubscription(newValue) {
      // if (newValue === this.comChildModuleInfo.uid) {
      //   this.$mitt.on("fieldOptionChange", this.setFieldOption);
      //   return;
      // };
      // this.$mitt.off("fieldOptionChange");
    },
    classCreate(comType) {
      const classParams = {
        'is-active-subfield-item': this.comActiveUid == this.comChildModuleInfo.uid,
        [`custom-subfielditem-${comType}`]: true
      };
      return classParams;
    },
    setFieldOption(value) {
      // console.log("触发：fieldOptionChange");
      // value.uid 等同于 comActiveUid （原因 ： 能修改的元素一定是当前comActiveUid命中的元素，取value.uid 为了修改数据的严谨）
      // 要修改的uid元素不是当前元素的id 不进行修改
      // console.log(`${this.comChildModuleInfo?.uid} 当前组件元素uid`, `${value.uid} 当前需要触发修改数据的uid`);
      if (value.uid !== this.comChildModuleInfo?.uid) return;
      this.comChildModuleInfo = value;
    },
    removeModuleItem() {
      this.$emit("removeModuleItem", this.comChildModuleInfo, this.parentUid);
    },
    activeSubfieldItem() {
      if (this.comActiveUid == this.comChildModuleInfo?.uid) return;
      this.$emit("activeSubfieldItem", this.comChildModuleInfo, this.parentUid);
    }
  },
}
</script>
<style lang="scss" scoped>
.subfield-item-container {
  width: 100%;
  min-height: 56px;
  padding: 12px 16px 12px 32px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  background: #dcebff;

  transition: width 0.3s linear;

  &.is-active-subfield-item {
    border: 1px solid #0081ff;
  }

  .subfield-module-item-dragg-target-icon {
    width: 14px;
    height: 14px;
    cursor: move;
  }

  ::v-deep .subfield-module-form-item {
    display: flex;
    max-width: calc(100% - 14px - 16px - 12px - 12px);
    margin-bottom: 0px;
    margin-left: 12px;

    .el-form-item__label {
      line-height: 32px;
      font-size: 14px;
      font-weight: 400;
      color: rgba(35, 35, 35, 0.8);
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      max-width: 55%;
    }

    .el-form-item__content {
      flex: 1;
      line-height: 32px;
      height: 32px;
      .el-input {
        line-height: 32px;
        height: 32px;
        .el-input__suffix {
          display: flex;
          align-items: center;
        }
      }
    }

    .el-input {
      width: 100%;
      .el-input__inner {
        width: 100%;
        height: 32px;
        line-height: 32px;
        padding-left: 12px;

        &::placeholder {
          color: #c0c4cc !important;
          font-size: 14px !important;
        }
      }
      .el-input__suffix {
        .el-input__icon {
          line-height: 32px;
        }
      }
    }
  }

  .remove-subfield-item-icon {
    width: 16px;
    height: 16px;
    margin-left: 12px;
    cursor: pointer;
  }

  /* 多行文本样式 */
  &.custom-subfielditem-textarea {
    .subfield-module-item-dragg-target-icon {
      align-self: flex-start;
      margin-top: 4px;
    }
    .remove-subfield-item-icon {
      align-self: flex-start;
      margin-top: 4px;
    }
    ::v-deep .subfield-module-form-item {
      .el-form-item__label {
        line-height: 22px;
      }
      .el-form-item__content {
        line-height: 32px;
        height: unset;
      }
      .el-textarea {
        .el-textarea__inner {
          resize: unset;
          min-height: 76px !important;
          font-size: 14px;
          font-family: Arial;
          &::placeholder {
            color: #c0c4cc !important;
            font-size: 14px !important;
          }
        }
      }
    }
  }

  /* 下拉选择框 */
  &.custom-subfielditem-select {
    ::v-deep .el-form-item {
      .el-select {
        width: 100%;
        .el-input__inner {
          border-radius: 2px;
        }
      }
    }
  }

  // 时间选择样式
  &.custom-subfielditem-date {
    ::v-deep .el-form-item {
      .el-date-editor {
        .el-input__prefix {
          display: none;
        }
      }
    }
  }
}
</style>
