<template>
  <div>
    <!-- <a v-if="layout" style="color: #808695" @click="showModal">
      <Icon type="ios-settings" size="22" style="margin:-5px 0px "/>
      <span style="font-size: 8px">显示列</span></a> -->
       <Button type="primary" v-if="layout" @click="showModal">显示列</Button>
    <Modal v-model="customLayoutModal" title="编辑显示字段" width="700" :scrollable="true">
      <div>
        <row>
          <Col span="10">
            隐藏字段
            <Input v-model="key1" ref="input1" prefix="ios-search" placeholder="搜索" @blur='queryData'
                   @input="queryData"/>
            <card style="height: 450px;overflow-y: scroll;margin-top: -2px">
              <CellGroup @on-click="click1" ref="group1" style="width:110%;margin-left: -9px">
                <Cell :name="index" v-for="(item,index) in columns1" :key="index" :selected="num==index" :title="item.title" />
              </CellGroup>
            </card>
          </Col>
          <Col span="2">
            <div style="margin-top: 180px;margin-left: 15px">
              <Button style="width: 23px" size="small" @click="toShowColumn">
                <Icon type="ios-arrow-forward" size="18" style="margin-left: -5px;color: #808695"/>
              </Button>
              <br>
              <Button style="width: 23px;margin-top: 18px" size="small" @click="toHideColumn">
                <Icon type="ios-arrow-back" size="18" style="margin-left: -6px;color: #808695"/>
              </Button>
            </div>
          </Col>
          <Col span="10">
            显示字段（不可少于4个）
            <Input v-model="key2" ref="input2" prefix="ios-search" placeholder="搜索" @blur='queryData2'
                   @input="queryData2"/>
            <card style="height: 450px;;overflow-y: scroll;margin-top: -2px">
              <CellGroup @on-click="click2" ref="group2" style="width:110%;margin-left: -9px">
                <Cell :name="index" v-for="(item,index) in columns2" :key="index" :selected="num2==index" :title="item.title"/>
              </CellGroup>
            </card>
          </Col>
          <Col span="2">
            <div v-if="this.key2.length==0" style="margin-top: 20px;margin-left: 6px">
              <Button style="width: 25px;height: 25px" size="small" @click="toUp">
                <Icon type="md-arrow-round-up" size="18" style="margin-left: -5px;color: #2db7f5"/>
              </Button>
              <br>
              <Button style="width: 25px;height: 25px;margin-top: 10px" size="small" @click="toDown">
                <Icon type="md-arrow-round-down" size="18" style="margin-left: -5px;color: #2db7f5"/>
              </Button>
            </div>
          </Col>
          <!-- <div style="float: left">
             <Checkbox v-model="column.show" style="size: 20px">{{column.title}}</Checkbox>
           </div>
           <div style="float: right">
             <Icon type="md-arrow-dropup-circle" color="#2d8cf0" style="cursor: pointer"
                   @click="showColumnsIndexChange(i,'up')" size="20"/>
             <Icon type="md-arrow-dropdown-circle" color="#17233d" style="cursor: pointer"
                   @click="showColumnsIndexChange(i,'down')" size="20"/>
           </div>-->
        </row>
      </div>
      <template #footer>
        <div>
          <Button @click="cancel" size="small">关闭</Button>
          <Button type="primary" :loading="saveLoading" @click="ok" size="small">保存设置</Button>
        </div>
      </template>
    </Modal>
  </div>
</template>
<script>
  import {getUserLayoutColumns, saveUserLayoutColumns} from './layout-columns-api'

  let $this;
  export default {
    name: 'bcTableEx',
    components: {},
    props: {
      allColumns: {
        type: Array,
        default: function () {
          return [{title: '勾选框(建议勿动)', type: 'selection', width: 60, align: 'center', show: true}]
        },
      },
      pageKey: {
        type: String,
        default: '',
      },
      dataColumns: {
        type: Array,
        default: function () {
          return []
        }
      },
      columnsShow: {
        type: Array,
        default: function () {
          return []
        }
      },
      firstColumn: {//第一列显示的内容
        type: String,
        default: '',
      },
      layout: {//第一列显示的内容
        type: Boolean,
        default: false,
      },
      ex: {//第一列显示的内容
        type: Boolean,
        default: false,
      }
    },
    data() {
      return {
        width: '100%',
        columns: [],
        renders:{},
//自定义布局部分
        num: null,
        num2: null,
        title: '',
        title2: '',
        key1: '',
        key2: '',
        columns1: [],
        allColumns1: [],
        columns2: [],
        allColumns2: [],
        firstColumns: {},
        saveLoading: false,
        customLayoutModal: false,
        layoutColumns: [],
        initColumns: this.allColumns,
        userColumns: this.dataColumns,
      }
    },
    methods: {
      //表格工具部分
      sizeControl() {
        if(this.columns.length>0){
          for(let i=0;i<this.columns.length;i++){
            if(this.renders[this.columns[i].title]!=undefined){
              this.columns[i].render=this.renders[this.columns[i].title]
            }
          }
        }
        let selection = {type: 'selection', width: 60, align: 'center', ifNotExport: true};
        let index = {type: 'index', width: 70, align: 'center', title: '序号', ifNotExport: true};
        if (this.firstColumn === 'selection') {
          this.columns.splice(0, 0, selection);
        } else if (this.firstColumn === 'index') {
          this.columns.splice(0, 0, index);
        }
        if (this.columns.length > 0) {
          for (let i = this.firstColumn === 'nothing' ? 0 : 1; i < this.columns.length; i++) {
            if (!this.columns[i].width) {
              if (this.columns[i].title.replace(/[\u0391-\uFFE5]/g, "aa").length <= 4) {
                this.$set(this.columns[i], 'minWidth', 80);
              } else if (this.columns[i].title.replace(/[\u0391-\uFFE5]/g, "aa").length <= 6) {
                this.$set(this.columns[i], 'minWidth', 100);
              } else if (this.columns[i].title.replace(/[\u0391-\uFFE5]/g, "aa").length <= 8) {
                this.$set(this.columns[i], 'minWidth', 120);
              } else if (this.columns[i].title.replace(/[\u0391-\uFFE5]/g, "aa").length <= 10) {
                this.$set(this.columns[i], 'minWidth', 135);
              } else {
                this.$set(this.columns[i], 'minWidth', 130);
              }
              /*this.$set(this.columns[i], 'maxWidth', 240);*/
            }
            if (this.columns[i].headCenter) {
              this.$set(this.columns[i], 'className', 'test-name')
            }
            if (this.columns[i].slot==undefined && this.columns[i].render==undefined) {
              var a = (h, params) => {
                return h('div', [
                  h('div', {
                    style: {
                      width: '100%',
                      display: '-webkit-box',
                      webkitLineClamp: 2,
                      webkitBoxOrient: 'vertical',
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                    },
                    domProps: {title: params.row[this.columns[i].key]},
                    on: {
                      click: (e) => {
                        e.stopPropagation();
                      }
                    }
                  }, params.row[this.columns[i].key])
                ]);
              };
              this.$set(this.columns[i], 'render', a);
            }
          }
        }
      },
      //自定义布局部分
      showModal() {
        this.customLayoutModal = true;
      },
      click1(index) {
        this.num = index;
        this.title = this.columns1[index].title
      },
      click2(index) {
        this.num2 = index;
        this.title2 = this.columns2[index].title
      },
      toShowColumn() {
        if (this.num != null) {
          let num = this.num;
          this.columns2.push(this.columns1[num]);
          this.allColumns2.push(this.columns1[num]);
          this.num2 = this.columns2.length - 1;
          this.columns1.splice(num, 1);
          this.num = null;
          if (this.key1.length > 0) {
            for (let i = 0; i < this.allColumns1.length; i++) {
              if (this.columns1[i].title === this.title) {
                this.allColumns1.splice(i, 1)
              }
            }
          } else {
            this.allColumns1.splice(num, 1)
          }
        }
      },
      toHideColumn() {
        if (this.num2 != null) {
          let num = this.num2;
          if(this.columns2.length<=4){
            this.$Message.warning("显示字段不能少于4个！");
            return
          }
          this.columns1.push(this.columns2[num]);
          this.allColumns1.push(this.columns2[num]);
          this.num = this.columns1.length - 1;
          this.columns2.splice(num, 1);
          this.num2 = null;
          if (this.key2.length > 0) {
            for (let i = 0; i < this.allColumns2.length; i++) {
              if (this.columns2[i].title === this.title2) {
                this.allColumns2.splice(i, 1)
              }
            }
          } else {
            this.allColumns2.splice(num, 1)
          }
        }
      },
      toUp() {
        if (this.num2 != null) {
          if (this.num2 != 0) {
            this.columns2[this.num2] = this.columns2.splice(this.num2 - 1, 1, this.columns2[this.num2])[0];
            this.allColumns2[this.num2] = this.allColumns2.splice(this.num2 - 1, 1, this.allColumns2[this.num2])[0];
            this.num2 = this.num2 - 1;
          } else {
            this.$Message.warning("已经置顶！");
          }
        }

      },
      toDown() {
        if (this.num2 != null) {
          if (this.num2 + 1 != this.columns2.length) {
            this.columns2[this.num2] = this.columns2.splice(this.num2 + 1, 1, this.columns2[this.num2])[0];
            this.allColumns2[this.num2] = this.allColumns2.splice(this.num2 + 1, 1, this.allColumns2[this.num2])[0];
            this.num2 = this.num2 + 1;
          } else {
            this.$Message.warning("已经到底了！");
          }
        }
      },
      queryData() {
        //并没有输入关键字时，就不要再搜索了
        if (this.key1 == '' || this.key1 == null) {
          this.columns1 = JSON.parse(JSON.stringify(this.allColumns1));
          return;
        }
        //搜索
        let list = this.allColumns1.filter(item => item.title.indexOf(this.key1) >= 0);
        this.columns1 = list;

      },
      queryData2() {
        //并没有输入关键字时，就不要再搜索了
        if (this.key2 == '' || this.key2 == null) {
          this.columns2 = JSON.parse(JSON.stringify(this.allColumns2));
          return;
        }
        //搜索
        let list = this.allColumns2.filter(item => item.title.indexOf(this.key2) >= 0);
        this.columns2 = list;

      },
      sortShow() {
        let showColumns = [];
        let hideColumns = [];
        this.columns.forEach(colum => {
          if (colum.show && colum.show === true) {
            showColumns.push(colum);
          } else if (colum.show != undefined && colum.show === false) {
            hideColumns.push(colum);
          }
        });
        this.columns1 = JSON.parse(JSON.stringify(hideColumns));
        this.allColumns1 = JSON.parse(JSON.stringify(hideColumns));
        this.columns2 = JSON.parse(JSON.stringify(showColumns));
        this.allColumns2 = JSON.parse(JSON.stringify(showColumns));
        this.columns=JSON.parse(JSON.stringify(showColumns));

      },
      picekHide() {
        let heideColumns = JSON.parse(JSON.stringify(this.dataColumns));
        for (let i = 0; i < this.layoutColumns.length; i++) {
          for (let j = 0; j < heideColumns.length; j++) {
            if (this.layoutColumns[i].title == heideColumns[j].title) {
              heideColumns.splice(j, 1);
            }
          }
        }
        this.columns1=JSON.parse(JSON.stringify(heideColumns));
        this.allColumns1=JSON.parse(JSON.stringify(heideColumns));
      },
      ok() {
        this.saveLoading = true;
        saveUserLayoutColumns(this.$store.state.user.userId, this.pageKey, JSON.stringify(this.allColumns2)).then(data => {
          this.$Message.success('操作成功！');
          this.saveLoading = false;
          this.selectLayout();
          this.customLayoutModal = false;
        }).catch(err => {
          this.$Message.error('操作失败！');
          this.saveLoading = false;
          console.log(err)
        })

      },
      cancel() {
        this.saveLoading = false;
        this.customLayoutModal = false;
      },
      selectLayout() {
        //查询用户的布局配置
        getUserLayoutColumns(this.$store.state.user.userId, this.pageKey).then(res => {
          this.layoutColumns = [];
          this.layoutColumns = res.data.result ? JSON.parse(res.data.result):[];
          if (this.layoutColumns.length > 0) {
            this.columns = JSON.parse(JSON.stringify(this.layoutColumns));
            this.picekHide();
            if(this.ex){
              this.sizeControl();
            }
            this.columns2=JSON.parse(JSON.stringify(this.layoutColumns));
            this.allColumns2=JSON.parse(JSON.stringify(this.layoutColumns));
          } else {
            this.sortShow();
            if(this.ex){
              this.sizeControl();
            }
          }
          this.$emit('update:columnsShow', this.columns)
        }).catch(err => {
          this.$Message.error("查询用户自定义布局设置失败!");
          console.log(err);
          this.$emit('update:columnsShow', this.columns)
        });
      }
    },
    mounted() {
      $this = this;
      // this.selectLayout();
    },
    watch: {
      dataColumns: {
        immediate: true,
        handler: function () {
          this.columns = JSON.parse(JSON.stringify(this.dataColumns));
          if(this.dataColumns.length>0){
            for(let i=0;i<this.dataColumns.length;i++){
              if(this.dataColumns[i].render!=undefined){
                this.renders[this.dataColumns[i].title]=this.dataColumns[i].render
              }
            }
          }
          if (this.ex && this.layout) {
            this.selectLayout();
          } else if (this.ex) {
            this.sizeControl();
            this.$emit('update:columnsShow',this.columns)
          } else if (this.layout) {
            this.selectLayout();
          }
        }
      },
     /* pageKey: {
          immediate: true,
          handler: function () {
            this.selectLayout();
          }
      }*/
    }
  }
</script>
<style>
  .ivu-table th.test-name {
    text-align: center;
  }
</style>
