<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_Filtering_Setting_Desc') }}</span>
    </div>
    <div class="i-table-no-border">
      <Table stripe :columns="columnsFiltering" :data="dataFiltering">
        <template slot-scope="{ row, index }" slot="action">
          <Button size="small" :title="$t('Front_Btn_Edit')" type="primary" ghost custom-icon="fa fa-edit" @click="filteringFmModalopen(row)"></Button>
          <Button size="small" :title="$t('Front_Btn_Up')" type="primary" ghost custom-icon="fa fa-chevron-up" @click="upfiltering(row, index)"></Button>
          <Button size="small" :title="$t('Front_Btn_Down')" type="primary" ghost custom-icon="fa fa-chevron-down" @click="downfiltering(row, index)"></Button>
          <Button size="small" :title="$t('Front_Btn_Remove')" type="primary" ghost custom-icon="fa fa-times" @click="removefiltering(row, index)"></Button>
        </template>
      </Table>
    </div>
    <template slot="footer">
      <Button type="primary" ghost custom-icon="fa fa-plus" @click="filteringFmModalopen(null)">{{ $t('Front_Btn_Add') }}</Button>
      <Button type="primary" custom-icon="fa fa-check" @click="SaveFiltering">{{ $t('Front_Btn_OK') }}</Button>
    </template>

    <!-- 对筛选条件进行处理 -->
    <Modal v-model="filteringFmModal" 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_Filtering_Setting_Edit') }}</span>
        <span class="description">{{ $t('Front_Label_Filtering_Setting_Edit_Desc') }}</span>
      </div>
      <Form ref="filteringform">
        <Row :gutter="24" type="flex">
          <Col>
            <FormItem :label="$t('Front_Label_Column')" prop="Code">
              <Input type="text" v-model="data.code">
                <Button slot="prepend" custom-icon="fa fa-search" @click="openSelect()"></Button>
              </Input>
            </FormItem>
          </Col>
          <Col>
            <FormItem :label="$t('Front_Label_Operator')" prop="Operator">
              <Select v-model="data.operator" :transfer="true">
                <Option v-for="item in getEnumList('Operator')" :key="item.value" :value="item.id">{{ item.name }}</Option>
              </Select>
            </FormItem>
          </Col>
          <Col>
            <FormItem :label="$t('Front_Label_Keyword')" prop="KeyValue">
              <Input type="text" v-model="data.keyValue" maxlength="200" />
            </FormItem>
          </Col>
        </Row>
      </Form>
      <template slot="footer">
        <Button type="primary" custom-icon="fa fa-check" @click="saveFilteringForm($event)">{{ $t('Front_Btn_OK') }}</Button>
      </template>
      <column-check ref="columnCheck" />
    </Modal>
  </Modal>
</template>

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

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

    props: {
      filter: String, //原表单筛选字段json值
      dataView: {} //原表单对象
    },
    data() {
      return {
        opened: false,
        formView: {},
        filteringFmModal: false,
        dataFiltering: [],
        data: {}
      };
    },
    computed: {
      columnsFiltering() {
        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_Operator'),
            key: 'operatorType'
          },
          {
            title: this.$t('Front_Label_Keyword'),
            key: 'keyValue'
          },
          {
            title: ' ',
            slot: 'action',
            width: 200,
            fixed: 'right',
            align: 'center'
          }
        ];
      }
    },
    methods: {
      open() {
        this.toData();
        this.opened = true;
      },
      close() {
        this.opened = false;
      },
      // 将数据库获取的json字符串转换为数组对象
      toData() {
        let filterArr = [];
        if (this.filter != '' && this.filter != null) {
          let json = JSON.parse(this.filter);
          for (let key in json) {
            let operatorArr = [];
            operatorArr = this.operatorChange(key);
            filterArr.push({
              column: operatorArr[0],
              operatorType: operatorArr[1],
              rule: operatorArr[2],
              operator: operatorArr[3],
              keyValue: json[key]
            });
          }
        }
        this.dataFiltering = filterArr;
      },
      // 操作符数据转换（ companyType_g  --->  companyType，_g，大于，GreaterThan）
      operatorChange(operator) {
        let operatorArr = new Array(4);
        if (operator.indexOf('_g') >= 0 && operator.indexOf('_ge') == -1) {
          operatorArr[0] = operator.replace('_g', '');
          operatorArr[1] = '大于';
          operatorArr[2] = '_g';
          operatorArr[3] = 'GreaterThan';
        } else if (operator.indexOf('_l') >= 0 && operator.indexOf('_le') == -1) {
          operatorArr[0] = operator.replace('_l', '');
          operatorArr[1] = '小于';
          operatorArr[2] = '_l';
          operatorArr[3] = 'LessThan';
        } else if (operator.indexOf('_ge') >= 0) {
          operatorArr[0] = operator.replace('_ge', '');
          operatorArr[1] = '大于等于';
          operatorArr[2] = '_ge';
          operatorArr[3] = 'GreaterThanOrEqual';
        } else if (operator.indexOf('_le') >= 0) {
          operatorArr[0] = operator.replace('_le', '');
          operatorArr[1] = '小于等于';
          operatorArr[2] = '_le';
          operatorArr[3] = 'LessThanOrEqual';
        } else if (operator.indexOf('_n') >= 0) {
          operatorArr[0] = operator.replace('_n', '');
          operatorArr[1] = '不等于';
          operatorArr[2] = '_n';
          operatorArr[3] = 'NotEqual';
        } else if (operator.indexOf('_c') >= 0) {
          operatorArr[0] = operator;
          operatorArr[1] = '文字包含';
          operatorArr[2] = '_c';
          operatorArr[3] = 'Contains';
        } else {
          operatorArr[0] = operator;
          operatorArr[1] = '等于';
          operatorArr[2] = '';
          operatorArr[3] = 'Equal';
        }
        return operatorArr;
      },
      // 操作符数据转换 （ companyType，_g，大于，GreaterThan --->  companyType_g ）
      operatorReChange(operator) {
        let operatorArr = new Array(2);
        if (operator == 'GreaterThan') {
          operatorArr[0] = '大于';
          operatorArr[1] = '_g';
        } else if (operator == 'LessThan') {
          operatorArr[0] = '小于';
          operatorArr[1] = '_l';
        } else if (operator == 'GreaterThanOrEqual') {
          operatorArr[0] = '大于等于';
          operatorArr[1] = '_ge';
        } else if (operator == 'LessThanOrEqual') {
          operatorArr[0] = '小于等于';
          operatorArr[1] = '_le';
        } else if (operator == 'NotEqual') {
          operatorArr[0] = '不等于';
          operatorArr[1] = '_n';
        } else if (operator == 'Contains') {
          operatorArr[0] = '文字包含';
          operatorArr[1] = '_c';
        } else {
          operatorArr[0] = '等于';
          operatorArr[1] = '';
        }
        return operatorArr;
      },

      // 筛选结果 将table对象转换为json字符串
      toFilteringJson() {
        let jsonStr = '{';
        if (this.dataFiltering.length > 0) {
          for (let key in this.dataFiltering) {
            jsonStr += '"' + this.dataFiltering[key].column + this.dataFiltering[key].rule + '":"' + this.dataFiltering[key].keyValue + '",';
          }
          jsonStr = jsonStr.substring(0, jsonStr.length - 1);
          jsonStr += '}';
        } else {
          jsonStr = '';
        }
        this.$emit('bindFilter', jsonStr);
        this.close();
      },

      // 打开筛选编辑表单
      filteringFmModalopen(row) {
        // // row = null表示新增
        if (row != null) {
          this.data.code = row.column;
          this.data.operator = row.operator;
          this.data.keyValue = row.keyValue;
        }
        // 表示新增
        else {
          this.data.code = '';
          this.data.rule = '';
          this.data.operator = 'Equal';
          this.data.keyValue = '';
        }
        this.filteringFmModal = true;
      },

      // 添加筛选字段表单确认
      async saveFilteringForm() {
        if (!!(this.data.code || '').trim() && !!(this.data.keyValue || '').trim() && !!(this.data.operator || '').trim()) {
          let ope = this.operatorReChange(this.data.operator);
          let checkSort = false;
          this.dataFiltering.forEach(item => {
            // 如果编辑列与原数据中有相同列，则做更新不做添加
            if (item.column == this.data.code) {
              checkSort = true;
              (item.operatorType = ope[0]), (item.rule = ope[1]), (item.operator = this.data.operator), (item.keyValue = this.data.keyValue);
            }
          });
          if (!checkSort) {
            this.dataFiltering.push({
              column: this.data.code,
              operatorType: ope[0],
              rule: ope[1],
              operator: this.data.operator,
              keyValue: this.data.keyValue
            });
          }

          this.filteringFmModal = false;
        } else {
          this.error('Front_Msg_Column_Filtering_Required');
        }
      },
      SaveFiltering() {
        this.toFilteringJson();
      },

      // 筛选字段的移动操作
      // 移除一行数据
      removefiltering(row, index) {
        if (row != null) {
          this.dataFiltering.splice(index, 1);
        }
      },
      // 上移
      upfiltering(row, index) {
        if (index > 0) {
          this.dataFiltering.splice(index, 1);
          this.dataFiltering.splice(index - 1, 0, row);
        }
      },
      // 下移
      downfiltering(row, index) {
        if (index < this.dataFiltering.length - 1) {
          this.dataFiltering.splice(index, 1);
          this.dataFiltering.splice(index + 1, 0, row);
        }
      },
      // 打开字段选择界面
      openSelect() {
        this.$refs.columnCheck.open(this.dataView.model, 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();
          });
        });
      }
    }
  };
</script>
