<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 #command="{ row, index }">
        <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 #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 #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.setting.data.batchSelectDataCode" @click="openColumnCheck($refs.setting.data, 'batchSelectDataCode')">
            <template #prepend>
              <Button custom-icon="fa fa-search" @click="openColumnCheck($refs.setting.data, 'batchSelectDataCode')"></Button>
            </template>
          </Input>
        </div>
        <div v-if="code == 'groupColumn'">
          <Input
            type="text"
            :readonly="true"
            v-model="$refs.setting.data.groupColumn"
            @click="
              $refs.groupColumn.open(dataView.model, $refs.setting.data.groupColumn, json => {
                $refs.setting.data.groupColumn = json;
              })
            "
          >
            <template #prepend>
              <Button
                custom-icon="fa fa-edit"
                @click="
                  $refs.groupColumn.open(dataView.model, $refs.setting.data.groupColumn, json => {
                    $refs.setting.data.groupColumn = json;
                  })
                "
              ></Button>
            </template>
          </Input>
        </div>
        <div v-if="code == 'groupMethod'">
          <Input
            type="text"
            :readonly="true"
            v-model="$refs.setting.data.groupMethod"
            @click="
              $refs.groupMethod.open(dataView.model, $refs.setting.data.groupMethod, json => {
                $refs.setting.data.groupMethod = json;
              })
            "
          >
            <template #prepend>
              <Button
                custom-icon="fa fa-edit"
                @click="
                  $refs.groupMethod.open(dataView.model, $refs.setting.data.groupMethod, json => {
                    $refs.setting.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', dataView.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', dataView.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', dataView.model)"
            type="primary"
            size="small"
            icon="ios-settings"
          >
            {{ $t('Front_Btn_Condition') }}
          </Button>
        </div>
      </template>
      <template #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 #column="{ 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 #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 #column="{ row, code }">
        <template v-if="code == 'param'">
          <Input type="text" size="small" v-model="row.param">
            <template #prepend>
              <Button size="small" custom-icon="fa fa-search" @click="$refs.columnCheck.openViewCode(commandButton.viewCode, column => (row.param = column.code))"></Button>
            </template>
          </Input>
        </template>
        <template v-if="code == 'value'">
          <Input type="text" size="small" v-model="row.value">
            <template #prepend>
              <Button size="small" custom-icon="fa fa-search" @click="$refs.columnCheck.open(dataView.model, column => (row.value = column.code))"></Button>
            </template>
          </Input>
        </template>
      </template>
      <template #footer>
        <Button type="primary" custom-icon="fa fa-save" @click="saveParams">{{ $t('Front_Btn_Save') }}</Button>
      </template>
    </modal-table>

    <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.vue';
  import columnSelect from './column-select.vue';
  import columnEdit from './column-edit.vue';
  import { mapActions } from 'vuex';
  import modalSettingSorting from './modal-setting-sorting.vue';
  import modalSettingFiltering from './modal-setting-filtering.vue';
  import groupMethod from './group-method.vue';
  import groupColumn from './group-column.vue';
  import conditionEdit from './condition-edit.vue';

  export default {
    mixins: [mixinPage],
    components: { columnCheck, columnSelect, columnEdit, conditionEdit, groupMethod, groupColumn, modalSettingFiltering, modalSettingSorting },
    data() {
      return {
        active: false,
        dataView: {},
        data: {},
        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() {
        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();
            });
          });
        }
      },
      // 打开操作栏按钮参数设置界面
      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>
