<template>
  <div>
    <div class="grid-container">
      <div class="grid-item-1">
        <div>
          <Navbar
            :title="$t('lang.AssetBatchOperationOrganization.assetConfirmationBatchTransfer')"
            :is-go-back="true"
          />
        </div>
      </div>

      <div class="grid-item-2">
        <div class="row">
          <div class="col-md-12">
            <div class="form-inline">
              <div class="form-group">
                <label
                  for="organizationName"
                  style="width: 115px"
                >{{ $t('lang.AssetBatchOperationOrganization.ownerDepartmentAfterTransfer') }}</label>
                <SearchWidget
                  :info-window-no="infoWindowNo"
                  :field="organizationField"
                  :field-value="organizationFieldValue"
                  :display-name="organizationField.listDisplayFieldName"
                  :where-clause-source="whereClauseSource"
                  @value-changed="valueChanged"
                />
              </div>
              <div class="form-group">
                <label
                  for="organizationName"
                  style="width: 115px"
                >{{ $t('lang.AssetBatchOperationOrganization.ownerClientAfterTransfer') }}</label>
                <input
                  v-model="organizationName"
                  autocomplete="off"
                  type="text"
                  class="form-control"
                  style="width: 236px"
                  readonly
                />
              </div>
              <div class="form-group">
                <label
                  for="organizationName"
                  style="width: 115px"
                >{{ $t('lang.AssetBatchOperationOrganization.useDepartmentAfterTransfer') }}</label>
                <SearchWidget
                  style="width: 236px;"
                  :info-window-no="infoWindowNo"
                  :field="responseOrganizationField"
                  :field-value="responseOrganizationFieldValue"
                  :display-name="responseOrganizationField.listDisplayFieldName"
                  :where-clause-source="whereClauseSource"
                  @value-changed="responsibilityValueChanged"
                />
              </div>
              <div class="form-group">
                <label
                  for="organizationName"
                  style="width: 115px"
                >{{ $t('lang.AssetBatchOperationOrganization.useClientAfterTransfer') }}</label>
                <input
                  v-model="responsibilityOrganizationName"
                  autocomplete="off"
                  type="text"
                  class="form-control"
                  style="width: 236px"
                  readonly
                />
              </div>
              <div class="form-group">
                <label
                  for="organizationName"
                  style="width: 115px"
                >{{ $t('lang.AssetBatchOperationOrganization.newStorageLocation') }}</label>
                <SearchWidget
                  style="width: 236px;"
                  :info-window-no="locationInfoWindowNo"
                  :field="locationField"
                  :field-value="locationFieldValue"
                  :display-name="locationField.listDisplayFieldName"
                  :where-clause-source="locationWhereClauseSource"
                  @value-changed="locationValueChanged"
                />
              </div>
              <div class="form-group">
                <label
                  for="userName"
                  style="width: 115px"
                >{{ $t('lang.AssetBatchOperationOrganization.personHhandlingAParticularTask') }}</label>
                <SearchWidget
                  style="width: 236px;"
                  :info-window-no="userWindowNo"
                  :field="userField"
                  :field-value="userFieldValue"
                  :display-name="userField.listDisplayFieldName"
                  :where-clause-source="clientIdWhereClauseSource"
                  @value-changed="userValueChanged"
                />
              </div>
              <div class="form-group">
                <label
                  for="reason"
                  style="width: 115px"
                >{{ $t('lang.AssetBatchOperationOrganization.reasonsForTransfer') }}</label>
                <input
                  id="reason"
                  v-model="reason"
                  autocomplete="off"
                  type="text"
                  class="form-control"
                  style="width: 236px"
                  :placeholder="$t('lang.AssetBatchOperationOrganization.pleaseFillInTheReasonForTransfer')"
                />
              </div>
              <div
                class="form-group"
                style="margin-top: 5px"
              >
                <button
                  class="btn btn-primary"
                  @click="resetQuery"
                >
                  {{ $t('lang.AssetBatchOperationOrganization.query') }}
                </button>
                <button
                  type="button"
                  class="btn btn-success"
                  @click="removeAssetChangeWaitDtos"
                >
                  {{ $t('lang.AssetBatchOperationOrganization.cancelTransfer') }}
                </button>
                <button
                  type="button"
                  class="btn btn-info"
                  style="text-align: right"
                  @click="saveAssetChangeWaitDtos"
                >
                  {{ $t('lang.AssetBatchOperationOrganization.generateDepartmentChangeDocument') }}
                </button>
                <span v-if="assetConfigDto.allowOrganizationBatchChange">
                  <button
                    type="button"
                    class="btn btn-success"
                    @click="generateAssetAllocate()"
                  >
                    {{ $t('lang.AssetBatchOperationOrganization.generateAssetTransferDocument') }}
                  </button>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="grid-item-3">
        <AssetBatchOperationQueue
          ref="assetBatchOperationQueue"
          :change-type="changeType"
        />
      </div>
    </div>

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

<script>
import ClientResource from '../../api/base/ClientResource.js';
import AssetChangeResource from '../../api/asset/AssetChangeResource.js';
import AssetConfigResource from '../../api/asset/AssetConfigResource.js';
import Common from '../../common/Common.js';

import AssetAllocateResource from '../../api/asset/AssetAllocateResource.js';
import AssetBatchOperationQueue from './AssetBatchOperationQueue.vue';
import { Notify, Uuid } from 'pc-component-v3';

export default {
  components: {
    
    
    
    
    AssetBatchOperationQueue,
  },
  data: function () {
    return {
      changeType: 'organizationChange',
      assetConfigDto: [], //固定资产设置Dto
      pagination: {
        total: 0,
        per_page: Common.pageSize, // required
        current_page: 1, // required
        last_page: 0, // required
      },
      infoWindowNo: '279750',
      whereClauseSource: {
        customerDataDimensions:[{
          fieldName: 'client.id',
          dataDimensionTypeNo: '202201191757',
          defaultDataDimensionTypeValueNo: '3',
        }],
      },
      locationInfoWindowNo: 109494,
      locationWhereClauseSource: {
        customerDataDimensions:[{
          fieldName: 'client.id',
          dataDimensionTypeNo: '202201191757',
          defaultDataDimensionTypeValueNo: '3',
        }],
      },

      clientIdWhereClauseSource: {
        customerDataDimensions:[{
          fieldName: 'client.id',
          dataDimensionTypeNo: '202201191757',
          defaultDataDimensionTypeValueNo: '3',
        }],
      },

      userWindowNo: '050408',
      organizationField: {
        name: '',
        listDisplayFieldName: 'name',
      },
      responseOrganizationField: {
        name: '',
        listDisplayFieldName: 'name',
      },
      locationField: {
        name: '',
        listDisplayFieldName: 'ar.name',
      },
      userField: {
        name: '',
        listDisplayFieldName: 'name',
      },
      organizationFieldValue: {
        id: null,
        displayValue: [''],
        fieldType: 'Key',
      },
      responseOrganizationFieldValue: {
        id: null,
        displayValue: [''],
        fieldType: 'Key',
      },
      locationFieldValue: {
        id: null,
        displayValue: [''],
        fieldType: 'Key',
      },
      userFieldValue: {
        id: null,
        displayValue: [''],
        fieldType: 'Key',
      },
      checked: false,
      reason: '',
      locationList: [],
      locationId: undefined,
      locationSelected: undefined,
      organizationName: undefined,
      responsibilityOrganizationName: undefined,
      loading: false,
    };
  },

  mounted: function () {
    var _self = this;
    _self.queryAssetConfig();
    _self.$refs.assetBatchOperationQueue.getDatas();
  },

  methods: {

    /**
         * 重置分页，然后查询
         */
    resetQuery: function () {
      var _self = this;
      _self.pagination.current_page = 1;
      _self.$refs.assetBatchOperationQueue.getDatas();
    },

    /**
         * 查询AssetConfigDto
         * @return {[type]} [description]
         */
    queryAssetConfig: function () {
      var _self = this;
      AssetConfigResource.queryAssetConfig().then(
        successData => {
          if(successData.errorCode == 0) {
            _self.assetConfigDto = successData.data;
          } else {
            Notify.error('提示',successData.errorMessage, false);
          }
        },
        errorData => { },
      );
    },

    // 使用部门选择框change事件
    valueChanged: function (newFieldValue) {
      var _self = this;
      this.organizationFieldValue = newFieldValue;
      _self.queryClient();
    },

    //所属部门选择框change事件
    responsibilityValueChanged: function (newResponsibilityFieldValue) {
      var _self = this;
      this.responseOrganizationFieldValue = newResponsibilityFieldValue;
      _self.queryResponsibilityClient();
    },

    /**
         * 存放地点选择框change事件
         */
    locationValueChanged: function (newResponsibilityFieldValue) {
      var _self = this;
      this.locationFieldValue = newResponsibilityFieldValue;
    },

    /**
         * 调拨经手人框change事件
         */
    userValueChanged: function (newResponsibilityFieldValue) {
      var _self = this;
      this.userFieldValue = newResponsibilityFieldValue;
    },

    /**
         * 根据使用部门Id查询所属单位
         */
    queryClient: function () {
      var _self = this;
      var organizationId = _self.organizationFieldValue.id;
      ClientResource.uniqueByOrganizationId(
        organizationId,
      ).then(
        baseObjectResponse => {
          if(baseObjectResponse.errorCode == 0){
            _self.organizationName = baseObjectResponse.data.name;
          }else{
            Notify.error('提示',baseObjectResponse.errorMessage, false);
          }
        },
        errorData => { },
      );
    },

    /**
         * 根据所属部门Id查询所属单位
         */
    queryResponsibilityClient: function () {
      var _self = this;
      var organizationId = _self.responseOrganizationFieldValue.id;
      ClientResource.uniqueByOrganizationId(
        organizationId,
      ).then(
        baseObjectResponse => {
          if(baseObjectResponse.errorCode == 0){
            _self.responsibilityOrganizationName = baseObjectResponse.data.name;
          }else{
            Notify.error('提示',baseObjectResponse.errorMessage, false);
          }
        },
        errorData => { },
      );
    },

    /**
         * 删除队列数据
         */
    removeAssetChangeWaitDtos: function () {
      this.$refs.assetBatchOperationQueue.removeAssetChangeWaitDtos();
    },

    /**
         * 获取转移资产DTO集合
         */
    getAssetChangeDtos: function () {
      var _self = this;
      let organizationId = null;
      let responseOrganizationId = null;
      let locationId = null;
      let responsibleUserId = null;

      if (_self.organizationFieldValue == undefined || _self.organizationFieldValue.id == undefined) {
        Notify.error('错误', '请选择转移后的所属部门。', true);
        return;
      } else {
        organizationId = _self.organizationFieldValue.id;
      }

      if (_self.responseOrganizationFieldValue == undefined ||
                _self.responseOrganizationFieldValue.id == undefined) {
        Notify.error('错误', '请选择转移后的使用部门。', true);
        return;
      } else {
        responseOrganizationId = _self.responseOrganizationFieldValue.id;
      }

      if(_self.reason == null || _self.reason == ''){
        Notify.error('错误', '转移原因不能为空。', true);
        return;
      }

      if (_self.locationFieldValue != null && _self.locationFieldValue.id != null) {
        locationId = _self.locationFieldValue.id;
      }

      if (_self.userFieldValue != null && _self.userFieldValue.id != null) {
        responsibleUserId = _self.userFieldValue.id;
      }

      var assetChangeDtos = _self.$refs.assetBatchOperationQueue.getAssetChangeDtos();
      if (assetChangeDtos != null) {
        assetChangeDtos.forEach(function (item) {
          item.organizationId = organizationId;
          item.responseOrganizationId = responseOrganizationId;
          item.reason = _self.reason;
          item.locationId = locationId;
          item.responsibleUserInId = responsibleUserId;
        });
      }

      return assetChangeDtos;
    },

    /**
         * 确认转移，生成部门变动单
         */
    saveAssetChangeWaitDtos: function () {
      var _self = this;
      let assetChangeDtos = _self.getAssetChangeDtos();

      if (assetChangeDtos == null) {
        return;
      }

      if (assetChangeDtos.length < 1) {
        Common.showDialog('提示', '请在表格中勾选待变动数据后再提交。', 'error');
        return;
      }

      _self.loading=true;
      AssetChangeResource.saveAssetChanges(assetChangeDtos).then(
        baseListResponse => {
          if(baseListResponse.errorCode == 0){
            _self.message = '共计' + baseListResponse.datas.length + '条资产数据变动成功。';
            Common.showDialog('提示', _self.message, 'success');
            if (baseListResponse.datas.length > 0) {
              let url = Common.getRedirectUrl(
                '#/desktop/window/041208?currPage=1&uuid=' +
                              Uuid.createUUID(),
              );
              window.open(url);
            }
          }else{
            Common.showDialog('提示', baseListResponse.errorMessage, 'error');
          }
          _self.checked = false;
          _self.loading=false;
          _self.$refs.assetBatchOperationQueue.getDatas();
        },
        errorData => {
          _self.loading=false;
          Common.processException(errorData);
        },
      );
    },

    /**
         * 生成调拨单
         *
         */
    generateAssetAllocate: function () {
      var _self = this;
      let assetChangeDtos = _self.getAssetChangeDtos();

      if (assetChangeDtos == null) {
        return;
      }

      if (assetChangeDtos.length < 1) {
        Common.showDialog('提示', '请在表格中勾选待变动数据后再提交。', 'error');
        return;
      }
      _self.loading=true;

      AssetAllocateResource.generate(assetChangeDtos).then(
        baseListResponse => {
          _self.loading=false;
          _self.checked = false;
          _self.$refs.assetBatchOperationQueue.getDatas();
          if(baseListResponse.errorCode == 0){
            if (baseListResponse.datas.length > 0) {
              let url = Common.getRedirectUrl(
                '#/desktop/window/041601?currPage=1&uuid=' +
                            Uuid.createUUID(),
              );
              window.open(url);
            }
          }
        },
        errorData => {
          _self.loading=false;
          Common.processException(errorData);
        },
      );
    },
  },
};
</script>

<style scoped>
.grid-container {
    display: grid;
    grid-template-columns: 100%;
    grid-template-rows: 80px min-content auto;
    /*视口被均分为 100 单位的 vh 占据整个窗口，扣掉顶部 topNav 的距离后，计算得到 responseOrganizationSelect 的高度*/
    height: calc(100vh - 80px);
    width: 100%;
}
.grid-item-1 {
    grid-column: 1 / 2;
}

.grid-item-2 {
    grid-column: 1 / 2;
    padding-bottom: 10px;
}

.grid-item-3 {
    padding-right: 20px;
    overflow: auto;
    grid-row: 3/4;
    grid-column: 1 / 2;
    height: 100%;
}
</style>