<template>
  <div class="flame-query-item">
    <div class="filter">
      <!-- <el-select size="mini" v-model="app_id" clearable filterable style="width: 400px;" @change="changeApp" placeholder="请选择要操作的模型">
        <el-option v-for="(option, index) in option_apps" :key="index" :label="option.label" :value="option.value"></el-option>
      </el-select> -->
      
      <el-select size="mini" v-model="query_code" clearable filterable style="width: 400px;" @change="ChangeTableKey" placeholder="请选择要操作的模型">
        <el-option v-for="(option, index) in option_querys" :key="index" :label="option.label" :value="option.value"></el-option>
      </el-select>
      <el-button type="primary" class="bt_search" @click="handleClickUp" size="mini" icon="el-icon-top">上移</el-button>
      <el-button type="primary" class="bt_search" @click="handleClickDown" size="mini" icon="el-icon-bottom">下移</el-button>
      <el-button type="primary" class="bt_search" @click="submit" size="mini" icon="el-icon-upload">提交</el-button>
    <el-button type="primary" class="bt_search" @click="reloadServerFrameTable" size="mini" icon="el-icon-upload">重置模型</el-button>
    </div>
    <div class="table">
      <el-table
        :data="tableData"
        border
        row-key="id"
        fit
        stripe
        highlight-current-row
        @current-change="handleCurrentChange"
        align="left"
        height="100%"
        max-height="100%"
      >
      <el-table-column type="index" width="50" label="序号" align="center" header-align="center" fixed></el-table-column>
      
        <el-table-column label="字段相关" header-align="center">
          <el-table-column label="英文字段名称" :width="InputWidth" prop="field_ename" header-align="center" fixed>
            <template slot-scope="{ row }">
              <div style="text-align:center"><input class="edit-cell" v-model="row.field_ename" /></div>
            </template>
          </el-table-column>
          <el-table-column label="中文字段名称" :width="InputWidth" prop="field_cname" header-align="center">
            <template slot-scope="{ row }">
              <div style="text-align:center"><input class="edit-cell" v-model="row.field_cname" /></div>
            </template>
          </el-table-column>
          <el-table-column label="显示的宽度" :width="InputWidth" prop="field_description" header-align="center">
            <template slot-scope="{ row }">
              <div style="text-align:center"><input class="edit-cell" v-model="row.width" /></div>
            </template>
          </el-table-column>
          <el-table-column label="数据格式化方式" :width="InputWidth" prop="str_format" header-align="center">
            <template slot-scope="{ row }">
              <div style="text-align:center">
                <el-select v-model="row.str_format" clearable placeholder="请选择">
                  <el-option v-for="item in optionsFormats" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </div>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="对齐方式" header-align="center">
          <el-table-column label="表头对齐方式" :width="InputWidth" prop="header_align" header-align="center">
            <template slot-scope="{ row }">
              <div style="text-align:center">
                <el-select v-model="row.header_align" clearable placeholder="请选择">
                  <el-option v-for="item in optionsAlign" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="单元格对齐方式" :width="InputWidth" prop="cell_align" header-align="center">
            <template slot-scope="{ row }">
              <div style="text-align:center">
                <el-select v-model="row.cell_align" clearable placeholder="请选择">
                  <el-option v-for="item in optionsAlign" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </div>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="显示设置" header-align="center">
          <el-table-column label="表格列表是否显示" style="text-align: center;" prop="is_display" :width="checkWidth" header-align="center">
            <template slot-scope="{ row }" align="center">
              <div style="text-align:center"><el-checkbox v-model="row.is_display"></el-checkbox></div>
            </template>
          </el-table-column>
          <el-table-column label="分组名" :width="InputWidth" prop="group_name" header-align="center">
            <template slot-scope="{ row }">
              <div style="text-align:center"><input class="edit-cell" v-model="row.group_name" /></div>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="固定信息" header-align="center">
          <el-table-column label="是否固定" :width="checkWidth" prop="is_fixed"  header-align="center" fixed>
            <template slot-scope="{ row }">
              <div style="text-align:center"><el-checkbox v-model="row.is_fixed"></el-checkbox></div>
            </template>
          </el-table-column>
          <el-table-column label="固定的位置" :width="InputWidth" prop="fixed_position" header-align="center">
            <template slot-scope="{ row }">
              <div style="text-align:center">
                <el-select v-model="row.fixed_position" clearable placeholder="请选择">
                  <el-option v-for="item in optionsFixed" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </div>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="备注" header-align="center">
            <el-table-column label="备注1" prop="remrak_01" :width="InputWidth" header-align="center">
              <template slot-scope="{ row }">
                 <div style="text-align:center"><input class="edit-cell" v-model="row.remark_01" /></div>
              </template>
            </el-table-column>
            <el-table-column label="备注3" prop="remrak_02" :width="InputWidth" header-align="center">
              <template slot-scope="{ row }">
               <div style="text-align:center"><input class="edit-cell" v-model="row.remrak_02" /></div>
              </template>
            </el-table-column>
            <el-table-column label="备注3" prop="remrak_03" :width="InputWidth" header-align="center">
              <template slot-scope="{ row }">
                 <div style="text-align:center"><input class="edit-cell" v-model="row.remrak_03" /></div>
              </template>
            </el-table-column>
            <el-table-column label="备注4" prop="remrak_04" :width="InputWidth" header-align="center">
              <template slot-scope="{ row }">
                <div style="text-align:center"><input class="edit-cell" v-model="row.remrak_04" /></div>
              </template>
            </el-table-column>
        
            <el-table-column label="备注5" prop="remrak_05" :width="InputWidth" header-align="center">
              <template slot-scope="{ row }">
               <div style="text-align:center"><input class="edit-cell" v-model="row.remrak_05" /></div>
              </template>
            </el-table-column>
            <el-table-column label="备注6" prop="remrak_06" :width="InputWidth" header-align="center">
              <template slot-scope="{ row }">
                <div style="text-align:center"><input class="edit-cell" v-model="row.remrak_06" /></div>
              </template>
            </el-table-column>
          </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import Sortable from 'sortablejs';
import { mapState, mapActions, mapGetters } from 'vuex';
import config from '../../../api/config.js';
import system from '../../../api/system.js';
import flame from '../../../api/flame.js';
export default {
  name: 'Frame-custome-query-item',
  data() {
    return {
      table_height: null,
      app_id: null,
      query_code: '',
      checkWidth: 80,
      InputWidth: 180,
      option_control_type: [],
      options_table: [],
      optionsFormats: [
        { label: '默认格式(不做处理)', value: 'formatDefault' },
        { label: '是否格式(false-否true-是)', value: 'formatBoolean' },
        { label: '日期格式(YYYY-MM-DD)', value: 'formatDate' },
        { label: '日期时间格式(YYYY-MM-DD HH:MM:SS)', value: 'formatDateTime' },
        { label: '时间格式(HH:MM:SS)', value: 'formatTime' },
        { label: '百分比(0.5035==>50.35%)', value: 'formatPercentage' },
        { label: '整数格格式没有小数(125)', value: 'formatInteger' },
        { label: '货币保留1位小数(124.5)', value: 'formatCurrency1' },
        { label: '货币保留2位小数(124.50)', value: 'formatCurrency2' },
        { label: '货币保留3位小数(124.500)', value: 'formatCurrency3' },
        { label: '货币保留4位小数(124.5000)', value: 'formatCurrency4' },
        { label: '货币保留5位小数(124.50000)', value: 'formatCurrency5' }
      ],
      optionsFixed: [{ label: '左边', value: 'left' }, { label: '右边', value: 'right' }],
      optionsAlign: [{ label: '向左对齐', value: 'left' }, { label: '居中对齐', value: 'center' }, { label: '向右对齐', value: 'right' }],
      option_querys: [{ value: '', label: '' }],
      option_apps:[{ value: '', label: '' }],
      dropCol: [],
      tableData: [],
      currentRow: null
    };
  },
  created() {
    let that = this;
    // that.getTableHeight();
    
  },
 
  mounted() {
    let that = this;
   
    // that.getApp();
    // that.getComBox();
    that.changeApp();
    // that.getUIWebControlType();
    this.rowDrop();
    // this.columnDrop();
  },
  computed: {
    ...mapGetters('global', ['flameQuerys', 'getOneQueryItemByCode'])
  },
  methods: {
    ...mapActions('global',['reloadFrame']),
    
    getApp() {
      let that = this;
      that.option_apps = [];
    
      flame.getAppInfo({}, res => {
        res.forEach(element => {
          that.option_apps.push({ value: element.flame_id, label: element.app_code + '--' + element.app_name });
        });
      });
      // that.getUIWebControlType();
    },
    // App选择项发生变化时
    changeApp() {
      // this.loadTableData();
      let that = this;
      that.getQuerys();
    },
    
    // 获取下拉的表名
    getUIWebControlType() {
      let that = this;
      config.dict({ config_group_code: 'UI_ControlType' }, res => {
        console.log('res', res);
        that.option_control_type = [];
        res.UI_ControlType.forEach(e => {
          that.option_control_type.push({ label: e.config_name, value: e.config_value });
        });
      });
    },
    getQuerys() {
      let that = this;
      that.option_querys = [];
      
      that.flameQuerys.forEach(element => {
        // if(element.app_id === that.app_id){
          that.option_querys.push({ value: element.query_code, label: element.query_code + '--' + element.query_name });
        // }
      });
    },
    // 选择项发生变化时
    ChangeTableKey() {
      this.loadTableData();
    },
    // 加载表的字段信息
    loadTableData() {
      let that = this;
      that.tableData = [];
      let temp_all = that.getOneQueryItemByCode(that.query_code);
      let temp = [];
      // 只自己的app_id的数据
      temp_all.forEach(e=>{
        // if (e.app_id === that.app_id){
          temp.push(e);
        // }
      });
      that.tableData = [];
      // 复制数据到tableData 中,先通过JSON.stringify将对象转换字符串，再通过JSON.parse转换一个一个新的对象，这样就实现深copy
      // JSON.stringify把对象转成字符串，再用JSON.parse把字符串转成新的对象
      
      that.tableData = JSON.parse(JSON.stringify(temp));
      that.rowDrop();
    },
    // 提交方法
    submit() {
      let that = this;
      let k = 1;
      that.tableData.forEach(element => {
        element.display_order = k;
        k += 1;
      });
      let commit_data ={data: that.tableData};
      system.batchUpdateInstance('flame_query_item', commit_data, res => {
        // console.log('res', res);
        if(res.result === true){
          that.reloadFrame();
          that.$message({
            type: 'success',
            message: '操作成功'
          });
        } else {
          that.$message({
            type: 'error',
            message: '操作失败'
          });
        }
        
      });
    },
    // 重置服务器上的缓存数据
    reloadServerFrameTable() {
      let that = this;
      flame.initFrameData({}, res => {
        if (res.result === true) {
          that.reloadFrame();
          that.$message({
            type: 'success',
            message: '操作成功,请重新登陆,才会有效.'
          });
        } else {
          that.$message({
            type: 'error',
            message: '操作失败'
          });
        }
      });
    },
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    getCurrrenRowIndex() {
      let that = this;
      for (let i = 0; i < that.tableData.length; i++) {
        if (that.tableData[i].flame_id == that.currentRow.flame_id) {
          return i;
        }
      }
      return -1;
    },
    handleClickUp() {
      let that = this;
      let index = that.getCurrrenRowIndex();
      console.log('当前索引：', index);
      if (index !== -1) {
        that.tableData.splice(index, 1);
        if (index - 1 >= 0) {
          that.tableData.splice(index - 1, 0, that.currentRow);
        } else {
          that.tableData.splice(this.tableData.length, 0, that.currentRow);
        }
      }
    },
    
    
    
    
    handleClickDown() {
      let that = this;
      let index = that.getCurrrenRowIndex();
      console.log('当前索引：', index);
      if (index !== -1) {
        that.tableData.splice(index, 1);
        if (index + 1 <= this.tableData.length) {
          that.tableData.splice(index + 1, 0, that.currentRow);
        } else {
          that.tableData.splice(0, 0, that.currentRow);
        }
      }
    },
    //行拖拽
    rowDrop() {
      const tbody = document.querySelector('.el-table__body-wrapper tbody');
      const _this = this;
      Sortable.create(tbody, {
        onEnd({ newIndex, oldIndex }) {
          const currRow = _this.tableData.splice(oldIndex, 1)[0];
          console.log('currRow:', currRow);
          _this.tableData.splice(newIndex, 0, currRow);
        }
      });
    },
    //列拖拽
    columnDrop() {
      const wrapperTr = document.querySelector('.el-table__header-wrapper tr');
      this.sortable = Sortable.create(wrapperTr, {
        animation: 180,
        delay: 0,
        onEnd: evt => {
          const oldItem = this.dropCol[evt.oldIndex];
          this.dropCol.splice(evt.oldIndex, 1);
          this.dropCol.splice(evt.newIndex, 0, oldItem);
        }
      });
    },
    getTableHeight() {
      let that = this;
      that.table_height = window.innerHeight - 195;
    }
  }
};
</script>

<style lang="scss" scoped>
.flame-query-item {
  height: calc(100% - 31px - #{$spacing-small});
}
.filter {
  padding: 0 $spacing-normal;
  width: calc(100% - #{$spacing-normal * 2});
  height: 60px;
  background: $theme-white-1;
  display: flex;
  align-items: center;
}
.table {
  height: calc(100% - 50px);
  // overflow-y: scroll;
}
</style>
