<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" :selectEnable="true" @create="create" @edit="edit">
        <template slot="filterCommand">
          <Button size="small" type="info" custom-icon="fa fa-cloud-download-alt" @click="exportFile()">{{ $t('Front_Btn_Export') }}</Button>
          <file-upload url="api/DataView/importFile" accept=".view" @on-success="importFileSuccess">
            <template slot="">
              <Button type="primary" custom-icon="fa fa-cloud-upload-alt" size="small">{{ $t('Front_Btn_Import') }}</Button>
            </template>
          </file-upload>
        </template>
        <template slot-scope="{ row }" slot="command">
          <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" @on-change="formChange" @on-after-save="$refs.table.loadData()">
      <template slot="column" slot-scope="{ data, code }">
        <div v-if="code == 'keywordColumn'">
          <Input type="text" :readonly="true" v-model="data.keywordColumn" @click.native="keywordColumnOpen()"></Input>
        </div>
        <div v-if="code == 'sorting'">
          <Input type="text" :readonly="true" v-model="$refs.form.data.sorting" @click.native="openSort">
            <Button slot="prepend" custom-icon="fa fa-edit" @click="openSort"></Button>
          </Input>
        </div>
        <div v-if="code == 'filtering'">
          <Input type="text" :readonly="true" v-model="$refs.form.data.filtering" @click.native="openFilter">
            <Button slot="prepend" custom-icon="fa fa-edit" @click="openFilter"></Button>
          </Input>
        </div>
        <div v-if="code == 'batchSelectDataCode'">
          <Input type="text" :readonly="true" v-model="$refs.form.data.batchSelectDataCode" @click.native="openColumnCheck($refs.form.data, 'batchSelectDataCode')">
            <Button slot="prepend" custom-icon="fa fa-search" @click="openColumnCheck($refs.form.data, 'batchSelectDataCode')"></Button>
          </Input>
        </div>
        <div v-if="code == 'groupColumn'">
          <Input
            type="text"
            :readonly="true"
            v-model="$refs.form.data.groupColumn"
            @click.native="
              $refs.groupColumn.open($refs.form.data.model, $refs.form.data.groupColumn, json => {
                $refs.form.data.groupColumn = json;
              })
            "
          >
            <Button
              slot="prepend"
              custom-icon="fa fa-edit"
              @click="
                $refs.groupColumn.open($refs.form.data.model, $refs.form.data.groupColumn, json => {
                  $refs.form.data.groupColumn = json;
                })
              "
            ></Button>
          </Input>
        </div>
        <div v-if="code == 'groupMethod'">
          <Input
            type="text"
            :readonly="true"
            v-model="$refs.form.data.groupMethod"
            @click.native="
              $refs.groupMethod.open($refs.form.data.model, $refs.form.data.groupMethod, json => {
                $refs.form.data.groupMethod = json;
              })
            "
          >
            <Button
              slot="prepend"
              custom-icon="fa fa-edit"
              @click="
                $refs.groupMethod.open($refs.form.data.model, $refs.form.data.groupMethod, json => {
                  $refs.form.data.groupMethod = json;
                })
              "
            ></Button>
          </Input>
        </div>
        <div v-if="code == 'editEnable'">
          <Switch
            :value="!!data.editEnable"
            v-if="showCheck(data.editEnableJson)"
            @input="
              $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 == 'removeEnable'">
          <Switch
            :value="!!data.removeEnable"
            v-if="showCheck(data.removeEnableJson)"
            @input="
              $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 slot="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>
    <modal-form-sort ref="modal_sort" :sort="data.sorting" :dataView="data" @bindSort="bindSort" />
    <modal-form-filter ref="modal_filter" :filter="data.filtering" :dataView="data" @bindFilter="bindFilter" />
    <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';
  import columnCheck from '../../components/view/column-check';
  import filterSetting from '../../components/view/filter-setting';
  import groupMethod from '../../components/view/group-method';
  import groupColumn from '../../components/view/group-column';
  import conditionEdit from '../../components/view/condition-edit';

  export default {
    name: 'system-ui-tableView',
    mixins: [mixinPage],
    components: { columnSelect, columnCheck, filterSetting, groupMethod, groupColumn, conditionEdit },
    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);
      },
      //绑定排序组件返回的排序json
      bindSort(value) {
        this.$refs.form.data.sorting = value;
        // this.data.sorting = value;
      },
      //绑定筛选组件返回的排序json
      bindFilter(value) {
        this.$refs.form.data.filtering = value;
        // this.data.filtering = value;
      },
      // 打开排序编辑框
      async openSort() {
        if (!this.$refs.form.data.model == '') {
          this.data = this.$refs.form.data;
          this.$refs.modal_sort.open();
        } else {
          this.error('Front_Msg_Please_Select_Model_First');
        }
      },
      // 打开筛选编辑框
      async openFilter() {
        if (!this.$refs.form.data.model == '') {
          this.data = this.$refs.form.data;
          this.$refs.modal_filter.open();
        } else {
          this.error('Front_Msg_Please_Select_Model_First');
        }
      },
      // 导出文件
      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>
