<template>
  <div
    v-if="modelData != null && modelData.data != undefined && field.visible"
    v-show="showField"
    class="form-group"
    :class="formGroupClass"
  >
    <label
      v-tooltip.right="field.help"
      class="control-label"
      :class="formGroupLabelClass"
      :style="field.cssStyle"
    >
      <span v-if="field.mandatory" class="required-mark">*</span>
      <font size="2">{{ Language.getDisplayNameTrl($i18n.locale, field) }}</font><br />
      <font v-if="isChineseEnglish && $i18n.locale == 'zh-CN'" size="0.5">{{ field.displayNameEng }}</font>
    </label>

    <div class="input-group" :class="inputGroupClass">
      <p
        v-if="
          !fieldUtil.isManyToManySetType(field) &&
            !fieldUtil.isImageType(field) &&
            !fieldUtil.isImageListType(field) &&
            !fieldUtil.isCheckBoxType(field) &&
            !fieldUtil.isRedGreenEditorType(field) &&
            !fieldUtil.isVideoType(field) &&
            !fieldUtil.isEnumMultiType(field) &&
            !fieldUtil.isImageListType(field) &&
            !fieldUtil.isEnumListType(field) &&
            !fieldUtil.isTextAreaType(field) &&
            !fieldUtil.isFileType(field) &&
            !fieldUtil.isRichTextAreaEditor(field) &&
            !fieldUtil.isNumberType(field)
        "
        v-tooltip.left="getFieldStringValue()"
        class="form-control-static input-group-item"
      >
        {{ getFieldStringValue() }}
      </p>

      <p
        v-if="fieldUtil.isNumberType(field)"
        class="form-control-static input-group-item"
      >
        {{ getFieldNumberValue() }}
      </p>

      <p v-if="fieldUtil.isRichTextAreaEditor(field)" :style="field.cssStyle">
        {{ getFieldStringValue() }}
      </p>

      <p
        v-if="fieldUtil.isTextAreaType(field)"
        v-tooltip.left="getFieldStringValue()"
        class="form-control-static"
        :class="inputGroupItemClass"
        style="word-break: break-all; white-space: pre-line"
      >
        {{ getFieldStringValue() }}
      </p>

      <p
        v-if="fieldUtil.isManyToManySetType(field)"
        class="form-control-static input-group-item"
        :class="inputGroupItemClass"
      >
        <span
          v-for="item in getManyToManyValues()"
          :key="item"
          class="input-group-item-manytomany"
        >
          {{ item }}
        </span>
      </p>

      <p
        v-if="fieldUtil.isCheckBoxType(field)"
        class="form-control-static input-group-item"
        :class="inputGroupItemClass"
      >
        {{ getFieldStringValue() == "true" ? $t("lang.TabFormFieldView.yes") : $t("lang.TabFormFieldView.no") }}
      </p>

      <p
        v-if="fieldUtil.isRedGreenEditorType(field)"
        class="form-control-static input-group-item"
        :class="inputGroupItemClass"
      >
        {{ getFieldStringValue() == "true" ? "红单" : "蓝单" }}
      </p>

      <p
        v-if="fieldUtil.isEnumListType(field)"
        class="form-control-static input-group-item"
        :class="inputGroupItemClass"
      >
        {{ getEnmuValue() === "编辑中" ? $t("lang.TabFormFieldView.editing"):
          getEnmuValue() === "审批中" ? $t("lang.TabFormFieldView.pendingApproval"):
          getEnmuValue() === "审批通过" ? $t("lang.TabFormFieldView.approved"):
          getEnmuValue() === "审批不通过" ? $t("lang.TabFormFieldView.rejected"):
          getEnmuValue() === "单据已撤回" ? $t("lang.TabFormFieldView.withdraw"):
          getEnmuValue() === "转移" ? $t("lang.TabFormFieldView.transfer"):
          getEnmuValue() === "报废" ? $t("lang.TabFormFieldView.disposal"):
          getEnmuValue() === "全盘" ? $t("lang.TabFormFieldView.overall"):
          getEnmuValue() === "抽盘" ? $t("lang.TabFormFieldView.randomInventory"):getEnmuValue()
        }}
      </p>

      <p
        v-if="fieldUtil.isEnumMultiType(field)"
        class="form-control-static input-group-item"
        :class="inputGroupItemClass"
      >
        {{ getMultiEnmuValue() }}
      </p>

      <div
        v-if="fieldUtil.isImageType(field)"
        class="form-control-static input-group"
        :class="inputGroupItemClass"
        style="display: inline-block"
        :style="field.cssStyle"
      >
        <ImageViewWidget
          v-if="fieldUtil.isImageType(field)"
          :field="field"
          :field-value="fieldValue"
          :class-name="className"
        />
      </div>
      <div
        v-if="fieldUtil.isImageListType(field)"
        class="form-control-static"
        :class="inputGroupItemClass"
        :style="field.cssStyle"
      >
        <ImageListViewWidget
          v-if="fieldUtil.isImageListType(field)"
          :key="'ImageListViewWidget' + new Date().getTime()"
          :field="field"
          :field-value="fieldValue"
          :class-name="className"
        />
      </div>

      <div
        v-if="fieldUtil.isVideoType(field)"
        class="form-control-static"
        :class="inputGroupItemClass"
        :style="field.cssStyle"
      >
        <VideoListWidget
          v-if="fieldUtil.isVideoType(field)"
          :field="field"
          :field-value="fieldValue"
          :class-name="className"
          :readonly="readOnly"
        />
      </div>

      <div
        v-if="fieldUtil.isFileType(field)"
        :class="inputGroupItemClass"
        :style="field.cssStyle"
        style="display: inline-block"
      >
        <FileListWidget
          v-if="fieldUtil.isFileType(field)"
          :field="field"
          :field-value="fieldValue"
          :class-name="className"
          :readonly="true"
        />
      </div>

      <div v-if="fieldUtil.isButtonType(field)" style="display: inline-block">
        <ButtonWidget
          :field="field"
          :field-value="fieldValue"
          :readonly="readOnly"
          @execute-callout="executeCallout"
        />
      </div>
    </div>
  </div>
</template>

<script>
import fieldUtil from '../../resource/dictionary/FieldUtil.js';
import WindowClientUtil from '../../resource/dictionary/WindowClientUtil.js';
import Language from '../../common/Language.js';
import Context from '../common/Context.js';

import EnumSelectWidget from '../tabFormWidget/EnumSelectWidget.vue';
import SelectWidget from '../tabFormWidget/SelectWidget.vue';
import EnumRadioGroupWidget from '../tabFormWidget/EnumRadioGroupWidget.vue';
import VideoListWidget from '../tabFormWidget/VideoListWidget.vue';
import FileListWidget from '../tabFormWidget/FileListWidget.vue';
import ButtonWidget from '../tabFormWidget/ButtonWidget.vue';

import ImageViewWidget from '../tabFormWidget/ImageViewWidget.vue';
import ImageListViewWidget from '../tabFormWidget/ImageListViewWidget.vue';
import JsUtil from '../../common/JsUtil.js';
import { SqlApi } from 'pc-component-v3';
import { Notify, Uuid } from 'pc-component-v3';
export default {
  components: {
    ImageViewWidget,
    ImageListViewWidget,
    EnumSelectWidget,
    SelectWidget,
    EnumRadioGroupWidget,
    VideoListWidget,
    FileListWidget,
    ButtonWidget,
  },

  props: {
    className: {
      type: String,
      default: null,
    },
    multipleColumn: {
      type: Boolean,
      default: null,
    },
    jsUrl: {
      type: String,
      default: null,
    },
    field: {
      type: Object,
      default: function () {
        return null;
      },
    },
    modelData: {
      type: Object,
      default: function () {
        return null;
      },
    },
    isChineseEnglish: {
      type: Boolean,
      default: null,
    },
  },

  emits: ['executeCallout'],

  data: function () {
    this.Language = Language;
    var value =
      this.modelData.data == undefined ||
      this.modelData.data[this.field.fieldName] == undefined
        ? ''
        : this.modelData.data[this.field.fieldName].displayValue.join(', ');

    var fieldValue =
      this.modelData.data == undefined ? [] : this.modelData.data[this.field.fieldName];

    return {
      displayValue: value,
      fieldValue: fieldValue,
      fieldUtil: fieldUtil,
      showField: true, // 显示字段
    };
  },

  computed: {
    /**
     * 表单组的CSS样式
     * 对应 bootstrap 表单 form-group
     */
    formGroupClass: function () {
      return {
        'form-group-single-row': this.field != undefined && this.field.singleRow,
        'form-group-multiple-row': this.field != undefined && !this.field.singleRow,
      };
    },

    /**
     * 标题的CSS样式
     * 对应 bootstrap 表单 label 样式
     */
    formGroupLabelClass: function () {
      return {
        'm-sr-only': this.field == null || !this.field.visible || !this.field.showLabel, // 显示/隐藏
        'col-xs-5 col-sm-4 col-md-3 col-lg-2':
          this.field != null && this.multipleColumn == false, // 单列
        'label-multiple-column': this.field != null && this.multipleColumn == true, // 多列
      };
    },

    /**
     * 控件的CSS样式
     * 对应 bootstrap 表单 input-group
     */
    inputGroupClass: function () {
      return {
        'col-xs-7 col-sm-8 col-md-9 col-lg-10':
          this.field != null && this.multipleColumn == false, // 单列
        'input-group-multiple-column': this.multipleColumn, // 多列
        'input-group-single-row':
          this.field != undefined && this.field.singleRow == true && this.multipleColumn, // 单独一行
      };
    },

    /**
     * 控件的CSS样式
     * 对应 bootstrap 表单 input-group 内的元素
     */
    inputGroupItemClass: function () {
      return {};
    },

    readOnly: function () {
      if (this.field == undefined) {
        return true;
      }

      if (this.field != undefined && this.field.readOnly == true) {
        return true;
      }

      if (this.field != undefined && this.field.entityFieldIndex > 0) {
        return true;
      }

      if (
        this.modelData != undefined &&
        this.modelData.id > 0 &&
        (this.field.updatable == undefined || this.field.updatable == false)
      ) {
        return true;
      }

      return this.field.readOnly;
    },
  },

  watch: {
    'modelData.data': {
      deep: true,
      handler(curVal, oldVal) {
        this.displayValue =
          curVal == undefined ||
          curVal[this.field.fieldName] == undefined ||
          curVal[this.field.fieldName].displayValue == undefined
            ? ''
            : curVal[this.field.fieldName].displayValue[0];
        this.fieldValue = curVal == undefined ? [] : curVal[this.field.fieldName];
        this.showLogical();
      },
    },
  },

  mounted: function () {
  },

  methods: {
    /**
     * 获取Context
     */
    getContext: Context,

    /**
     * 执行Callout
     */
    executeCallout: function (field) {
      this.$emit('executeCallout', field);
    },

    // 获取String字符串
    getFieldStringValue: function () {
      var value = '';
      if (
        this.fieldValue == undefined ||
        this.fieldValue.displayValue == undefined ||
        this.fieldValue.displayValue.length < this.field.entityFieldIndex
      ) {
        return '';
      } else {
        value = fieldUtil.formatNumbers(
          this.fieldValue.displayValue[this.field.entityFieldIndex],
          this.field.pattern,
          this.field.displayType,
        );
        return value;
      }
    },

    // 获取Number
    getFieldNumberValue: function () {
      if (
        this.fieldValue == undefined ||
        this.fieldValue.displayValue == undefined ||
        this.fieldValue.displayValue.length < this.field.entityFieldIndex
      ) {
        return '';
      } else {
        return this.fieldValue.displayValue[this.field.entityFieldIndex];
      }
    },

    showLogical: function (field) {
      let _self = this;

      var logic = this.field.showLogical;
      if (logic == null || logic == '') {
        this.showField = true;
        return;
      }

      let functionName = this.field.fieldName.replace('.', '_') + '_showLogical';


      let executeFunction = function(){
        try{
          let context = new _self.getContext(_self.modelData);
          _self.showField = _self[functionName](context);
        }catch(error){
          console.error(error);
          Notify.error('数据字典定义异常', '【' + logic + '】前端列显示逻辑定义异常,请联系管理员检查数据字典的定义。', false);
        }
      };

      if (_self[functionName] == null) {
        const jsUrl = _self.jsUrl;
        if (jsUrl == null || jsUrl == undefined) {
          Notify.error(
            '数据字典定义异常',
            '【' +
              logic +
              '】前端列显示逻辑的JS文件不存在,请联系管理员检查数据字典是否JS文件。',
            false,
          );
          return;
        }
        let promise = JsUtil.dynamicLoadJsFunction(jsUrl, logic);
        promise.then(
          targetFunction => {            
            _self[functionName] = targetFunction;

            if(_self[functionName] == null){
              Notify.error('数据字典定义异常', '【' + logic + '】前端列显示逻辑方法不存在,请联系管理员检查数据字典。', false);
              return;
            }

            executeFunction();
          },
          errorData => {
            console.error(errorData);
          },
        );
      } else {
        executeFunction();
      }
    },

    /**
     * 获取枚举单选框的值
     */
    getEnmuValue: function () {
      var _self = this;
      var result;
      if (_self.fieldValue != undefined && _self.fieldValue.displayValue != undefined) {
        var value0 = _self.fieldValue.displayValue[0];
        if (_self.field != null && _self.field.keyValues != null) {
          _self.field.keyValues.forEach(function (item1) {
            if (value0 == item1.keyStr) {
              result = item1.value;
            }
          });
        }
      }
      return result;
    },

    /**
     * 获取枚举多选框的值
     */
    getMultiEnmuValue: function () {
      var _self = this;
      var result = [];
      if (_self.fieldValue != undefined && _self.fieldValue.displayValue != undefined) {
        var arr = _self.fieldValue.displayValue[0].split(',');
        arr.forEach(function (item) {
          _self.field.keyValues.forEach(function (item1) {
            if (item == item1.keyStr) {
              result.push(item1.value + ' ');
            }
          });
        });
      }
      return result.join(',');
    },

    // 获取ManyToManySetType值
    getManyToManyValues: function () {
      if (
        this.fieldValue == undefined ||
        this.fieldValue.displayValue == undefined ||
        this.fieldValue.displayValue.length < this.field.index
      ) {
        return [];
      } else {
        return this.fieldValue.displayValue;
      }
    },
  },
};
</script>

<style scoped>
.required-mark {
  color: red;
  margin-right: 10px;
}

.form-group-single-row {
  display: block;
  width: 100%;
}

.input-group-item {
  word-break: break-all;
}

.input-group-item-manytomany {
  color: #333;
  background-color: #f0f0f0;
  border: 1px solid #ccc;
  border-radius: 4px;
  height: 26px;
  margin: 4px 4px 0px 0px;
  padding: 6px 0.25em;
}

.label-multiple-column {
  width: 120px;
}

@media (max-width: 768px) {
  .input-group-single-row {
    width: 100%;
  }

  .input-group-item {
    padding-top: 0px;
  }
}

@media (min-width: 768px) {
  .label-multiple-column {
    text-overflow: ellipsis;
    text-align: right;
    padding-right: 5px;
  }

  .input-group-multiple-column {
    width: 230px;
  }

  .input-group-single-row {
    width: calc(100% - 200px) !important;
    word-wrap: break-word;
  }
}

.m-sr-only {
  visibility: hidden;
}
</style>
