<template>
  <div>
    <div class="i-layout-page-header">
      <PageHeader :title="$route.meta.title" :content="$route.meta.description" hidden-breadcrumb />
    </div>
    <Card :bordered="false" dis-hover class="ivu-mt">
      <view-table
        ref="table"
        view-code="TableView"
        :filter="filter"
        :select-enable="allow('export')"
        :create-enable="allow('create')"
        :remove-enable="allow('remove')"
        @create="create"
        @edit="edit"
      >
        <template #filterCommand>
          <Button v-if="allow('export')" size="small" type="info" custom-icon="fa fa-cloud-download-alt" @click="exportFile()">{{ $t('Front_Btn_Export') }}</Button>
          <file-upload v-if="allow('import')" url="api/DataView/importFile" accept=".view" @on-success="importFileSuccess">
            <template #>
              <Button type="primary" custom-icon="fa fa-cloud-upload-alt" size="small">{{ $t('Front_Btn_Import') }}</Button>
            </template>
          </file-upload>
        </template>
        <template #command="{ row }">
          <Button size="small" :title="$t('Front_Btn_Column_Setting')" type="info" custom-icon="fa fa-bars" @click="tableSetting(row)"></Button>
          <Button size="small" :title="$t('Front_Btn_Filter_Setting')" type="info" custom-icon="fa fa-filter" @click="filterSetting(row)"></Button>
        </template>
      </view-table>
    </Card>
    <modal-form ref="form" view-code="TableViewEdit" :create-enable="allow('create')" :edit-enable="allow('edit')" @on-change="formChange" @on-after-save="$refs.table.loadData()">
      <template #column="{ data, code }">
        <div v-if="code == 'keywordColumn'">
          <Input type="text" :readonly="true" v-model="data.keywordColumn" @click="keywordColumnOpen()"></Input>
        </div>
        <div v-if="code == 'sorting'">
          <modal-setting-sorting ref="settingSorting" v-model="data.sorting" :is-data-source="data.isDataSource" :model="data.model" :data-source="data.dataSource" />
        </div>
        <div v-if="code == 'filtering'">
          <modal-setting-filtering ref="settingFiltering" v-model="data.filtering" :is-data-source="data.isDataSource" :model="data.model" :data-source="data.dataSource" />
        </div>
        <div v-if="code == 'batchSelectDataCode'">
          <Input type="text" :readonly="true" v-model="$refs.form.data.batchSelectDataCode" @click="openColumnCheck($refs.form.data, 'batchSelectDataCode')">
            <template #prepend>
              <Button custom-icon="fa fa-search" @click="openColumnCheck($refs.form.data, 'batchSelectDataCode')"></Button>
            </template>
          </Input>
        </div>
        <div v-if="code == 'groupColumn'">
          <Input
            type="text"
            :readonly="true"
            v-model="$refs.form.data.groupColumn"
            @click="
              $refs.groupColumn.open($refs.form.data.model, $refs.form.data.groupColumn, json => {
                $refs.form.data.groupColumn = json;
              })
            "
          >
            <template #prepend>
              <Button
                custom-icon="fa fa-edit"
                @click="
                  $refs.groupColumn.open($refs.form.data.model, $refs.form.data.groupColumn, json => {
                    $refs.form.data.groupColumn = json;
                  })
                "
              ></Button>
            </template>
          </Input>
        </div>
        <div v-if="code == 'groupMethod'">
          <Input
            type="text"
            :readonly="true"
            v-model="$refs.form.data.groupMethod"
            @click="
              $refs.groupMethod.open($refs.form.data.model, $refs.form.data.groupMethod, json => {
                $refs.form.data.groupMethod = json;
              })
            "
          >
            <template #prepend>
              <Button
                custom-icon="fa fa-edit"
                @click="
                  $refs.groupMethod.open($refs.form.data.model, $refs.form.data.groupMethod, json => {
                    $refs.form.data.groupMethod = json;
                  })
                "
              ></Button>
            </template>
          </Input>
        </div>
        <div v-if="code == 'editEnable'">
          <Switch
            :model-value="!!data.editEnable"
            v-if="showCheck(data.editEnableJson)"
            @update:model-value="
              $event => {
                data.editEnable = $event;
                //$forceUpdate();
              }
            "
            @on-change="checkChange('editEnableJson', 'editEnable')"
          />
          <Button
            style="margin-left: 8px"
            @click="$refs.conditionEdit.open(data, 'editEnableJson', 'editEnable', $refs.form.data.model)"
            type="primary"
            size="small"
            icon="ios-settings"
          >
            {{ $t('Front_Btn_Condition') }}
          </Button>
        </div>
        <div v-if="code == 'showEnable'">
          <Switch
            :model-value="!!data.showEnable"
            v-if="showCheck(data.showEnableJson)"
            @update:model-value="
              $event => {
                data.showEnable = $event;
                //$forceUpdate();
              }
            "
            @on-change="checkChange('showEnableJson', 'showEnable')"
          />
          <Button
            style="margin-left: 8px"
            @click="$refs.conditionEdit.open(data, 'showEnableJson', 'showEnable', $refs.form.data.model)"
            type="primary"
            size="small"
            icon="ios-settings"
          >
            {{ $t('Front_Btn_Condition') }}
          </Button>
        </div>
        <div v-if="code == 'removeEnable'">
          <Switch
            :model-value="!!data.removeEnable"
            v-if="showCheck(data.removeEnableJson)"
            @update:model-value="
              $event => {
                data.removeEnable = $event;
                //$forceUpdate();
              }
            "
            @on-change="checkChange('removeEnableJson', 'removeEnable')"
          />
          <Button
            style="margin-left: 8px"
            @click="$refs.conditionEdit.open(data, 'removeEnableJson', 'removeEnable', $refs.form.data.model)"
            type="primary"
            size="small"
            icon="ios-settings"
          >
            {{ $t('Front_Btn_Condition') }}
          </Button>
        </div>
      </template>
      <template #footer>
        <Button type="primary" custom-icon="fa fa-save" @click="() => $refs.form.onSave()">{{ $t('Front_Btn_Save') }}</Button>
        <Button type="primary" v-if="canCopy" custom-icon="fa fa-copy" @click="copy">{{ $t('Front_Btn_Copy') }}</Button>
      </template>
    </modal-form>
    <table-setting ref="tableSetting" />
    <filter-setting ref="filterSetting" />
    <column-select ref="columnSelect" />
    <column-check ref="columnCheck" />
    <group-method ref="groupMethod" />
    <group-column ref="groupColumn" />
    <condition-edit ref="conditionEdit" />
  </div>
</template>
<script>
  import dataViewApi from '../../api/dataView';
  import mixinPage from '../../mixins/page';
  import viewColumnApi from '../../api/viewColumn';
  import filterColumnApi from '../../api/filterColumn';
  import columnSelect from '../../components/view/column-select.vue';
  import columnCheck from '../../components/view/column-check.vue';
  import filterSetting from '../../components/view/filter-setting.vue';
  import groupMethod from '../../components/view/group-method.vue';
  import groupColumn from '../../components/view/group-column.vue';
  import conditionEdit from '../../components/view/condition-edit.vue';
  import modalSettingSorting from '../../components/view/modal-setting-sorting.vue';
  import modalSettingFiltering from '../../components/view/modal-setting-filtering.vue';

  export default {
    name: 'system-ui-tableView',
    mixins: [mixinPage],
    components: { columnSelect, columnCheck, conditionEdit, filterSetting, groupMethod, groupColumn, modalSettingFiltering, modalSettingSorting },
    data() {
      return {
        filter: {
          viewType: 'TableView',
          newCode: null
        },
        data: {},
        canCopy: null
      };
    },
    computed: {},
    created() {},
    methods: {
      formChange() {
        const data = this.$refs.form.data;
        const columns = this.$refs.form.columns;

        const columnModel = columns.find(item => {
          return item.code === 'model';
        });
        const columnDataSource = columns.find(item => {
          return item.code === 'dataSource';
        });
        const columnIsVirtual = columns.find(item => {
          return item.code === 'isVirtual';
        });
        // const columnBatchSelectDataCode = columns.find(item => {
        //     return item.code === 'batchSelectDataCode';
        // });
        // const columnHolder1 = columns.find(item => {
        //     return item.code === 'holder1';
        // });

        if (data.isDataSource) {
          columnIsVirtual.isShow = false;
          columnModel.isShow = false;
          columnDataSource.isShow = true;
        } else {
          columnIsVirtual.isShow = true;
          columnDataSource.isShow = false;

          if (data.isVirtual) {
            columnModel.isShow = false;
          } else {
            columnModel.isShow = true;
          }
        }

        // if (data.batchSelectEnable) {
        //     columnBatchSelectDataCode.isShow = true;
        //     columnHolder1.isShow = false;
        // } else {
        //     columnBatchSelectDataCode.isShow = false;
        //     columnHolder1.isShow = true;
        // }

        //this.$refs.form.forceUpdate();
      },
      // 字段设置
      async tableSetting(row) {
        let res = await viewColumnApi.queryByDataViewID(row.id);
        this.$refs.tableSetting.open(row, res.data);
      },
      // 筛选设置
      async filterSetting(row) {
        let res = await filterColumnApi.queryByDataViewID(row.id);
        this.$refs.filterSetting.open(row, res.data);
      },
      // 导出文件
      exportFile() {
        let ids = this.$refs.table.getSelected().map(x => {
          return x.id;
        });
        if (ids.length > 0) {
          dataViewApi.exportFile(ids);
        } else {
          this.error('Front_Msg_Please_Select_Export_Item');
        }
      },
      // 导入成功
      importFileSuccess(res) {
        if (res.code == 0) {
          this.success('Front_Msg_Success', () => {
            this.$refs.table.loadData();
          });
        } else {
          this.error(res.message);
        }
      },
      // 复制
      copy() {
        if (!this.$refs.form.data.id) {
          this.error('Front_Msg_Can_Not_Copy_In_Create');
          return;
        }

        this.confirmInput(
          'Front_Msg_Sure_To_Copy_Create_View',
          this.$t('Front_Label_View_Code'),
          async () => {
            let dataView = await dataViewApi.copy(this.$refs.form.data.id, this.newCode);
            this.$refs.form.open(dataView);
            this.$refs.table.loadData();
          },
          newCode => {
            if (!(newCode || '').trim()) {
              this.warning('Front_Msg_Please_Input_View_Code');
              return false;
            } else {
              this.newCode = newCode;
              return true;
            }
          }
        );
      },
      // 新建
      create() {
        this.canCopy = false;
        this.$refs.form.openDefault({ viewType: 'TableView' });
      },
      // 编辑
      edit({ row }) {
        this.canCopy = true;
        this.$refs.form.open(row);
      },
      // 打开字段选择界面
      openColumnCheck(data, code) {
        if (data.model == null) {
          return;
        }

        this.$refs.columnCheck.open(data.model, checked => {
          data[code] = checked.code;
          //this.$forceUpdate();
        });
      },
      // 打开筛选字段选择
      keywordColumnOpen() {
        if (!(this.$refs.form.data.model || '').trim()) {
          this.error('Front_Msg_Please_Select_Model_First');
          return;
        }

        let data = this.$refs.form.data;
        let keywordColumn = data.keywordColumn;
        let columns = [];

        if (!!(keywordColumn || '').trim()) {
          columns = keywordColumn.split(',').map(item => {
            return { code: item };
          });
        }

        this.$refs.columnSelect.open(this.$refs.form.data, columns, checked => {
          this.$refs.form.data.keywordColumn = checked
            .map(item => {
              return item.code;
            })
            .join();

          //this.$forceUpdate();
        });
      },
      // 是否显示选择框
      showCheck(json) {
        if (!(json || '').trim()) {
          return true;
        } else {
          let setting = JSON.parse(json);

          return setting.type == 'True' || setting.type == 'False';
        }
      },
      // 选择框变化
      checkChange(jsonKey, checkKey) {
        if (!!(this.data[jsonKey] || '').trim()) {
          let setting = JSON.parse(this.data[jsonKey]);
          if (this.data[checkKey]) {
            setting.type = 'True';
          } else {
            setting.type = 'False';
          }
          this.data[jsonKey] = JSON.stringify(setting);
        }
      }
    }
  };
</script>
