<template>
  <div class="">
    <el-dialog title="显示栏位管理" :visible.sync="visible" width="300px" append-to-body destroy-on-close :before-close="close" top="10vh">
      <!-- <div class="project-table-field">
        <el-transfer
            class="transfer"
            v-model="selected"
            :props="{
              key: 'fieldKey',
              label: 'fieldName'
            }"
            filterable
            :filter-method="filterMethod"
            :titles="['未选择', '已选择']"
            :button-texts="['', '']"
            :format="{ noChecked: '${total}', hasChecked: '${checked}/${total}' }"
            @right-check-change="rightCheckChange"
            @change="handleChange2"
            :data="dataList">
          <span slot-scope="{ option }">
            <span>{{ option.fieldName }}</span>
            <span style="float:right">
              <i class="el-icon-delete" @click.stop.prevent="delField(option)"></i>
              <i class="iconfont icon-bianji margin-left_10" @click.stop.prevent="editField(option)"></i>
            </span>
            </span>
          <div class="transfer-footer" slot="left-footer">
            <el-button @click="addField(0)" size="small" icon="el-icon-plus" circle></el-button>
          </div>
          <div class="transfer-footer" slot="right-footer">
            <el-button @click="handleQueryOrder(-1)" type="primary" size="small" icon="el-icon-top" circle></el-button>
            <el-button @click="handleQueryOrder(1)" size="small" icon="el-icon-bottom" circle></el-button>
            <el-button @click="addField(1)" size="small" icon="el-icon-plus" circle></el-button>
          </div>
        </el-transfer>
      </div> -->
      <div>
        <el-checkbox-group v-model="selected">
          <p v-for="option in dataList" :key="option.fieldKey" style="margin:10px 0;">
            <el-checkbox :label="option.fieldKey">
              <span>{{ option.fieldName }}</span>
            </el-checkbox>
            <span style="float:right">
              <i class="el-icon-delete" @click.prevent="delField(option)" style="font-size:16px"></i>
              <!-- <i class="iconfont icon-bianji margin-left_10" @click.prevent="editField(option)"></i> -->
            </span>
          </p>
        </el-checkbox-group>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submit" :loading="btnLoading">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="addVisible" width="650px" append-to-body :before-close="cancel">
      <div>
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="栏位名称">
            <el-input v-model="form.fieldName" placeholder="请输入栏位名称"></el-input>
          </el-form-item>
          <el-form-item label="栏位字段">
            <el-input v-model="form.fieldKey" placeholder="请输入栏位字段"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitField" :loading="btnLoading2">确 定</el-button>
      </div>
    </el-dialog>
    <AddOrEditField ref="addOrEditField" :reportId="reportId" :tableFields="dataList" @submit="queryInvalidFields(1)"></AddOrEditField>
  </div>
</template>

<script>
import AddOrEditField from './addOrEditField.vue'
export default {
  components:{
    AddOrEditField
  },
  props:['reportId'],
  data() {
    return {
      visible: false,
      dataList: [],
      btnLoading: false,
      selected: [],
      rightSelect: [],
      form:{},
      addVisible:false,
      btnLoading2: false,
      title:''
    }
  },
  mounted() {
  },
  methods: {
    //打开编辑显示栏位弹窗
    editField(option){
      this.title = '编辑显示栏位管理'
      this.form = JSON.parse(JSON.stringify(option))
      this.$refs.addOrEditField.open(this.form)
      // this.addVisible = true
    },
    //删除显示栏位
    delField(option){
      this.deletes([option.id])
    },
    deletes(ids){
      this.$confirm('是否确定删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$api.deleteInvalidFields(ids).then(response=>{
            if(response.code == 200){
              this.$message.success('删除成功')
              this.queryInvalidFields()
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      
    },
    //打开添加显示栏位弹窗
    addField(val){
      this.title = '添加显示栏位管理'
      this.form.fieldState=val
      this.addVisible = true
    },
    //关闭添加显示栏位弹窗
    cancel(){
      this.form = {}
      this.addVisible = false
    },
    //确认添加显示栏位
    submitField(){
      this.btnLoading2 = true
      this.form.reportId = this.reportId
      this.$api.addOrUpdateInvalidFields(this.form).then(response=>{
        if(response.code == 200){
          this.btnLoading2 = false
          if(this.form.id){
            this.$message.success('更新成功')
          }else{
            this.$message.success('添加成功')
          }
          this.cancel()
          this.queryInvalidFields()
        }
      }).catch(error=>{
        this.btnLoading2 = false
      })
    },
    //获取自定义栏位
    queryInvalidFields(val){
      this.$api.queryInvalidFields({reportId:this.reportId}).then(response=>{
            if(response.code == 200){
              
              if(!val){
                this.$emit('update',{val:response.data})
              }else{
                this.$emit('update',{val:response.data,update:true})
              }
              this.dataList = response.data
              this.selected = this.dataList.filter(item => item.fieldState).map(item => item.fieldKey)
            }
      })
    },
    handleQueryOrder(order) {
      this.rightSelect.map(item => {
        const index = this.selected.indexOf(item)
        const cIndex = index + order
        if (cIndex < 0 || cIndex >= this.selected.length) {
          return false
        }
        let current = this.dataList.find(item => item.fieldKey === this.selected[index])
        let exchange = this.dataList.find(item => item.fieldKey === this.selected[cIndex])
        current.fieldSort = current.fieldSort + order
        exchange.fieldSort = exchange.fieldSort + (order === -1 ? 1 : -1)
        this.dataList.sort((a, b) => {
          return a.fieldSort - b.fieldSort
        })
        const temp = this.selected[index]
        this.selected[index] = this.selected[cIndex] 
        this.selected[cIndex] = temp
      })
    },
    handleChange2() {
      let order = 1
      for (let i = 0; i < this.selected.length; i++) {
        const index = this.dataList.map(item => item.fieldKey).indexOf(this.selected[i])
        this.dataList[index].fieldSort = order++
      }
    },
    filterMethod(query, item) {
      return item.fieldName.indexOf(query) !== -1
    },
    rightCheckChange(data) {
      this.rightSelect = data
    },
    open(dataList) {
      // console.log(dataList)
      this.dataList = JSON.parse(JSON.stringify(dataList))
      this.selected = this.dataList.filter(item => item.fieldState).map(item => item.fieldKey)
      this.visible = true
    },
    close() {
      this.visible = false
      this.$emit('close')
    },
    submit() {
      // this.dataList.map(item => item.fieldState != this.selected.indexOf(item.fieldKey) === -1)
      // this.$emit('update', this.dataList)
      this.dataList.forEach(item => {
        item.fieldState = 0
        var index = this.selected.indexOf(item.fieldKey)
        if(index!=-1){
          item.fieldState = 1
        }
      })
      
      this.btnLoading = true
      this.$api.updateSort(this.dataList).then(response => {
        this.visible = false
        this.btnLoading = false
        this.$message.success('操作成功')
        this.queryInvalidFields(1)
      }).catch(error => {
        this.btnLoading = false
      })
    }
  }
}
</script>

<style lang="scss">
.project-table-field {
  text-align: center;
  .transfer {
    .el-transfer-panel__item{
      margin-right:0
    }
    text-align: left;
    display: inline-block;
  }
  .el-transfer-panel__body {
    height: 400px;
  }
  .el-transfer-panel__list.is-filterable {
    height: 350px;
  }
  .transfer-footer {
    margin: 5px;
  }
}
</style>