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

    <div class="grid-item-2">
      <div class="form-inline">
        <div class="form-group">
          <label for="exampleInputName2">
            {{ $t("lang.RoleCurdField.role") }}
          </label>
          <label style="width: 350px" for="exampleInputName2">
            <select id="role" width="100%" class="js-data-example-ajax" />
          </label>
        </div>

        <div class="form-group">
          <label for="exampleInputName2">
            {{ $t("lang.RoleCurdField.window") }}
          </label>
          <label style="width: 350px" for="exampleInputName2">
            <v-select
              v-model="roleCurdFieldDto.window"
              :options="windowOptions"
              :label="'value'"
              :placeholder="$t('lang.RoleCurdField.pleaseSelectTheWindowName')"
              @input="windowChange"
            />
          </label>
        </div>
        <button type="button" class="btn btn-primary" @click="saveData">
          {{ $t("lang.RoleCurdField.save") }}
        </button>
      </div>
    </div>

    <div class="grid-item-3">
      <div
        v-if="
          curdWindowDto && curdWindowDto.tabs && curdWindowDto.tabs.length > 0
        "
      >
        <RoleCurdFieldTab
          v-for="(tab, index) in curdWindowDto.tabs"
          ref="roleCurdFieldTab"
          :key="'roleCurdFieldTab_tab_' + index"
          :tab="tab"
          :role-curd-field-list="roleCurdFieldList"
          :role-id="roleCurdFieldDto.roleId"
          :curd-window-no="roleCurdFieldDto.curdWindowNo"
        />
      </div>
    </div>
  </div>
</template>

<script>
import Common from '../common/Common.js';

import vSelect from 'vue-select';
import 'vue-select/dist/vue-select.css';
import RoleCurdFieldTab from './RoleCurdFieldTab.vue';
import CurdWindowResource from '../api/dic/CurdWindowResource.js';
import RoleCurdFieldResource from '../api/base/RoleCurdFieldResource.js';
export default {
  components: {
    RoleCurdFieldTab,
    'v-select': vSelect.VueSelect,
    RoleCurdFieldResource,
  },
  data: function () {
    return {
      roleCurdFieldDto: {
        id: undefined,
        roleId: undefined,
        curdWindowNo: undefined,
        tabName: undefined,
        fieldName: undefined,
        displayName: undefined,
        invisible: undefined,
        readonly: undefined,
        whereClause: undefined,
        mandatory: undefined,
        entityFieldIndex: undefined,
        windowNo: undefined,
        windowName: '',
        window: undefined,
      },
      roleCurdFieldDtos: [],
      windowOptions: [],
      roleCurdFieldList: [],
      curdWindowDto: {
        no: undefined,
        tabs: [],
      },
      tabFormViewDto: {
        tabFormFields: [],
      },
      tabFormFieldDto: {
        fieldName: undefined, // 类字段名称
      },
      tabDataSourceDto: {
        tabDataSourceFields: [],
      },
    };
  },

  mounted: function () {
    var _self = this;
    _self.loadSelectRole();
    _self.loadWindows();
  },

  methods: {
    /**
     * 保存角色CURD访问权限的改动数据
     * @author LiangZhiCheng 20210324
     */
    saveData: function () {
      var _self = this;
      var roleCurdFieldTab = _self.$refs.roleCurdFieldTab;
      var roleCurdFields = [];
      if (roleCurdFieldTab) {
        for (let i = 0; i < roleCurdFieldTab.length; i++) {
          var tabRoleflowCurdFields = roleCurdFieldTab[i].getData();
          if (tabRoleflowCurdFields != null) {
            tabRoleflowCurdFields.forEach(item => {
              roleCurdFields.push(item);
            });
          }
        }
      }
      RoleCurdFieldResource.saveRoleCurdField(
        _self.roleCurdFieldDto.roleId,
        _self.roleCurdFieldDto.curdWindowNo,
        roleCurdFields,
      ).then(
        successData => {
          if (successData) {
            Common.showDialog(
              _self.$t('lang.RoleCurdField.presentation'),
              _self.$t('lang.RoleCurdField.successfulPreservation'),
              'success',
            );
          }
        },
        errorData => {
          Common.processException(errorData);
        },
      );
    },
    /**
     * 窗口选择发生改变
     * @author LiangZhiCheng 20210324
     */
    windowChange: function (val) {
      var _self = this;
      if (_self.roleCurdFieldDto != undefined) {
        if (val != undefined) {
          _self.roleCurdFieldDto.curdWindowNo = val.keyStr;
          _self.roleCurdFieldDto.windowName = val.value;
          _self.roleCurdFieldDto.window = val;
          if (
            _self.roleCurdFieldDto.name == null ||
            _self.roleCurdFieldDto.name.length == 0
          ) {
            _self.roleCurdFieldDto.name = val.value;
          }
          _self.loadWindow();
        } else {
          _self.roleCurdFieldDto.curdWindowNo = undefined;
          _self.roleCurdFieldDto.windowName = undefined;
          _self.roleCurdFieldDto.window = undefined;
        }
      }
    },

    /**
     * 获取角色
     * @author LiangZhiCheng 20210324
     */
    loadSelectRole: function () {
      var _self = this;
      $('#role')
        .select2({
          // 请求搜索框数据
          //data: _self.data,
          placeholder: _self.$t('lang.RoleCurdField.pleaseSelectTheRole'),
          minimumInputLength: 0,
          placeholderOption: 'first',
          quietMillis: 250,
          allowClear: true,
          language: 'zh-CN',
          width: '100%',
          // 请求搜索框数据
          ajax: {
            url: function (params) {
              return Common.getApiURL('roleResource/getAllSubRoleDto');
            },
            dataType: 'json',
            type: 'get',
            delay: 250,
            minimumInputLength: 0,
            transport: function (params, success, failure) {
              params.beforeSend = Common.addTokenToRequest;
              var $request = $.ajax(params);
              $request.then(success);
              $request.fail(failure);
              return $request;
            },
            data: function (params) {
              return {};
            },
            processResults: function (data, params) {
              var more = params * 10 <= data.length;
              for (var i = 0; i < data.length; i++) {
                data[i].text = data[i].name;
              }
              return {
                results: data,
                more: more,
              };
            },
          },
        })
        .on('change', function () {
          _self.roleCurdFieldDto.roleId = $(this).val();
          _self.loadWindow();
        });
    },

    /**
     * [loadWindows 获取窗口]
     * @return {[type]} [description]
     * @author LiangZhiCheng 20210324
     */
    loadWindows: function () {
      var _self = this;
      $.ajax({
        url: Common.getApiURL('CurdWindowResource/getWindowKeyValues'),
        type: 'get',
        dataType: 'json',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.windowOptions.splice(0, _self.windowOptions.length);
          // 清空数据
          if (data == undefined || data.length == 0) {
            return;
          }

          for (var i = 0, len = data.length; i < len; i++) {
            _self.windowOptions.push(data[i]);
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 根据窗口编号查询数据
     * @author LiangZhiCheng 20210324
     */
    loadWindow: function () {
      var _self = this;
      //console.log(_self.roleCurdFieldDto.window);
      var windowNo = _self.roleCurdFieldDto.curdWindowNo;
      var roleId = _self.roleCurdFieldDto.roleId;
      var length = undefined;
      console.log(windowNo);
      if (windowNo != undefined || windowNo != null) {
        CurdWindowResource.uniqueByNo(windowNo).then(
          successData => {
            if (successData.errorCode == 0) {
              _self.curdWindowDto = successData.data;
              length = _self.curdWindowDto.tabs.length;
              for (var i = 0; i < length; i++) {
                if (
                  _self.curdWindowDto.tabs[i] != undefined ||
                  _self.curdWindowDto.tabs[i] == ''
                ) {
                  _self.tabFormViewDto.tabFormFields[i] =
                    _self.curdWindowDto.tabs[i].tabFormView.tabFormFields;
                  _self.tabDataSourceDto.tabDataSourceFields[i] =
                    _self.curdWindowDto.tabs[
                      i
                    ].tabDataSource.tabDataSourceFields;
                }
              }
              _self.loadRoleIdWindowNo(roleId, windowNo);
              // console.log(_self.tabFormViewDto.tabFormFields);
            } else {
              Notify.error(_self.$t('lang.Notify.error'), successData.errorMessage, true);
            }
          },
          errorData => {
            Common.processException(errorData);
          },
        );
      }
    },

    /**
     * 根据角色、窗口编号查询
     * @param roleId 角色Id
     * @param windowNo 窗口编号
     * @author LiangZhiCheng 20210324
     */
    loadRoleIdWindowNo: function (roleId, windowNo) {
      var _self = this;
      _self.roleCurdFieldList = [];
      RoleCurdFieldResource.loadRoleIdWindowNo(roleId, windowNo).then(
        successData => {
          if (successData) {
            successData.forEach(function (item) {
              var roleCurdFieldDto = {
                tabName: item.tabName,
                fieldName: item.fieldName,
                entityFieldIndex: item.entityFieldIndex,
                readonly: item.readonly,
                invisible: item.invisible,
                whereClause: item.whereClause,
              };
              _self.roleCurdFieldList.push(roleCurdFieldDto);
            });
            console.log(_self.roleCurdFieldList);
          }
        },
        errorData => {
          Common.processException(errorData);
        },
      );
    },
  },
};
</script>

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

.grid-item-1 {
  grid-column: 1 / 2;
}

.grid-item-2 {
  grid-column: 1 / 2;
}

.grid-item-3 {
  padding-top: 0px;
  padding-right: 20px;
  overflow: auto;
  grid-row: 3/4;
  grid-column: 1 / 3;
  height: 100%;
}

.m-label {
  width: 100px;
}

.m-form-control {
  width: 200px;
}

.grid-item-4 {
  padding-top: 10px;
  grid-column: 1 / 2;
}
</style>