<template>
  <div>
    <Navbar
      :title="processReportDto.name"
      :is-go-back="processReportDto.goback"
    />
    <div>
      <h5>{{ processReportDto.description }}</h5>
    </div>
    <div>
      <div class="form-inline">
        <div
          v-for="(item, index) in parameters"
          :key="'parameter-' + index"
          class="form-group m-form-group"
        >
          <div class="form-inline-div">
            <label
              v-if="item.displayType != 'ListBoxEnumEditor'"
              :for="'editor_' + item.id"
            >{{ item.displayName }}</label>

            <input
              v-if="item.displayType =='TextEditor'"
              :id="'editor_' + item.id"
              v-model="item.fieldValue.displayValue[0]"
              autocomplete="off"
              type="text"
              class="form-control m-input-group"
              placeholder="请输入内容"
              @change="valueChanged(item)"
            />

            <textarea
              v-if="item.displayType =='TextAreaEditor'"
              :id="'editor_' + item.id"
              v-model="item.fieldValue.displayValue[0]"
              rows="5"
              type="text"
              class="form-control m-input-group"
              placeholder="请输入内容"
              @change="valueChanged(item)"
            />

            <input
              v-if="item.displayType =='NumberEditor'"
              :id="'editor_' + item.id"
              v-model="item.fieldValue.displayValue[0]"
              autocomplete="off"
              type="number"
              class="form-control m-input-group"
              placeholder="请输入数字"
              @change="valueChanged(item)"
            />


            <Switches
              v-if="item.displayType =='CheckBoxEditor'"
              v-model="item.fieldValue.displayValue[0]"
              color="green"
              type-bold="true"
              @change="valueChanged(item)"
            />

            <DateTime
              v-if="item.displayType =='DateTimeBoxEditor'"
              :id="'editor_' + item.id"
              v-model="item.fieldValue.displayValue[0]"
              class="m-input-group"
              name="datetime"
              @update:model-value="changeValue(item, $event)"
            />

            <EnumSelectWidget
              v-if="item.displayType =='ListBoxEnumEditor'"
              :field="item"
              :field-value="item.fieldValue"
              class="m-input-group"
              @value-changed="valueChanged($event, item)"
            />

            <MultiSearchWidget
              v-if="item.displayType =='MultiSearchBoxEditor'"
              :info-window-no="item.infoWindowNo"              
              :where-clause-source="{'processReportParameter': {'processReportNo': processReportDto.no, 'fieldName': item.fieldName}}"
              :field="item"
              :field-value="item.fieldValue"
              class="m-input-group"
              :display-name="item.listDisplayFieldNames"
              @value-changed="tabValueChanged($event, item)"
            />

            <SearchWidget
              v-if="item.displayType =='SearchBoxEditor'"
              :where-clause-source="{'processReportParameter': {'processReportNo': processReportDto.no, 'fieldName': item.fieldName}}"
              :info-window-no="item.infoWindowNo"
              :field="item"
              :field-value="item.fieldValue"
              :display-name="item.listDisplayFieldNames"
              class="m-input-group"
              :parent-model-data="parentModelData"
              @value-changed="tabValueChanged($event, item)"
            />
          </div>
          <!--<div v-if = "item.constraintEnum == 'Between'" class="form-inline-div">
						<label v-if="item.displayType != 'ListBoxEnumEditor'" :for="'editor_' + item.id">——</label>
						<input autocomplete="off" v-if="item.displayType =='NumberEditor'" type="number" v-model="item.value2" 
              class="form-control m-input-group" :id="'editor_' + item.id" placeholder="请输入数字" @change="valueChanged(item)"/>
		
						<DateTime v-if="item.displayType =='DateTimeBoxEditor'" :dateValue="item.value2" 
            class="form-control m-input-group" name="datetime" 
            :id="'editor_' + item.id" @on-value-change="changeValue(item, $event)" />
					</div>	-->
        </div>
      </div>
      <div class="form-group">
        <button
          v-if="processReportDto.htmlHelpUrl != null && processReportDto.htmlHelpUrl != ''"
          class="btn btn-default"
          @click="openHtmlHelp(processReportDto.htmlHelpUrl)"
        >
          <span class="glyphicon glyphicon-question-sign" />
        </button>
        <input
          autocomplete="off"
          type="button"
          class="btn btn-primary"
          style="margin-top: 15px;"
          value="确定"
          @click="runProcessDynamic()"
        />
      </div>
      <ProcessReportResultPreview
        :process-report-result="processReportResult"
        :pdf-only="processReportDto.pdfOnly"
        :excel-only="processReportDto.excelOnly"
      />
    </div>

    <Loading v-if="loading" />
  </div>
</template>

<script>
import { defineAsyncComponent } from 'vue';

import Common from '../../common/Common.js';

import Navbar from '../../navbar/src/Navbar.vue';
import DateTime from '../../datetime/src/DateTime.vue';
import Loading from '../../loading/src/Loading.vue';
import ProcessReportResultPreview from './ProcessReportResultPreview.vue';
import SearchWidget from '../../info/src/SearchWidget.vue';
import Switches from '../../switches/src/Switches.vue';



export default {

  components: {
    DateTime,
    MultiSearchWidget : defineAsyncComponent(() =>
      import('../../info/src/MultiSearchWidget.vue'),
    ),
    Loading,
    ProcessReportResultPreview,
    SearchWidget,
    Switches,
    Navbar,
  },
  props: {
    'processReportDto':{
      type: Object,
      default: null,
    },
  },

  emits:['valueChanged'],
  data: function () {
    return {
      'processReportId': '',
      'processReportDtos': {},
      'processResultData': '',
      'processReportResult': {},
      'parameters': [],
      'parentModelData': {
        'data': {
        },
      },
      loading: false,
    };
  },

  //监控processReportDto，当dto变化时重新渲染界面
  watch: {
    'processReportDto': function (to, from) {
      this.parameters = [];
      this.processReportResult.reportResults = undefined;
      this.initData(this.processReportDto);
    },
    'processReportDto.processReportParameters': function () {
      this.initData(this.processReportDto);
    },
    // 路由切换的时候清空报表结果数据
    '$route': function () {
      this.processReportResult = {};
    },

  },

  mounted: function () {
    this.initData(this.processReportDto);
  },

  methods: {
    /**
         * 打开帮助页面
         */
    openHtmlHelp: function (htmlHelpUrl) {
      window.open(htmlHelpUrl);
    },


    /**
         * 初始化数据
         * @param  {Object} data 流程报表数据
         * @return {void}
         */
    initData: function (data) {
      console.log('获取的参数列表：' + JSON.stringify(data));
      var _self = this;
      if (data == undefined) {
        return;
      }
      _self.parameters = [];
      if (data.processReportParameters) {
        data.processReportParameters.forEach(function (item) {
          if (item.constraintEnum == 'Between') {
            var cloneObject1 = _self.cloneParameter(item);
            _self.parameters.push(cloneObject1);
            var cloneObject = {
              'index': 2,
              'isMandatory': false,
              'id': item.id,
              'fieldName': item.fieldName + '2',
              'name': item.name,
              'help': item.help,
              'displayType': item.displayType,
              'listDisplayFieldNames': item.listDisplayFieldNames,
              'infoWindowId': item.infoWindowId,
              'sortNo': item.sortNo,
              'isShow': item.isShow,
              'constraintEnum': item.constraintEnum,
              'enumClass': item.enumClass,
              'fieldValue': {
                'id': '',
                'constraintEnum': item.constraintEnum,
                'displayValue': [],
                'fieldType': 'String',
              },
              'calloutProcessNo': item.calloutProcessNo,
              'listDisplayFieldName': item.listDisplayFieldName,
              'displayName': '～',
              'infoWindowNo': item.infoWindowNo,

            };
            _self.parentModelData.data[cloneObject.fieldName] = cloneObject.fieldValue;
            console.log(cloneObject);
            _self.parameters.push(cloneObject);
          } else {
            var obj = _self.cloneParameter(item);
            _self.parameters.push(obj);
          }
        });
      }
      // 排序
      _self.parameters.sort(function (a, b) {
        return a.sortNo - b.sortNo;
      });

      console.log(_self.parameters);
      //_self.processReportDto = data;
    },

    /**
         * 执行流程
         * @return {void}
         */
    runProcessDynamic: function () {
      var _self = this;
      _self.processResultData = {
        'processReportNo': _self.processReportDto.no,
        'modelData': {
          data: {},
        },
      };
      _self.parameters.forEach(function (item) {
        var fieldName = item.fieldName;
        _self.processResultData.modelData.data[fieldName] = item.fieldValue;
      });
      _self.processReportResult = {};

      _self.loading=true;
      $.ajax({
        url: Common.getApiURL('ProcessReportResource/runProcessDynamic'),
        type: 'post',
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        contentType: 'application/json',
        data: JSON.stringify(_self.processResultData),
        success: function (data) {
          _self.loading=false;
          _self.processReportResult = data;

          if (_self.processReportResult.reportResults != undefined && _self.processReportResult.reportResults.length > 0) {
            _self.processReportResult.reportResults.forEach(function (item, index) {
              item.previewIndex=1;
              if (index == 0) {
                item.showPreview=true;
              } else {
                item.showPreview=false;
              }
            });
          }
          // _self.processReportDto.excelOnly = false;
          // _self.processReportDto.pdfOnly = true;

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading=false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
         * 时间选择框数据发生改变
         * @param  {Object} item     当前field
         * @param  {String} newValue 改变后的值
         * @return {void}          
         */
    changeValue: function (item, newValue) {
      item.fieldValue.displayValue[0]=newValue;
      this.valueChanged(item);
    },

    /**
         * 搜索框值发生改变
         * @param  {Object} newFieldValue 改变后的值
         * @param  {Object} item          当前field
         * @return {void}               
         */
    tabValueChanged: function (newFieldValue, item) {
      item.fieldValue = newFieldValue;
      this.valueChanged(item);
    },

    /**
         * 复制参数
         * @param {Object} 
         */
    cloneParameter: function (parameter) {
      var cloneObject = {
        'index': 1,
        'isMandatory': false,
        'id': parameter.id,
        'fieldName': parameter.fieldName,
        'name': parameter.name,
        'help': parameter.help,
        'displayType': parameter.displayType,
        'listDisplayFieldNames': parameter.listDisplayFieldNames,
        'infoWindowId': parameter.infoWindowId,
        'sortNo': parameter.sortNo,
        'isShow': parameter.isShow,
        'constraintEnum': parameter.constraintEnum,
        'enumClass': parameter.enumClass,
        'fieldValue': '',
        'calloutProcessNo': parameter.calloutProcessNo,
        'listDisplayFieldName': parameter.listDisplayFieldName,
        'displayName': parameter.displayName,
        'infoWindowNo': parameter.infoWindowNo,
        'value2': '',

      };
      if (parameter.fieldValue) {
        cloneObject.fieldValue = parameter.fieldValue;
      } else {
        cloneObject.fieldValue = {
          'id': parameter.id,
          'constraintEnum': parameter.constraintEnum,
          'displayValue': [],
          'fieldType': 'String',
        };
      }
      this.parentModelData.data[cloneObject.fieldName] = cloneObject.fieldValue;
      return cloneObject;

    },
    // 值改变事件
    valueChanged: function (processReportParameter) {
      // this.fieldValue = newFieldValue;
      this.$emit('valueChanged', processReportParameter);
      this.parentModelData.data[processReportParameter.fieldName] = processReportParameter.fieldValue;
      this.parameters.forEach(function (item) {
        if (item.fieldName == processReportParameter.fieldName) {
          item = processReportParameter;
        }
      });
    },

  },

};
</script>
<style scoped>
.m-form-group label {
    font-size: 15px;
    width: 80px;
    text-align: center;
}

.processResult-textarea {
    width: 100%;
    height: 200px;
}

.form-input {
    border-radius: 4px !important;
}

.form-inline-div {
    display: inline;
}

.m-form-group {
    margin-left: 5px !important;
    margin-right: 5px !important;
    margin-bottom: 5px !important;
}

.m-input-group {
    border-radius: 4px !important;
    width: 200px !important;
}
</style>