<template>
  <div>
    <x-list-page-dialog
      v-bind="$attrs"
      v-on="$listeners"
      :button-config="buttonConfig"
      :condition-config="{model: {}, list: []}"
      :columns="columns"
      height="600px"
      width="680px"
      @cell-dblclick="handleDblclick"
      :page-config="{show: false}"
      :dynamic-statistics-config="{enabled: false}"
      @opened="handleOpened"
      @close="handleClose"
      :data="tableData"
      ref="listPageDialog"
      :menu-config="menuConfig"
    ></x-list-page-dialog>
    <el-dialog :visible.sync="scopeDialogVisible" title="设置范围" height="110px" width="300px">
      <x-page-container>
        <template v-slot:header>
          <x-button-group :button-config="scopeButtonConfig"></x-button-group>
        </template>
        <template v-slot:sub>
          <x-condition :condition-config="scopeConditionConfig"></x-condition>
        </template>
      </x-page-container>
    </el-dialog>
    <el-dialog :visible.sync="saveDialogVisible" :title="saveDialogTitle" height="110px" width="300px" @close="saveConditionConfig.model.configureName = ''">
      <x-page-container>
        <template v-slot:header>
          <x-button-group :button-config="saveButtonConfig"></x-button-group>
        </template>
        <template v-slot:sub>
          <x-condition :condition-config="saveConditionConfig"></x-condition>
        </template>
      </x-page-container>
    </el-dialog>
  </div>
</template>

<script>
  import { XListPageDialog, XDialog, XPageContainer, XButtonGroup, XCondition } from '@newpearl/ui';
  import {misConfigureExtensionSaveOrUpdate, misConfigureListAll, misConfigureUpdateScope, removeMisConfigure, saveTableColumnMsg} from '../../api/misConfigApi';
  import {FIELD_TYPE_INPUT} from '../x-condition/x-condition-constant';
  const SCOPE_PUBLIC = 'public';
  const SCOPE_PRIVATE = 'private';
  const {FIELD_TYPE_SELECT} = XCondition.constant;
  export default {
    name: 'XTableSettingDialog',
    inheritAttrs: false,
    components: {
      XCondition,
      XButtonGroup,
      [XPageContainer.name]: XPageContainer,
      [XButtonGroup.name]: XButtonGroup,
      [XCondition.name]: XCondition,
      [XDialog.ElDialog.name]: XDialog.ElDialog,
      [XListPageDialog.name]: XListPageDialog
    },
    props: {
      api: Function,
      conditionConfig: Object,
      misConfigure: Object,
      handleSelect: Function
    },
    data() {
      return {
        menuConfig: null,
        scopeDialogVisible: false,
        saveDialogVisible: false,
        buttonConfig: {
          list: [
            {
              name: '选择',
              click: this.selectTableSetting
            },
            {
              name: '保存',
              click: this.showSaveDialog
            },
            {
              name: '另存为',
              click: this.showSaveDialogCopy
            },
            {
              name: '设置默认',
              click: this.setTableSettingDefault
            },
            {
              name: '取消默认',
              click: this.cancelTableSettingDefault
            },
            {
              name: '设置范围',
              click: this.setTableSettingScope
            },
            {
              name: '删除',
              type: 'danger',
              click: this.deleteTableSetting
            }
          ]
        },
        columns: [
          {field: 'selection', type: 'radio', width: 40},
          {field: 'seq', type: 'seq', title: '序号', width: 50},
          {field: 'configureName', title: '名称', minWidth: 200},
          {field: 'creatorName', title: '创建人', width: 150},
          {
            field: 'isDefault',
            title: '默认',
            width: 100,
            formatter: ({cellValue}) => {
              if (cellValue === true) {
                return '默认';
              }
              if (cellValue === false) {
                return '';
              }
              return cellValue;
            }
          },
          {
            field: 'scope',
            title: '范围',
            width: 100,
            formatter: ({cellValue}) => {
              if (cellValue === SCOPE_PUBLIC) {
                return '共享';
              }
              if (cellValue === SCOPE_PRIVATE) {
                return '私有';
              }
              return cellValue;
            }
          }
        ],
        tableData: [],
        scopeButtonConfig: {
          list: [
            {
              name: '确定',
              click: this.updateScope
            },
            {
              name: '取消',
              click: () => {
                this.scopeDialogVisible = false;
              }
            }
          ]
        },
        scopeConditionConfig: {
          model: {
            scope: ''
          },
          list: [
            {
              field: 'scope',
              label: '范围',
              type: FIELD_TYPE_SELECT,
              span: 23,
              options: [
                {label: '共享', value: SCOPE_PUBLIC},
                {label: '私有', value: SCOPE_PRIVATE}
              ]
            }
          ]
        },
        saveButtonConfig: {
          list: [
            {
              name: '确定',
              click: this.confirmSaveTableSetting
            },
            {
              name: '取消',
              click: () => {
                this.saveDialogVisible = false;
              }
            }
          ]
        },
        saveConditionConfig: {
          model: {
            configureName: ''
          },
          rules: {
            configureName: [{trigger: 'blur', required: true, message: '请输入名称'}]
          },
          list: [
            {
              field: 'configureName',
              label: '名称',
              type: FIELD_TYPE_INPUT,
              span: 23
            }
          ]
        },
        saveDialogTitle: ''
      };
    },
    methods: {
      deleteTableSetting() {
        const loginUser = this.$access.getInfo();
        if (!loginUser) {
          this.$notify.error('用户未登录');
        }
        const row = this.getListPageDialog().getListPage().getGridInstance().getRadioRecord();
        if (!row) {
          this.$notify.error('请选择记录');
          return;
        }
        if (row.userId + '' !== loginUser.userId + '') {
          this.$notify.error('只能删除本用户创建的记录');
          return;
        }
        removeMisConfigure({ids: [row.id]}, {originResponse: false}).then((res) => {
          if (!res.isSuccess()) {
            this.$notify.error(res.msg);
            return;
          }
          this.$notify.success(res.msg);
          this.search();
        });
      },
      showSaveDialog() {
        const loginUser = this.$access.getInfo();
        if (!loginUser) {
          this.$notify.error('用户未登录');
        }
        const row = this.getListPageDialog().getListPage().getGridInstance().getRadioRecord();
        if (row !== null && row.userId + '' !== loginUser.userId + '') {
          this.$notify.error('只能修改本用户创建的记录');
          return;
        }
        this.$showSaveDialog('保存');
      },
      showSaveDialogCopy() {
        const loginUser = this.$access.getInfo();
        if (!loginUser) {
          this.$notify.error('用户未登录');
        }
        const row = this.getListPageDialog().getListPage().getGridInstance().getRadioRecord();
        if (!row) {
          this.$notify.error('请选择记录');
          return;
        }
        this.$showSaveDialog('另存为');
      },
      $showSaveDialog(title) {
        const row = this.getListPageDialog().getListPage().getGridInstance().getRadioRecord();
        if (row) {
          this.saveConditionConfig.model.configureName = row.configureName;
        }
        this.saveDialogTitle = title;
        this.saveDialogVisible = true;
      },
      getListPageDialog() {
        return this.$refs.listPageDialog;
      },
      selectTableSetting() {
        const row = this.getListPageDialog().getListPage().getGridInstance().getRadioRecord();
        if (!row) {
          this.$notify.error('请选择记录');
          return;
        }
        if (this.handleSelect) {
          this.handleSelect({row});
        }
        this.$refs.listPageDialog.hide();
      },
      confirmSaveTableSetting() {
        if (this.saveDialogTitle === '保存') {
          this.saveTableSetting();
        } else {
          this.saveTableSettingCopy();
        }
      },
      saveTableSetting() {
        const row = this.getListPageDialog().getListPage().getGridInstance().getRadioRecord();
        const params = {
          name: this.misConfigure.name,
          objectType: this.misConfigure.objectType,
          objectJson: this.misConfigure.objectJson,
          configureName: this.saveConditionConfig.model.configureName
        };
        if (row) {
          params.id = row.id;
          params.scope = row.scope;
        } else {
          params.scope = SCOPE_PRIVATE;
        }
        saveTableColumnMsg(params, {originResponse: false}).then((res) => {
          if (!res.isSuccess()) {
            this.$notify.error(res.msg);
            return;
          }
          this.$notify.success(res.msg);
          this.saveDialogVisible = false;
          this.search();
        });
      },
      saveTableSettingCopy() {
        const row = this.getListPageDialog().getListPage().getGridInstance().getRadioRecord();
        if (!row) {
          this.$notify.error('请选择记录');
          return;
        }
        if (row.configureName === this.saveConditionConfig.model.configureName) {
          this.$notify.error('名称重复');
          return;
        }
        const params = {
          name: this.misConfigure.name,
          objectType: this.misConfigure.objectType,
          configureName: this.saveConditionConfig.model.configureName,
          scope: SCOPE_PRIVATE
        };
        // 如果是同一个方案，就使用界面中最新的，因为用户可能会拖拽或显示隐藏
        // 否则就用方案本身的
        if (row.id === this.misConfigure.id) {
          params.objectJson = this.misConfigure.objectJson;
        } else {
          params.objectJson = row.objectJson;
        }
        saveTableColumnMsg(params, {originResponse: false}).then((res) => {
          if (!res.isSuccess()) {
            this.$notify.error(res.msg);
            return;
          }
          this.$notify.success(res.msg);
          this.saveDialogVisible = false;
          this.search();
        });
      },
      cancelTableSettingDefault() {
        if (!this.misConfigureExtension) {
          return;
        }
        const params = {id: this.misConfigureExtension.id, name: this.misConfigureExtension.name};
        misConfigureExtensionSaveOrUpdate(params).then((response) => {
          const res = response.data;
          if (!res.isSuccess()) {
            this.$notify.error(res.msg);
            return;
          }
          this.search();
        });
      },
      setTableSettingDefault() {
        const params = {name: this.misConfigure.name};
        const row = this.getListPageDialog().getListPage().getGridInstance().getRadioRecord();
        if (!row) {
          this.$notify.error('请选择记录');
          return;
        }
        if (this.misConfigureExtension) {
          // 如果原来就是默认的，就不处理
          if (this.misConfigureExtension.defaultConfigure === row.id) {
            return;
          }
          params.id = this.misConfigureExtension.id;
        }
        params.defaultConfigure = row.id;
        misConfigureExtensionSaveOrUpdate(params).then((response) => {
          const res = response.data;
          if (!res.isSuccess()) {
            this.$notify.error(res.msg);
            return;
          }
          this.search();
        });
      },
      setTableSettingScope() {
        const loginUser = this.$access.getInfo();
        if (!loginUser) {
          this.$notify.error('用户未登录');
        }
        const row = this.getListPageDialog().getListPage().getGridInstance().getRadioRecord();
        if (!row) {
          this.$notify.error('请选择记录');
          return;
        }
        if (row.userId + '' !== loginUser.userId + '') {
          this.$notify.error('只能修改本用户创建的记录');
          return;
        }
        this.scopeDialogVisible = true;
        this.scopeConditionConfig.model.scope = row.scope;
      },
      updateScope() {
        const row = this.getListPageDialog().getListPage().getGridInstance().getRadioRecord();
        if (row.scope === this.scopeConditionConfig.model.scope) {
          this.scopeDialogVisible = false;
          return;
        }
        misConfigureUpdateScope({id: row.id, scope: this.scopeConditionConfig.model.scope}, {originResponse: false}).then(res => {
          if (!res.isSuccess()) {
            this.$notify.error(res.msg);
            return;
          }
          this.scopeDialogVisible = false;
          this.$notify.success(res.msg);
          this.search();
        });
      },
      handleOpened() {
        this.getListPageDialog().getListPage().getGridInstance().recalculate(true).then(() => {
          this.search();
        });
      },
      handleClose() {
        this.misConfigureExtension = null;
        this.tableData = [];
      },
      search() {
        this.misConfigureExtension = null;
        misConfigureListAll({name: this.misConfigure.name, page: 1, pageSize: 65535, scope: SCOPE_PUBLIC}).then((response) => {
          const res = response.data;
          if (!res.isSuccess()) {
            this.$notify.error(res.msg);
            return;
          }
          const list = res.data.pager.list;
          const misConfigureExtension = res.data.misConfigureExtension;
          let radioRow = null;
          if (misConfigureExtension != null) {
            for (const item of list) {
              if (item.id === misConfigureExtension.defaultConfigure) {
                item.isDefault = true;
                radioRow = item;
              } else {
                item.isDefault = false;
              }
            }
          }
          // 如果外部传入misConfigure,就更这个属性来控制默认选中
          if (this.misConfigure) {
            for (const item of list) {
              if (item.id === this.misConfigure.id) {
                radioRow = item;
                break;
              }
            }
          }
          this.misConfigureExtension = misConfigureExtension;
          this.tableData = list;
          this.$nextTick(() => {
            // 设置选中选项
            if (radioRow) {
              this.$refs.listPageDialog.getListPage().getXTable().getGridInstance().setRadioRow(radioRow);
            }
          });
        });
      },
      async quickQuery() {
        let model = {};
        if (this.conditionConfig && this.conditionConfig.model) {
          model = this.conditionConfig.model;
        }
        const { data } = await this.api(Object.assign({}, this.queryParams, model));
        if (!data.isSuccess()) {
          return Promise.reject(new RequestError(data.msg));
        }
        return Promise.resolve(data.data);
      },
      getAllRecords() {
        return this.$refs.listPage.getTableData().fullData;
      },
      getRecords() {
        const row = this.$refs.listPage.getRadioRecord();
        if (row) {
          return [row];
        }
        return this.$refs.listPage.getCheckboxRecords();
      },
      handleDblclick() {

      }
    },
    watch: {
      presetQueryParams: {
        handler(newVal) {
          if (!newVal) {
            return;
          }
          Object.assign(this.queryParams, newVal);
        },
        immediate: true
      }
    }
  };
</script>
