<template>
  <form-item-wrapper
    :designer="designer"
    :field="field"
    :rules="rules"
    :design-state="designState"
    :parent-widget="parentWidget"
    :parent-list="parentList"
    :index-of-parent-list="indexOfParentList"
    :sub-form-row-index="subFormRowIndex"
    :sub-form-col-index="subFormColIndex"
    :sub-form-row-id="subFormRowId"
  >
    <el-button
      icon="el-icon-plus"
      type="warning"
      class="el-button-tag"
      v-if="designState"
    ></el-button>
    <div v-else>
      <el-tag
        v-for="(tag, index) in fieldModel"
        :key="index"
        type="warning"
        :disable-transitions="false"
        :closable="!field.options.disabled && field.options.tabDeleteEnabled"
        @close="deleteCallback(index)"
      >
        <el-tooltip
          :enterable="false"
          effect="dark"
          :content="tag[field.options.tagLabelField]"
          placement="bottom"
        >
          <span :style="tagStyle">{{ tag[field.options.tagLabelField] }}</span>
        </el-tooltip>
      </el-tag>
      <el-button
        icon="el-icon-plus"
        type="warning"
        class="el-button-tag"
        @click="openProjectTagDialog"
        v-if="!field.options.disabled"
      ></el-button>
    </div>
  </form-item-wrapper>
</template>

<script>
import FormItemWrapper from "./form-item-wrapper";
import emitter from "../../../../../components/xform/utils/emitter";
import i18n from "../../../../../components/xform/utils/i18n";
import fieldMixin from "../../../../../components/xform/form-designer/form-widget/field-widget/fieldMixin";

export default {
  name: "project-tag-widget",
  componentName: "FieldWidget", //必须固定为FieldWidget，用于接收父级组件的broadcast事件
  mixins: [emitter, fieldMixin, i18n],
  props: {
    field: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    designer: Object,

    designState: {
      type: Boolean,
      default: false,
    },

    subFormRowIndex: {
      /* 子表单组件行索引，从0开始计数 */ type: Number,
      default: -1,
    },
    subFormColIndex: {
      /* 子表单组件列索引，从0开始计数 */ type: Number,
      default: -1,
    },
    subFormRowId: {
      /* 子表单组件行Id，唯一id且不可变 */ type: String,
      default: "",
    },
  },
  components: {
    FormItemWrapper,
  },
  inject: ["refList", "globalOptionData", "globalModel", "getFormConfig"],
  data() {
    return {
      oldFieldValue: [], //field组件change之前的值
      fieldModel: [],
      rules: [],
    };
  },
  watch: {
    fieldModel(val) {
      this.handleChangeEvent(val);
    },
  },
  computed: {
    formDataId() {
      let formRef = this.getFormRef();
      return formRef.dataId;
    },
    limit() {
      return this.field.options.limit ? this.field.options.limit : null;
    },
    multi() {
      return this.limit !== 1;
    },
    tagStyle() {
      let result = {};
      let tagWidth = this.field.options.tagWidth;
      if (tagWidth) {
        result.width = tagWidth;
        // result.overflow = "hidden";
        result.textOverflow = "ellipsis";
        // result.whiteSpace = "nowrap";
      }
      return result;
    },
  },
  beforeCreate() {
    /* 这里不能访问方法和属性！！ */
  },

  created() {
    /* 注意：子组件mounted在父组件created之后、父组件mounted之前触发，故子组件mounted需要用到的prop
       需要在父组件created中初始化！！ */

    this.initFieldModel();
    this.registerToRefList();
    this.initEventHandler();
    this.buildFieldRules();

    this.handleOnCreated();
  },

  mounted() {
    this.handleOnMounted();
  },

  beforeDestroy() {
    this.unregisterFromRefList();
  },
  methods: {
    loadDataDefaultHandle() {
      let dataId = this.formDataId;
      let reportTemplate = this.getFormRef().reportTemplate;
      let formCode = reportTemplate.formCode;
      let formScriptEnabled = this.field.options.formScriptEnabled || false;
      let scriptCode = this.field.options.formScriptCode || "getList";
      if (!scriptCode) return;
      let accessParam = this.handleCustomEvent(this.field.options.formScriptParam);
      return this.formHttp({
        scriptCode: scriptCode,
        data: {
          formCode: formCode,
          formVersion: reportTemplate.formVersion,
          taBm: this.fieldKeyName,
          data: {
            ...accessParam,
            id: dataId,
          },
        },
        callback: (res) => {
          let rows = res.objx || [];
          this.setValue(rows);
          this.handleCustomEvent(this.field.options.formScriptSuccess, ["res"], [res]);
        },
      });
    },
    openProjectTagDialog() {
      if (this.field.options.onClick) {
        this.handleCustomEvent(this.field.options.onClick);
        return;
      }
      let formCode = this.field.options.tagFormCode;
      let tagLabelField = this.field.options.tagLabelField;
      let tagUniqueField = this.field.options.tagUniqueField;
      let tagFormLabelField = this.field.options.tagFormLabelField;
      let tagFormUniqueField = this.field.options.tagFormUniqueField;
      /*let checkRows = this.fieldModel.map(item => {
        return {
          [tagFormUniqueField]: item[tagUniqueField] ?? null,
          [tagFormLabelField]: item[tagLabelField] ?? null,
        }
      })*/
      let queryParam = null;
      if (this.field.options.tagFormParam) {
        queryParam = this.handleCustomEvent(this.field.options.tagFormParam);
      }
      this.getFormRef().openSearchDialog({
        formCode,
        queryParam,
        // rows: checkRows,
        multiple: true,
        confirm: (rows) => {
          if (!this.field.options.tagConfirmCallback) {
            let tagFillConfig = this.field.options.tagFillConfig || [];
            let items = rows.map((item) => {
              let newData = {
                [tagUniqueField]: item[tagFormUniqueField],
                [tagLabelField]: item[tagFormLabelField],
              };
              tagFillConfig.forEach((item1) => {
                newData[item1.targetField] = item[item1.sourceField];
              });
              return newData;
            });
            this.addTagData(items);
          } else {
            this.handleCustomEvent(
              this.field.options.tagConfirmCallback,
              ["rows"],
              [rows]
            );
          }
        },
      });
    },
    addTagData(rows) {
      let tagUniqueField = this.field.options.tagUniqueField;
      let keys = this.fieldModel.map((item) => item[tagUniqueField]);
      let items = rows.filter((item) => !keys.includes(item[tagUniqueField]));
      this.fieldModel.push(...items);
    },
    deleteCallback(index) {
      this.fieldModel.splice(index, 1);
      this.handleCustomEvent(this.field.options.tagDeleteCallback);
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/styles/global.scss"; //* form-item-wrapper已引入，还需要重复引入吗？ *//

.full-width-input {
  width: 100% !important;
}

.hideUploadDiv {
  ::v-deep div.el-upload--picture-card {
    /* 隐藏最后的图片上传按钮 */
    display: none;
  }

  ::v-deep div.el-upload--text {
    /* 隐藏最后的文件上传按钮 */
    display: none;
  }

  ::v-deep div.el-upload__tip {
    /* 隐藏最后的文件上传按钮提示 */
    display: none;
  }
}
</style>
