<template>
  <div class="flame-table-info-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="table_name" clearable filterable style="width: 400px;" @change="changeTable" placeholder="请选择要操作的模型">
        <el-option v-for="(option, index) in option_app_tables" :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="flame_id"
        fit
        stripe
        highlight-current-row
        @current-change="handleCurrentChange"
        align="left"
        height="100%"
        max-height="100%"
      >
        <el-table-column type="index" label="序号" width="50" align="center" header-align="center" fixed></el-table-column>
        <el-table-column label="字段名" prop="field_name" width="200" fixed></el-table-column>
        <el-table-column label="字段相关" header-align="center">
          <el-table-column label="字段说明" :width="InputWidth" prop="field_description" header-align="center" fixed>
            <template slot-scope="{ row }">
              <div style="text-align:center"><input class="edit-cell" v-model="row.field_description" /></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" size="mini" 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" size="mini" 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" size="mini" 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="弹出列表是否显示" 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_dialog"></el-checkbox></div>
            </template>
          </el-table-column>
          <el-table-column label="查询下拉是否显示" style="text-align: center;" prop="is_display_search" header-align="center" :width="checkWidth">
            <template slot-scope="{ row }" align="center">
              <div style="text-align:center"><el-checkbox v-model="row.is_display_search"></el-checkbox></div>
            </template>
          </el-table-column>
          <el-table-column label="编辑界面是否显示" style="text-align: center;" prop="is_display_detail" header-align="center" :width="checkWidth">
            <template slot-scope="{ row }" align="center">
              <div style="text-align:center"><el-checkbox v-model="row.is_display_detail"></el-checkbox></div>
            </template>
          </el-table-column>
          <el-table-column label="编辑界面是否只读" style="text-align: center;" prop="is_detail_read_only" header-align="center" :width="checkWidth">
            <template slot-scope="{ row }" align="center">
              <div style="text-align:center"><el-checkbox v-model="row.is_detail_read_only"></el-checkbox></div>
            </template>
          </el-table-column>
          <el-table-column label="是否可以为空" style="text-align: center;" prop="is_null_space" header-align="center" :width="checkWidth">
            <template slot-scope="{ row }" align="center">
              <div style="text-align:center"><el-checkbox v-model="row.is_null_space"></el-checkbox></div>
            </template>
          </el-table-column>
          <el-table-column label="是否可以重复" style="text-align: center;" prop="is_repeat" header-align="center" :width="checkWidth">
            <template slot-scope="{ row }" align="center">
              <div style="text-align:center"><el-checkbox v-model="row.is_repeat"></el-checkbox></div>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="控件类型选项" header-align="center">
          <el-table-column label="平台Web管理端" :width="InputWidth" prop="web_ui_control_type" header-align="center">
            <template slot-scope="{ row }">
              <div style="text-align:center">
                <el-select v-model="row.web_ui_control_type" size="mini" placeholder="请选择">
                  <el-option v-for="item in option_control_type" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
                <!-- <input class="edit-cell" v-model="row.web_ui_control_type" /> -->
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column label="手机端" header-align="center"> -->
          <el-table-column label="H5网页端" :width="InputWidth" prop="h5_ui_control_type" header-align="center">
            <template slot-scope="{ row }">
              <div style="text-align:center">
                <el-select v-model="row.h5_ui_control_type" size="mini" placeholder="请选择">
                  <el-option v-for="item in option_control_type" :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="wx_ui_control_type" header-align="center">
            <template slot-scope="{ row }">
              <div style="text-align:center">
                <el-select v-model="row.wx_ui_control_type" size="mini" placeholder="请选择">
                  <el-option v-for="item in option_control_type" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </div>
            </template>
            <!-- </el-table-column> -->
          </el-table-column>
        </el-table-column>

        <el-table-column label="下拉选项(值与值用逗号分开)" header-align="center">
          <el-table-column label="下拉后台值列表" prop="com_box_value" :width="InputWidth" header-align="center">
            <template slot-scope="{ row }">
              <input class="edit-cell" v-model="row.com_box_value" />
            </template>
          </el-table-column>
          <el-table-column label="下拉显示值列表" prop="com_box_display_name" :width="InputWidth" header-align="center">
            <template slot-scope="{ row }">
              <input class="edit-cell" v-model="row.com_box_display_name" />
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="字段相关" header-align="center">
          <el-table-column label="默认值" :width="InputWidth" prop="default_value" header-align="center">
            <template slot-scope="{ row }">
              <div style="text-align:center"><input class="edit-cell" v-model="row.default_value" /></div>
            </template>
          </el-table-column>
          <el-table-column label="最大值" :width="InputWidth" prop="field_max_value" header-align="center">
            <template slot-scope="{ row }">
              <div style="text-align:center"><input class="edit-cell" v-model="row.field_max_value" /></div>
            </template>
          </el-table-column>
          <el-table-column label="最小值" :width="InputWidth" prop="field_min_value" header-align="center">
            <template slot-scope="{ row }">
              <div style="text-align:center"><input class="edit-cell" v-model="row.field_min_value" /></div>
            </template>
          </el-table-column>
          <el-table-column label="数据权限要过滤表名" :width="InputWidth" prop="permission_table" header-align="center">
            <template slot-scope="{ row }">
              <div style="text-align:center">
                <el-select v-model="row.permission_table" size="mini" clearable placeholder="请选择">
                  <el-option v-for="item in options_table" :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="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" size="mini" 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="是否外键" prop="is_fk" :width="checkWidth" header-align="center">
            <template slot-scope="{ row }" align="center">
              <div style="text-align:center"><el-checkbox v-model="row.is_fk"></el-checkbox></div>
            </template>
          </el-table-column>
          <el-table-column label="外键对应的表名" prop="fk_table_name" :width="InputWidth" header-align="center">
            <template slot-scope="{ row }">
              <el-select v-model="row.fk_table_name" size="mini" clearable placeholder="请选择">
                <el-option v-for="item in options_table" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="对应外键表的字段名" prop="fk_table_name_field" :width="InputWidth" header-align="center">
            <template slot-scope="{ row }">
              <el-select v-model="row.fk_table_name_field" size="mini" clearable placeholder="请选择">
                <el-option v-for="item in options_col[row.fk_table_name]" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
              <!-- <input class="edit-cell" v-model="row.fk_table_name_field" /> -->
            </template>
          </el-table-column>
          <el-table-column label="外键转换显示的字段" prop="fk_table_display_field_name" :width="InputWidth" header-align="center">
            <template slot-scope="{ row }">
              <el-select v-model="row.fk_table_display_field_name" size="mini" clearable placeholder="请选择">
                <el-option v-for="item in options_col[row.fk_table_name]" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
              <!-- <input class="edit-cell" v-model="row.fk_table_display_field_name" /> -->
            </template>
          </el-table-column>
          <el-table-column label="引用类型显示字段列表" prop="fk_table_ref_display_fields" :width="InputWidth" header-align="center">
            <template slot-scope="{ row }">
              <!-- <el-select v-model="row.fk_table_ref_display_fields" multiple collapse-tags size="mini" clearable placeholder="请选择">
                <el-option v-for="item in options_col[row.fk_table_name]" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select> -->
             
              <input class="edit-cell" v-model="row.fk_table_ref_display_fields" />
            </template>
          </el-table-column>

          <el-table-column label="获取外键表数据的脚本" prop="fk_sql" :width="InputWidth" header-align="center">
            <template slot-scope="{ row }">
              <input class="edit-cell" v-model="row.fk_sql" />
            </template>
          </el-table-column>
        </el-table-column>

        <el-table-column label="系统自动完成" header-align="center">
          <el-table-column label="自动产生类型" prop="col_identity" :width="InputWidth" header-align="center">
            <template slot-scope="{ row }">
              <!-- <input class="edit-cell" v-model="row.col_identity" /> -->
              <div style="text-align:center">
                <el-select v-model="row.col_identity" size="mini" clearable placeholder="请选择">
                  <el-option v-for="item in options_col_identity" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
                <!-- <input class="edit-cell" v-model="row.web_ui_control_type" /> -->
              </div>
            </template>
          </el-table-column>
          <el-table-column label="执行的脚本或方法" prop="col_identity_item" :width="InputWidth" header-align="center">
            <template slot-scope="{ row }">
              <input class="edit-cell" v-model="row.col_identity_item" />
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
      <!-- <hr />
      <pre style="text-align: left">
        {{tableData}}
      </pre>-->
    </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';
import _ from 'lodash';
export default {
  name: 'Frame-table-info-item',
  data() {
    return {
      table_height: null,
      app_id: null,
      table_name: '',
      checkWidth: 80,
      InputWidth: 180,
      option_control_type: [
        { label: '文本输入框', value: 'Input' },
        { label: '文本选择框', value: 'Input_btn' },
        { label: '文本树型选择框', value: 'Input_tree' },
        { label: '下拉单项选择框', value: 'Select' },
        { label: '下拉多项选择框', value: 'Multi-Select' },
        { label: '日期选择框', value: 'DatePicker' },
        { label: '是否选择框', value: 'Radio' }
      ],
      options_col_identity: [
        { label: '编码', value: 'code' },
        { label: '层级', value: 'rank' },
        { label: '当前时间', value: 'current_date' },
        { label: '单据编码', value: 'sheet_id' }
      ],
      options_table: [],
      optionsFixed: [{ label: '左边', value: 'left' }, { label: '右边', value: 'right' }],
      optionsAlign: [{ label: '向左对齐', value: 'left' }, { label: '居中对齐', value: 'center' }, { label: '向右对齐', value: 'right' }],
      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' }
      ],
      option_apps: [{ value: '', label: '' }],
      option_app_tables: [{ value: '', label: '' }],
      options_col: {},
      dropCol: [],
      tableData: [],
      currentRow: null
    };
  },
  created() {
    // this.getTableHeight();
  },
  mounted() {
    let that = this;
    // that.getAppInfo();
    that.changeApp();
    // that.getUIWebControlType();
    this.rowDrop();
    // this.columnDrop();
  },
  computed: {
    ...mapGetters('global', ['flameTableInfos', 'getOneTableInfoItemByTableName'])
  },
  methods: {
    ...mapActions('global', ['reloadFrame']),
    // 获取下拉的表名
    getUIWebControlType() {
      let that = this;
      config.dict({ conditions: { 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 });
        });
      });
    },
    // app选择变化时，要修改操作的模型
    changeApp() {
      let that = this;
      let temp_all = that.flameTableInfos;
      let temp = [];
      temp_all.forEach(e => {
        // if(e.app_id === that.app_id){
        temp.push(e);
        // }
      });
      that.option_app_tables = [];
      // 复制数据到tableData 中,先通过JSON.stringify将对象转换字符串，再通过JSON.parse转换一个一个新的对象，这样就实现深copy
      // JSON.stringify把对象转成字符串，再用JSON.parse把字符串转成新的对象
      let table_temp = _.cloneDeep(temp);
      /// JSON.parse(JSON.stringify(temp));
      // console.log(that.tableData);
      that.options_table = [];
      that.option_app_tables = [];

      that.table_name = null;
      table_temp.forEach(e => {
        // if(e.app_id === that.app_id){

        that.option_app_tables.push({ value: e.table_name, label: e.table_name + '--' + e.table_description });
        that.options_table.push({ value: e.table_name, label: e.table_name + '--' + e.table_description });
        // }
        
        let table_col = [];
        let table_info_item = that.getOneTableInfoItemByTableName(e.table_name);
        table_info_item.forEach(e => {
          table_col.push({ label: e.field_description, value: e.field_name });
        });
        that.options_col[e.table_name]= table_col ;
      });
      // console.log(that.option_app_tables);
      that.rowDrop();
    },
    // 操作的模型发生变化时要修改grid的数据源
    changeTable() {
      let that = this;
      // that.option_app_tables = [];
      this.loadTableData();
      // that.flameTableInfos.forEach(element => {
      //   that.option_app_tables.push({ value: element.table_name, label: element.table_name + '--' + element.table_description });
      //   that.options_table.push({ value: element.table_name, label: element.table_name + '--' + element.table_description });
      // });
    },
    // 加载表grid表要的数据信息
    loadTableData() {
      let that = this;
      that.tableData = [];

      let temp_all = that.getOneTableInfoItemByTableName(that.table_name);
      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 =_.cloneDeep(temp);
      // JSON.parse(JSON.stringify(temp));
      that.rowDrop();
    },
    // 提交方法
    submit() {
      let that = this;
      let k = 1;
      that.tableData.forEach(element => {
        element.field_color_der = k;
        element.search_sort = k;
        k += 1;
      });
      let commit_data = { data: that.tableData };
      system.batchUpdateInstance('flame_table_info_item', commit_data, 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-table-info-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>
