<template>
  <div>
    <modal-table ref="table" :static="true" :setting-enable="false" :footer-enable="true" :draggable="true" :sticky="true" @on-drag-drop="dragDrop" v-if="active">
      <template slot-scope="{ row, index }" slot="command">
        <Button size="small" :title="$t('Front_Btn_Edit')" type="primary" ghost custom-icon="fa fa-edit" @click="edit(row, index)"></Button>
        <Button size="small" :title="$t('Front_Btn_Up')" type="primary" ghost custom-icon="fa fa-chevron-up" @click="up(row, index)"></Button>
        <Button size="small" :title="$t('Front_Btn_Down')" type="primary" ghost custom-icon="fa fa-chevron-down" @click="down(row, index)"></Button>
        <Button size="small" :title="$t('Front_Btn_Remove')" type="primary" ghost custom-icon="fa fa-times" @click="remove(row, index)"></Button>
      </template>
      <template slot="footer">
        <Button type="primary" v-if="!dataView.isVirtual" ghost custom-icon="fa fa-indent" @click="openColumnSelect">{{ $t('Front_Btn_Select_Column') }}</Button>
        <Button type="primary" custom-icon="fa fa-bookmark" @click="createVirtual">{{ $t('Front_Btn_Virtual_Column') }}</Button>
        <Button type="primary" custom-icon="fa fa-save" v-if="!isSetting" @click="save">{{ $t('Front_Btn_Save') }}</Button>
        <Button type="error" custom-icon="fa fa-save" v-if="isSetting" @click="globalSave">{{ $t('Front_Btn_Global_Save') }}</Button>
        <Button type="error" custom-icon="fa fa-cog" v-if="isSetting" @click="setting">{{ $t('Front_Btn_Table_Setting') }}</Button>
      </template>
    </modal-table>
    <column-select ref="columnSelect" />
    <column-edit ref="columnEdit" view-type="TableView" />
    <modal-form ref="setting" view-code="TableViewSetting" v-if="isSetting">
      <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="sort" @click.native="$refs.modal_sort.open()">
            <Button slot="prepend" custom-icon="fa fa-edit" @click="$refs.modal_sort.open()"></Button>
          </Input>
        </div>
        <div v-if="code == 'filtering'">
          <Input type="text" :readonly="true" v-model="filter" @click.native="$refs.modal_filter.open()">
            <Button slot="prepend" custom-icon="fa fa-edit" @click="$refs.modal_filter.open()"></Button>
          </Input>
        </div>
        <div v-if="code == 'batchSelectDataCode'">
          <Input type="text" :readonly="true" v-model="$refs.setting.data.batchSelectDataCode" @click.native="openColumnCheck($refs.setting.data, 'batchSelectDataCode')">
            <Button slot="prepend" custom-icon="fa fa-search" @click="openColumnCheck($refs.setting.data, 'batchSelectDataCode')"></Button>
          </Input>
        </div>
        <div v-if="code == 'groupColumn'">
          <Input
            type="text"
            :readonly="true"
            v-model="$refs.setting.data.groupColumn"
            @click.native="
              $refs.groupColumn.open(dataView.model, $refs.setting.data.groupColumn, json => {
                $refs.setting.data.groupColumn = json;
              })
            "
          >
            <Button
              slot="prepend"
              custom-icon="fa fa-edit"
              @click="
                $refs.groupColumn.open(dataView.model, $refs.setting.data.groupColumn, json => {
                  $refs.setting.data.groupColumn = json;
                })
              "
            ></Button>
          </Input>
        </div>
        <div v-if="code == 'groupMethod'">
          <Input
            type="text"
            :readonly="true"
            v-model="$refs.setting.data.groupMethod"
            @click.native="
              $refs.groupMethod.open(dataView.model, $refs.setting.data.groupMethod, json => {
                $refs.setting.data.groupMethod = json;
              })
            "
          >
            <Button
              slot="prepend"
              custom-icon="fa fa-edit"
              @click="
                $refs.groupMethod.open(dataView.model, $refs.setting.data.groupMethod, json => {
                  $refs.setting.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', dataView.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', dataView.model)"
            type="primary"
            size="small"
            icon="ios-settings"
          >
            {{ $t('Front_Btn_Condition') }}
          </Button>
        </div>
      </template>
      <template slot="bottom">
        <Divider :plain="true" dashed orientation="left" size="small">
          <span class="title">{{ $t('Front_Label_Command_Button') }}</span>
        </Divider>
        <view-table ref="commandButton" view-code="CommandButton" :static="true" :embedded="true">
          <template slot="column" slot-scope="{ row, code }">
            <template v-if="code == 'params'">
              <Button type="primary" v-if="row.viewCode && row.viewType == 'TableView'" size="small" custom-icon="fa fa-list" @click="openParams(row)">
                {{ $t('Front_Btn_Param') }}
              </Button>
            </template>
          </template>
        </view-table>
      </template>
      <template slot="footer">
        <Button type="primary" custom-icon="fa fa-save" @click="saveSetting">{{ $t('Front_Btn_Save') }}</Button>
      </template>
    </modal-form>
    <modal-table ref="commandButtonParams" view-code="CommandButtonParams" :static="true" :embedded="true" :footerEnable="true">
      <template slot="column" slot-scope="{ row, code }">
        <template v-if="code == 'param'">
          <Input type="text" size="small" v-model="row.param">
            <Button
              slot="prepend"
              size="small"
              custom-icon="fa fa-search"
              @click="$refs.columnCheck.openViewCode(commandButton.viewCode, column => (row.param = column.code))"
            ></Button>
          </Input>
        </template>
        <template v-if="code == 'value'">
          <Input type="text" size="small" v-model="row.value">
            <Button slot="prepend" size="small" custom-icon="fa fa-search" @click="$refs.columnCheck.open(dataView.model, column => (row.value = column.code))"></Button>
          </Input>
        </template>
      </template>
      <template slot="footer">
        <Button type="primary" custom-icon="fa fa-save" @click="saveParams">{{ $t('Front_Btn_Save') }}</Button>
      </template>
    </modal-table>
    <modal-form-sort ref="modal_sort" :sort="sort" :dataView="dataView" @bindSort="bindSort" />
    <modal-form-filter ref="modal_filter" :filter="filter" :dataView="dataView" @bindFilter="bindFilter" />
    <column-check ref="columnCheck" />
    <group-method ref="groupMethod" />
    <group-column ref="groupColumn" />
    <condition-edit ref="conditionEdit" />
  </div>
</template>
<script>
  import mixinPage from '../../mixins/page';
  import columnCheck from './column-check';
  import columnSelect from './column-select';
  import columnEdit from './column-edit';
  import { mapActions } from 'vuex';
  import modalFormSort from './modal-form-sort';
  import modalFormFilter from './modal-form-filter';
  import groupMethod from './group-method';
  import groupColumn from './group-column';
  import conditionEdit from './condition-edit';

  export default {
    mixins: [mixinPage],
    components: { columnCheck, columnSelect, columnEdit, modalFormSort, modalFormFilter, groupMethod, groupColumn, conditionEdit },
    data() {
      return {
        active: false,
        dataView: {},
        data: {},
        tablename: '',
        sort: '',
        filter: '',
        tableid: '',
        commandButton: {}
      };
    },
    created() {},
    props: {
      // 是否公共配置界面
      isSetting: {
        type: Boolean,
        default: false
      }
    },
    computed: {},
    methods: {
      ...mapActions('admin/dataView', {
        resetDataView: 'reset',
        saveDataView: 'save',
        saveUserView: 'saveUserView',
        saveDataViewSetting: 'saveSetting'
      }),
      // 打开
      open(dataView, columns) {
        this.dataView = dataView;
        this.active = true;
        let code;

        if (this.isSetting) {
          code = 'TableViewColumnSimple';
        } else {
          code = 'TableViewColumn';
        }

        setTimeout(async () => {
          await this.$refs.table.init(code, () => {
            this.$refs.table.loadData(columns);
            this.$refs.table.open();
          });
        });
      },
      // 打开字段设置界面
      edit(row, index) {
        this.$refs.columnEdit.open(row, index, this.$refs.table.data, data => {
          let columns = this.$refs.table.data;
          columns.splice(index, 1, data);

          this.$refs.table.loadData(columns);
        });
      },
      // 打开字段选择界面
      openColumnCheck(data, code) {
        if (data.model == null) {
          return;
        }

        this.$refs.columnCheck.open(data.model, checked => {
          data[code] = checked.code;
          this.$forceUpdate();
        });
      },
      // 上移
      up(row, index) {
        let columns = this.$refs.table.data;
        if (index > 0) {
          columns.splice(index, 1);
          columns.splice(index - 1, 0, row);

          this.$refs.table.loadData(columns);
        }
      },
      // 下移
      down(row, index) {
        let columns = this.$refs.table.data;
        if (index < columns.length - 1) {
          columns.splice(index, 1);
          columns.splice(index + 1, 0, row);

          this.$refs.table.loadData(columns);
        }
      },
      // 拖动完成
      dragDrop({ index1, index2 }) {
        if (index1 != index2) {
          let columns = this.$refs.table.data;
          let row = columns[index1];

          columns.splice(index1, 1);
          columns.splice(index2, 0, row);
        }
      },
      // 移除
      remove(row, index) {
        let columns = this.$refs.table.data;
        columns.splice(index, 1);

        this.$refs.table.loadData(columns);
      },
      // 打开字段选择界面
      openColumnSelect() {
        let columns = this.$refs.table.data;
        this.$refs.columnSelect.open(this.dataView, columns, checked => {
          // 移除未勾选的
          columns = columns.filter(column => {
            return (
              checked.some(item => {
                return column.code === item.code;
              }) || column.isVirtual
            );
          });

          // 添加新勾选的
          checked.forEach(item => {
            if (
              !columns.some(column => {
                return column.code === item.code;
              })
            ) {
              columns.push({
                code: item.code,
                name: item.name,
                dataType: item.dataType,
                dataView: this.dataView,
                isShow: true,
                controlType: 'Label', // 默认只读文本
                align: 'Center' // 默认居中
              });
            }
          });

          setTimeout(() => {
            this.$refs.table.loadData(columns);
          });
        });
      },
      // 创建虚拟字段
      createVirtual() {
        let columns = this.$refs.table.data;

        let row = {
          isShow: true,
          isVirtual: true,
          dataType: 'String'
        };

        this.$refs.columnEdit.open(row, -1, this.$refs.table.data, data => {
          columns.push(data);
          this.$refs.table.loadData(columns);
        });
      },
      // 全局保存
      globalSave() {
        this.confirm('Front_Msg_Sure_To_Save_Global_Setting', () => {
          this.confirm('Front_Msg_Sure_To_Save_Global_Setting_Confirm', async () => {
            await this.saveDataView({
              code: this.dataView.code,
              columns: this.$refs.table.data
            });

            this.$emit('on-change', this.dataView.code);
            this.success('Front_Msg_Success', () => {
              this.$refs.table.close();
            });
          });
        });
      },
      // 重置
      reset() {
        this.confirm('Front_Msg_Sure_To_Reset_Setting', async () => {
          await this.resetDataView(this.dataView.code);

          this.$emit('on-change', this.dataView.code);
          this.success('Front_Msg_Success', () => {
            this.$refs.table.close();
          });
        });
      },
      // 用户保存
      userSave() {
        this.confirm('Front_Msg_Sure_To_Save_Setting', async () => {
          await this.saveUserView({
            code: this.dataView.code,
            columns: this.$refs.table.data
          });

          this.$emit('on-change', this.dataView.code);
          this.success('Front_Msg_Success', () => {
            this.$refs.table.close();
          });
        });
      },
      // 保存
      save() {
        this.confirm('Front_Msg_Sure_To_Save_Setting', async () => {
          await this.saveDataView({
            code: this.dataView.code,
            columns: this.$refs.table.data
          });

          this.success('Front_Msg_Success', () => {
            this.$refs.table.close();
          });
        });
      },
      // 设置
      setting() {
        // 排序字段参数赋值
        this.sort = this.dataView.sorting;
        this.filter = this.dataView.filtering;

        if (!!(this.dataView.commandButton || '').trim()) {
          this.$refs.commandButton.loadData(JSON.parse(this.dataView.commandButton));
        } else {
          this.$refs.commandButton.loadData([]);
        }

        this.$refs.setting.open(this.copy(this.dataView));
      },
      // 保存设置
      async saveSetting() {
        let isOK = await this.$refs.setting.validate();

        if (!isOK) {
          this.error('Front_Msg_Form_Validate_Fail');
        } else {
          if (!this.$refs.commandButton.validate()) {
            return;
          }

          // 操作栏按钮
          this.$refs.setting.data.commandButton = JSON.stringify(this.$refs.commandButton.getData());

          this.confirm('Front_Msg_Sure_To_Save_Setting', async () => {
            let res = await this.saveDataViewSetting(this.$refs.setting.data);
            this.dataView = res.dataView;

            this.$emit('on-change', this.dataView.code);
            this.success('Front_Msg_Success', () => {
              this.$refs.setting.close();
            });
          });
        }
      },
      //绑定排序组件返回的排序json
      bindSort(value) {
        this.sort = value;
        this.$refs.setting.data.sorting = value;
      },
      //绑定筛选组件返回的排序json
      bindFilter(value) {
        this.filter = value;
        this.$refs.setting.data.filtering = value;
      },
      // 打开操作栏按钮参数设置界面
      openParams(row) {
        this.commandButton = row;

        let params = [];
        if (!!(row.params || '').trim()) {
          params = JSON.parse(row.params);
        }

        this.$refs.commandButtonParams.loadData(params);
        this.$refs.commandButtonParams.open();
      },
      // 保存操作栏按钮参数
      saveParams() {
        let params = this.$refs.commandButtonParams.getData();
        this.commandButton.params = JSON.stringify(params);

        this.$refs.commandButtonParams.close();
      },
      // 打开筛选字段选择
      keywordColumnOpen() {
        if (!(this.dataView.model || '').trim()) {
          this.error('Front_Msg_Please_Select_Model_First');
          return;
        }

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

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

        this.$refs.columnSelect.open(this.dataView, columns, checked => {
          this.$refs.setting.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>
