<template>
  <!-- 字段排序table展示 -->
  <Modal v-model="opened" scrollable :mask-closable="layout.maskClosable" :draggable="layout.draggable" :sticky="true" :reset-drag-position="true" :width="formView.width || '800'">
    <div slot="header">
      <span class="title">{{ $t('Front_Label_Sorting_Setting') }}</span>
      <span class="description">{{ $t('Front_Label_Sorting_Setting_Desc') }}</span>
    </div>
    <div class="i-table-no-border">
      <Table stripe :columns="columnsSorting" :data="dataSorting">
        <template slot-scope="{ row, index }" slot="action">
          <Button size="small" :title="$t('Front_Btn_Edit')" type="primary" ghost custom-icon="fa fa-edit" @click="sortingFmModalopen(row)"></Button>
          <Button size="small" :title="$t('Front_Btn_Up')" type="primary" ghost custom-icon="fa fa-chevron-up" @click="upSorting(row, index)"></Button>
          <Button size="small" :title="$t('Front_Btn_Down')" type="primary" ghost custom-icon="fa fa-chevron-down" @click="downSorting(row, index)"></Button>
          <Button size="small" :title="$t('Front_Btn_Remove')" type="primary" ghost custom-icon="fa fa-times" @click="removeSorting(row, index)"></Button>
        </template>
      </Table>
    </div>
    <template slot="footer">
      <Button type="primary" ghost custom-icon="fa fa-plus" @click="sortingFmModalopen(null)">{{ $t('Front_Btn_Add') }}</Button>
      <Button type="primary" custom-icon="fa fa-check" @click="SaveSorting">{{ $t('Front_Btn_OK') }}</Button>
    </template>
    <!-- 对排序字段进行处理 -->
    <Modal v-model="sortingFmModal" scrollable :mask-closable="layout.maskClosable" :draggable="layout.draggable" :sticky="true" :reset-drag-position="true" width="800">
      <div slot="header">
        <span class="title">{{ $t('Front_Label_Sorting_Setting_Edit') }}</span>
        <span class="description">{{ $t('Front_Label_Sorting_Setting_Edit_Desc') }}</span>
      </div>
      <Form ref="sortingform">
        <Row :gutter="24" type="flex">
          <Col>
            <FormItem :label="$t('Front_Label_Column')" prop="Code">
              <Input type="text" readonly v-model="data.code" @on-focus="openSelect()">
                <Button slot="prepend" custom-icon="fa fa-search" @click="openSelect()"></Button>
              </Input>
            </FormItem>
          </Col>
          <Col>
            <FormItem :label="$t('Front_Label_Operator')" prop="SortingRule">
              <Select v-model="data.rule" :transfer="true">
                <Option v-for="item in sortingList" :value="item.value" :key="item.value">{{ item.label }}</Option>
              </Select>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <template slot="footer">
        <Button type="primary" custom-icon="fa fa-check" @click="saveSortingForm($event)">{{ $t('Front_Btn_OK') }}</Button>
      </template>
    </Modal>

    <column-check ref="columnCheck" />
  </Modal>
</template>

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

  export default {
    mixins: [mixinPage],
    components: { columnCheck },

    props: {
      sort: String, //原排序字段json值
      dataView: {} //原表单对象
    },
    data() {
      return {
        opened: false,
        formView: {},
        sortingFmModal: false,
        dataSorting: [],
        data: {}
      };
    },
    computed: {
      columnsSorting() {
        return [
          {
            type: 'index',
            width: 100,
            title: this.$t('Front_Label_Sn'),
            align: 'center'
          },
          {
            title: this.$t('Front_Label_Column'),
            key: 'column'
          },
          {
            title: this.$t('Front_Label_Rule'),
            key: 'rule'
          },
          {
            title: ' ',
            slot: 'action',
            width: 200,
            fixed: 'right',
            align: 'center'
          }
        ];
      },
      sortingList() {
        return [
          {
            value: 'asc',
            label: this.$t('Front_Label_Asc')
          },
          {
            value: 'desc',
            label: this.$t('Front_Label_Desc')
          }
        ];
      }
    },
    async created() {},
    methods: {
      open() {
        this.toData();
        this.opened = true;
      },
      close() {
        this.opened = false;
      },
      // 打开排序字段设置表单
      sortingFmModalopen(row) {
        // row = null表示新增
        if (row != null) {
          this.data.code = row.column;
          this.data.rule = row.rule;
        }
        // 表示新增
        else {
          this.data.code = '';
          this.data.rule = '';
        }
        this.sortingFmModal = true;
      },
      // 将数据库获取的json字符串转换为数组对象
      toData() {
        let array = [];
        // 如果该字段为空，则如下转换不进行
        if (this.sort != '' && this.sort != null) {
          let json = JSON.parse(this.sort);
          for (let key in json) {
            array.push({
              column: key,
              rule: json[key]
            });
          }
        }
        this.dataSorting = array;
      },
      // 添加排序规则确认
      async saveSortingForm() {
        // 保存前字段均不为空
        if (this.data.code != '' && this.data.code != null && this.data.rule != null && this.data.rule != '') {
          let checkSort = false;
          // 遍历原排序对象 dataSorting 中是否有与新增的字段相同的
          // 暂时不做此判断，后续再优化2021年3月19日18:39:13
          // this.dataSorting.forEach(item => {
          //     if (item.column == this.data.code) {
          //         checkSort = true;
          //     }
          // });
          this.dataSorting.forEach(item => {
            // 如果编辑列与原数据中有相同列，则做更新不做添加
            if (item.column == this.data.code) {
              checkSort = true;
              item.rule = this.data.rule;
            }
          });
          if (!checkSort) {
            // 将新加的字段对象添加到原排序对象 dataSorting 中
            this.dataSorting.push({
              column: this.data.code,
              rule: this.data.rule
            });
          }
          // 确认后关闭modal
          this.sortingFmModal = false;
        } else {
          this.error('Front_Msg_Column_Sorting_Required');
        }
      },
      // 添加排序字段table确认
      SaveSorting() {
        this.toSortingJson();
      },
      // 排序数据的移动操作
      // 移除一行数据
      removeSorting(row, index) {
        if (row != null) {
          this.dataSorting.splice(index, 1);
        }
      },
      // 上移
      upSorting(row, index) {
        if (index > 0) {
          this.dataSorting.splice(index, 1);
          this.dataSorting.splice(index - 1, 0, row);
        }
      },
      // 下移
      downSorting(row, index) {
        if (index < this.dataSorting.length - 1) {
          this.dataSorting.splice(index, 1);
          this.dataSorting.splice(index + 1, 0, row);
        }
      },
      // 打开字段选择界面
      openSelect() {
        this.$refs.columnCheck.openView(this.dataView, checked => {
          this.data.code = checked.code;
          this.data.name = checked.name;
          this.data.dataType = checked.dataType;
          this.data.source = checked.objColumn != null ? checked.objColumn.dataType : null;
          this.data.sourceDataCode = checked.objColumn != null ? 'id' : null;
          this.data.sourceDisplayCode =
            checked.objColumn != null &&
            checked.objColumn.columns.some(function (column) {
              return column.code === checked.objColumn.code + '.name';
            })
              ? 'name'
              : null;
          setTimeout(() => {
            this.$forceUpdate();
          });
        });
      },
      //[{column: 'type.orderNo',rule: 'asc'},{column: 'orderNo',rule: 'asc'}]
      // { "type.orderNo": "asc", "orderNo": "asc" }
      // 排序结果 将table对象转换为json字符串
      toSortingJson() {
        let jsonStr = '{';
        if (this.dataSorting.length > 0) {
          for (let key in this.dataSorting) {
            jsonStr += '"' + this.dataSorting[key].column + '":"' + this.dataSorting[key].rule + '",';
          }
          jsonStr = jsonStr.substring(0, jsonStr.length - 1);
          jsonStr += '}';
        } else {
          jsonStr = '';
        }
        this.$emit('bindSort', jsonStr);
        this.close();
      }
    }
  };
</script>
