<template>
  <div>
    <Navbar
      :title="processReportDto.name"
      :is-go-back="processReportDto.goback"
    />
    <div>
      <h5>{{ processReportDto.description }}</h5>
    </div>
    <div class="form-inline">
      <template v-for="item in processReportDtos.processReportParameters" :key="'processReportParameter-' + item.fieldName">
        <div
        
          v-if="processReportDtos != undefined && processReportDtos.processReportParameters != undefined"
        
          class="form-group"
        >
          <label
            v-if="item.displayType != 'ListBoxEnumEditor'"
            class="m-label"
            :for="'editor_' + item.id"
          >{{ item.displayName }}</label>
          <span
            v-show="!item.mandatory"
            style="color: red;"
          >该项为必填项字段</span>

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

            <input
              v-if="item.displayType =='NumberEditor'"
              :id="'editor_' + item.id"
              v-model="item.fieldValue.displayValue[0]"
              type="number"
              class="form-control"
              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"
              :date-value="item.fieldValue.displayValue[0]"
              class="form-control"
              name="datetime"
              @on-value-change="changeValue(item, $event)"
            />

            <EnumSelectWidget
              v-if="item.displayType =='ListBoxEnumEditor'"
              :key-values="item.keyValues"
              :enum-value="item.fieldValue.displayValue[0]"
              @value-changed="changeValue(item, $event)"
            />

            <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"
              @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"
              :model-data="modelData"
              @value-changed="tabValueChanged($event, item)"
            />

            <VueMonthlyPicker
              v-if="item.displayType =='YearMonthEditor'"
              :value="item.fieldValue.displayValue[0]"
              :allow-change-value="false"
              date-format="YYYY-MM"
              class="vue-monthly-picker m-date-fieldEditView"
              @selected="changeValue(item, $event)"
            />
            <YearPicker
              v-if="item.displayType =='YearEditor'"
              :date-value="item.fieldValue.displayValue[0]"
              @selected="changeValue(item, $event)"
            />
          </div>
        </div>
      </template>
    </div>
    <div>
      <div class="form-group">
        <button
          v-if="processReportDtos.htmlHelpUrl != null && processReportDtos.htmlHelpUrl != ''"
          class="btn btn-default"
          @click="openHtmlHelp(processReportDtos.htmlHelpUrl)"
        >
          <span class="glyphicon glyphicon-question-sign" />
        </button>
        <input
          type="button"
          class="btn btn-primary"
          style="margin-top: 15px;"
          value="确定"
          @click="subDatas()"
        />
      </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';

var Common = require('../../common/Common.js').default;
var DateTime = require('../../datetime/src/DateTime.vue').default;
var YearPicker = require('../../year-picker/src/YearPicker.vue').default;
var Loading = require('../../loading/src/Loading.vue').default;
var ProcessReportResultPreview = require('./ProcessReportResultPreview.vue').default;
var SearchWidget = require('../../info/src/SearchWidget.vue').default;
var Switches = require('../../switches/src/Switches.vue').default;
var Navbar = require('../../navbar/src/Navbar.vue').default;
var VueMonthlyPicker = require('../../vue-monthly-picker/src/VueMonthlyPicker.vue').default;
var EnumSelectWidget = require('./EnumSelectWidget.vue').default;



export default {

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

  emits:['valueChanged'],
  data: function () {
    return {
      processReportId: '',
      processReportDtos: '',
      processResultData: '',
      processReportResult: {},
      complete: true, //参数是否全部填写
      modelData: {
        data: {

        },
      },
      loading: false,
    };
  },

  //监控processReportDto，当dto变化时重新渲染界面
  watch: {
    'processReportDto': function (to, from) { // eslint-disable-line
      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) {
      var _self = this;
      if (data == undefined) {
        return;
      }
      _self.processReportDtos = '';
      if (data.processReportParameters) {
        data.processReportParameters.forEach(function (item) {
          if (item.mandatory == undefined) {
            item.mandatory = true;
          }
          if (item.listDisplayFieldName == undefined) {
            item.listDisplayFieldName = item.listDisplayFieldNames;
          }

          if (item.fieldValue == undefined) {
            item.fieldValue = {
              id: '',
              displayValue: [],
              fieldType: 'String',
            };
          }

          if (item.displayType == 'YearMonthEditor') {
            item.fieldValue.displayValue[0] = moment().format('YYYY-MM');
          }
          _self.modelData.data[item.fieldName] = item.fieldValue;
        });
      }

      _self.processReportDtos = data;
    },

    /**
         * 判断参数是否填写
         */
    judgeDataFull: function () {
      var _self = this;

      _self.complete = true;
      if (
        _self.processReportDtos &&
                _self.processReportDtos.processReportParameters
      ) {
        _self.processReportDtos.processReportParameters.forEach(
          function (item) {
            item.mandatory = true;
            if (item.fieldValue.displayValue.length <= 0) {
              item.mandatory = false;
            }
            _self.complete = _self.complete && item.mandatory;
          },
        );
      }
    },

    /**
         * 执行流程
         * @return {void}
         */
    subDatas: function () {
      var _self = this;
      _self.judgeDataFull();

      _self.processResultData = {
        processReportNo: _self.processReportDto.no,
        modelData: {
          data: {},
        },
      };

      if (
        _self.processReportDtos &&
                _self.processReportDtos.processReportParameters
      ) {
        _self.processReportDtos.processReportParameters.forEach(
          function (item) {
            var fieldName = item.fieldName;
            _self.processResultData.modelData.data[fieldName] =
                            item.fieldValue;
          },
        );
      }

      _self.processReportResult = {};
      if (!_self.complete) {
        return;
      }
      _self.loading=true;

      $.ajax({
        url: Common.getApiURL('ProcessReportResource/runProcess'),
        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=2;
                if (index == 0) {
                  item.showPreview=true;
                } else {
                  item.showPreview=false;
                }
              },
            );
          }
        },
        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);
    },
    // 值改变事件
    valueChanged: function (processReportParameter) {
      // this.fieldValue = newFieldValue;
      this.$emit('valueChanged', processReportParameter);
      this.modelData.data[processReportParameter.fieldName] = processReportParameter.fieldValue;
    },

  },
};
</script>
<style scoped>
.control-label {
    font-size: 15px;
}

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

.m-label {
    width: 5em;
    margin-left: 1em;
}
</style>

<style>
.m-date-fieldEditView > div:first-child {
    width: 100%;
}
</style>