<template>
  <Input type="text" :readonly="true" :model-value="modelValue" @click="open()">
    <template #prepend>
      <Button custom-icon="fa fa-edit" @click="open()"></Button>
    </template>
  </Input>
  <modal-table ref="table" view-code="TableDefaultSorting" :static="true" :footer-enable="true" @edit="({ row, index }) => edit(row, index)">
    <template #footer>
      <Button type="primary" ghost custom-icon="fa fa-plus" @click="edit()">
        {{ $t('Front_Btn_Add') }}
      </Button>
      <Button type="primary" custom-icon="fa fa-check" @click="saveSorting">{{ $t('Front_Btn_OK') }}</Button>
    </template>
  </modal-table>
  <modal-form ref="form" view-code="TableDefaultSortingEdit">
    <template #column="{ data, code }">
      <template v-if="code == 'column'">
        <Input type="text" readonly v-model="data[code]" @on-focus="openSelect()">
          <template #prepend>
            <Button custom-icon="fa fa-search" @click="openSelect()"></Button>
          </template>
        </Input>
      </template>
    </template>
    <template #footer>
      <Button type="primary" custom-icon="fa fa-check" @click="save()">{{ $t('Front_Btn_OK') }}</Button>
    </template>
  </modal-form>
  <column-check ref="columnCheck" />
</template>

<script>
  import mixinPage from '../../mixins/page';
  import columnCheck from './column-check.vue';

  export default {
    mixins: [mixinPage],
    components: { columnCheck },
    props: {
      /**
       * @model
       */
      modelValue: {
        type: String
      },
      /**
       * 是否数据源
       */
      isDataSource: {
        type: Boolean
      },
      /**
       * 模型
       */
      model: {
        type: String
      },
      /**
       * 数据源
       */
      dataSource: {
        type: String
      }
    },
    data() {
      return {
        index: null
      };
    },
    computed: {},
    async created() {},
    methods: {
      open() {
        if (this.isDataSource && !(this.dataSource || '').trim()) {
          this.error('Front_Msg_Please_Select_Model_First');
          return;
        } else if (!this.isDataSource && !(this.model || '').trim()) {
          this.error('Front_Msg_Please_Select_Model_First');
          return;
        }

        let array = [];

        if (!!(this.modelValue || '').trim()) {
          let json = JSON.parse(this.modelValue);
          for (let key in json) {
            array.push({
              column: key,
              rule: json[key]
            });
          }
        }

        this.$refs.table.loadData(array);
        this.$refs.table.open();
      },
      edit(row, index) {
        this.index = index;
        this.$refs.form.open(row);
      },
      async save() {
        let isOK = await this.$refs.form.validate();

        if (!isOK) {
          this.error('Front_Msg_Form_Validate_Fail');
          return;
        }

        let array = this.$refs.table.data;
        let data = this.$refs.form.data;

        if (this.index == null) {
          // 新增
          if (array.some(item => item.column == data.column)) {
            this.error('排序字段已存在！');
            return;
          }

          array.push(data);
        } else {
          // 编辑
          for (let i = 0; i < data.length; i++) {
            if (i != this.index && data[i].column == data.column) {
              this.error('排序字段不能重复！');
              return;
            }
          }

          array[this.index].column = data.column;
          array[this.index].rule = data.rule;
        }

        this.$refs.table.loadData(array);
        this.$refs.form.close();
      },
      saveSorting() {
        let obj = {};
        let json = null;

        if (this.$refs.table.data.length > 0) {
          this.$refs.table.data.forEach(item => {
            obj[item.column] = item.rule;
          });

          json = JSON.stringify(obj);
        }

        this.$emit('update:modelValue', json);

        this.$refs.table.close();
      },
      // 打开字段选择界面
      openSelect() {
        if (this.isDataSource) {
          this.$refs.columnCheck.openDataSourceFilter(this.dataSource, checked => {
            this.$refs.form.data.column = checked.code;
          });
        } else {
          this.$refs.columnCheck.open(this.model, checked => {
            this.$refs.form.data.column = checked.code;
          });
        }
      }
    }
  };
</script>
