<template>
<div class="query-list">
  <!--顶部查询区域-->
  <el-row class="query-list__query">
    <div class="query__form">
      <el-select v-model="condition" @change="conditionChange">
        <template v-for="item in conditions">
          <el-option
            v-if="item.display"
            :key="item.name"
            :label="item.title"
            :value="item.name"
          ></el-option>
        </template>
      </el-select>
      <el-input
        class="query-item"
        v-model="inputQuery[condition]"
        :disabled="disableInput"
        @keyup.enter.native="toGetList"
      ></el-input>
    </div>
    <div>
      <el-button type="primary" @click="toGetList">查询</el-button>
      <el-button type="primary" @click="toReset">重置</el-button>
    </div>
  </el-row>

  <!--查询结果-->
  <div class="query-list__operation">
    <!--左侧已选区域-->
    <div v-if="!single" class="operation__selected">
      <el-table
        ref="left-table"
        height="400"
        :data="selectedList"
        stripe
        @selection-change="selectedChange"
        @row-click="row => toCheck(row, 'left-table')"
      >
        <el-table-column type="selection" fixed align="center"></el-table-column>
        <el-table-column label="已选" :prop="config.textField"></el-table-column>
      </el-table>
    </div>

    <!--穿梭按钮-->
    <div v-if="!single" class="operation__btn">
      <!--<div><el-button icon="el-icon-arrow-left" type="success" circle @click="select"></el-button></div>-->
      <div><el-button icon="el-icon-arrow-right" type="warning" circle @click="unSelect"></el-button></div>
    </div>

    <!--右侧结果列表-->
    <div class="operation__list" :class="single ? 'operation__list--single' : ''">
      <el-table
        ref="right-table"
        height="400"
        :data="resultList"
        stripe
        border
        @selection-change="selectingChange"
        @row-click="row => toCheck(row, 'right-table')"
      >
        <el-table-column v-if="!single" type="selection"></el-table-column>
        <el-table-column v-else>
          <template slot-scope="scope">
            <el-radio v-model="radio" :label="scope.row.rownum">{{ }}</el-radio>
          </template>
        </el-table-column>
        <!--动态表头-->
        <template v-for="(item, index) in config.columns">
          <!--特殊情况-->
          <!--库位 使用类型 字段-->
          <template v-if="item.field === 'locUseType'">
            <el-table-column :label="item.title" :key="index" :prop="item.field">
              <template slot-scope="scope">
                <span>{{ $utils.keyMatcher(scope.row.locUseType, $keys.warehouseBasic.locUseType).name || '-' }}</span>
              </template>
            </el-table-column>
          </template>
          <!--库位 使用类型 字段-->
          <template v-else-if="item.field === 'status'">
            <el-table-column :label="item.title" :key="index" :prop="item.field">
              <template slot-scope="scope">
                <span>{{ $utils.keyMatcher(scope.row.status, $keys.warehouseBasic.status).name || '-' }}</span>
              </template>
            </el-table-column>
          </template>
          <template v-else>
            <table-column
              :key="index"
              :label="item.title"
              :prop="item.field"
              :formatter="formatColumn"
            ></table-column>
          </template>
        </template>
      </el-table>

      <!--分页-->
      <el-pagination
        class="pagination"
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page="currentNo"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="prev, pager, next, ->, total, sizes, jumper"
        :total="total"
      ></el-pagination>
    </div>
  </div>

  <!--底部提交按钮-->
  <div class="query-list__submit">
    <el-button type="primary" @click="confirm">确定</el-button>
    <el-button type="primary" @click="close">关闭</el-button>
  </div>
</div>
</template>

<script>
export default {
  name: 'QueryList',
  props: {
    selected: [Array, Object],
    baseUrl: String,
    cfgKey: String,
    // 是否为单选状态, 默认是查询模式为多选, 新增时传single为单选
    single: {
      type: Boolean,
      default: false,
    },
    queryParams: Object, // 父组件传查询参数
    disabledQueryParams: Object, // 禁用的查询参数
    queryUrl: String, // 个性请求接口
  },
  watch: {
    selected (val) {
      this.selectedList = val
    },
    queryParams (val) {
      this.resultList = [] // 有传参的情况下, 清空右侧列表重新请求
      this.getConfig()
    }
  },
  created () {
  },
  mounted () {
    this.getConfig()
  },

  data () {
    return {
      radio: '', // 单选值
      config: {}, // 配置
      conditions: [], // 查询条件列表
      condition: 'ALL', // 初始默认查询条件
      selectedList: [], // 左侧已选列表
      resultList: [], // 右侧结果列表
      // 分页变量
      currentNo: 1,
      pageSize: 10,
      total: 0,
      // 基础查询
      baseQuery: {
        'page.currentPage': 1,
        'page.limitCount': 10,
        queryType: this.cfgKey,
      },
      inputQuery: { ...this.disabledQueryParams }, // 视图层输入的查询条件
      query: {}, // 逻辑层输入的查询条件
      disableInput: false, // 禁用输入框
    }
  },
  methods: {
    // 获取配置
    getConfig () {
      const url = `${this.baseUrl}/popWinController/getConfig.shtml?cfgKey=${this.cfgKey}`
      const param = {}
      this.$https.post(url, param)
        .then(data => {
          this.config = data
          this.getList()
        })
        .then(() => {
          const tempArr = this.config.conditions.slice()
          tempArr.unshift({
            display: true,
            name: 'ALL',
            title: '全部',
          })
          this.conditions = tempArr
        })
    },
    // 条件变化
    conditionChange (condition) {
      // eslint-disable-next-line
      this.disableInput = this.disabledQueryParams[condition] != undefined // 可能是 null, 可能是 undefined
      this.inputQuery = { ...this.disabledQueryParams }
    },
    // 查询按钮
    toGetList () {
      // 复制副本, 防止更改视图层
      const copy = { ...this.inputQuery }
      if (this.condition === 'ALL') {
        // 为全部时, 为所有条件赋值, ##API: 当存在 disabledQueryParams 时, all查询失效, 接口问题!
        for (const item of this.config.conditions) {
          copy[item.name] = this.inputQuery.ALL || ''
        }
      }
      delete copy.ALL // 删除"全部"的属性
      Object.entries(copy).map(item => {
        // 为存在的变量加入%%支持模糊查询
        (item[1] !== undefined) && (copy[item[0]] = `%${item[1]}%`)
      })
      // 副本进入逻辑层变量
      this.query = copy
      this.getList()
    },
    // 获取结果列表
    getList () {
      const url = this.queryUrl || `${this.baseUrl}/popWinController/query.shtml?cfgKey=${this.cfgKey}`
      const param = {
        ...this.baseQuery, // 基础查询条件
        ...this.query, // 输入的查询条件
        ...this.queryParams, // 传入的非视图层查询条件
        ...this.disabledQueryParams, // 传入的视图层不可变更的查询条件
      }
      const config = (this.queryUrl && this.queryUrl.includes('outboundShippmentService/queryWmsCustomer')) ? {
        // 特殊查询 url 处理
        headers: { 'Content-Type': 'application/json' },
        transformRequest: [],
      } : {}
      this.$https.post(url, param, config)
        .then(data => {
          this.total = data.total
          this.resultList = data.rows
        })
    },
    // 重置按钮
    toReset () {
      this.reset()
      this.getList()
    },
    // 重置
    reset () {
      this.inputQuery = {}
      this.query = {}
    },
    // 点击表格行
    toCheck (row, refName) {
      if (this.single) {
        // 单选状态
        this.radio = row.rownum
        this.cacheRadioRow = row
      } else {
        // 默认多选状态
        this.$refs[refName].toggleRowSelection(row)
      }
    },
    // 页码变化
    currentChange (currentNo) {
      this.currentNo = currentNo
      this.baseQuery['page.currentPage'] = currentNo
      this.getList()
    },
    // 每页条数变化
    sizeChange (pageSize) {
      this.pageSize = pageSize
      this.baseQuery['page.limitCount'] = pageSize
      this.getList()
    },
    // 左侧已选变化
    selectedChange (selected) {
      this.cacheUnSelected = new Set(selected.map(item => item[this.config.textField])) // 保存待反选集合
    },
    // 右侧列表选择变化
    selectingChange (selecting) {
      this.cacheSelected = selecting // 临时保存选中数组
      const tempArr = this.cacheSelected.filter(item => {
        // 校验不能重复赋值
        return this.selectedList.every(selected => selected[this.config.textField] !== item[this.config.textField])
      })
      this.selectedList = [ ...this.selectedList, ...tempArr ]
    },
    // ##弃用, 向左穿梭 - 选中
    // select () {
    //   const tempArr = this.cacheSelected.filter(item => {
    //     // 校验不能重复赋值
    //     return this.selectedList.every(selected => selected[this.config.textField] !== item[this.config.textField])
    //   })
    //   this.selectedList = [ ...this.selectedList, ...tempArr ]
    // },
    // 向右穿梭 - 反选
    unSelect () {
      this.selectedList = this.selectedList.filter(item => !this.cacheUnSelected.has(item[this.config.textField])) // 利用Set去重
    },
    // 确定
    confirm () {
      const detail = {
        config: this.config,
        selected: this.single ? this.cacheRadioRow : this.selectedList
      }
      this.$emit('confirm', detail)
      this.init()
    },
    // 关闭
    close () {
      this.$emit('close')
      this.init()
    },
    // 初始化
    init () {
      this.selectedList = []
      this.reset()
    }
  },
}
</script>

<style lang="scss" scoped>
.query-list {
  &__query {
    /*display: flex;*/
    /*justify-content: space-between;*/
    margin-bottom: 10px;
    div:first-child {
      float: left;
      .el-input {
        max-width: 180px;
      }
    }
    div:last-child {
      float: right;
    }
    .query__form {
      .query-item {
        margin-left: 10px;
      }
    }
  }
  &__operation {
    > div {
      display: inline-block;
      max-height: 400px;
      vertical-align: middle;
    }
    .operation__selected {
      width: 30%;
    }
    .operation__btn {
      text-align: center;
      width: 10%;
      > div:first-child {
        margin-bottom: 20px;
      }
    }
    .operation__list {
      width: 60%;
      .el-pagination {
        /*可深层改变element样式*/
        /deep/
        .el-pagination__rightwrapper {
          margin-left: 10px;
          float: initial;
        }
      }
      &--single {
        width: 100%;
        .el-pagination {
          /*可深层改变element样式*/
          /deep/
          .el-pagination__rightwrapper {
            float: right;
          }
        }
      }
    }

    .el-table {
      border: 1px solid #eee;
    }
  }
  &__submit {
    margin-top: 50px;
  }
}
</style>
