<!--
  * @File 选择
  * configure 需要设置的一些属性 isSearch:是否需要搜索  isChoice:是否多选(如果不需要选择 可以使用插槽 或者再配置列数据中 不配置action)
              iWidth:弹框的宽度   isReset: 是否需要重置按钮   isPagination:是否需要分页 isGetChoseItem: 多选是否返回整列数据
              isHideFilterColumns:是否隐藏列的过滤器
              objPagination:{size: 'page_size',index: 'page_index',}  分页需要的配置
              span:栅格
              getFunction:列表获取函数
              dataIndexId: dataIndex ID
              isManualGet: 是否为手动获取列表数据
    searchList  需要搜索的内容
            name: lable名称
            placeholder：提示语
            field：字段
            type：类型
              [text 文本] [select 下拉框]  [timeDate 按照天的日历]  [timeMonth 按照月的日历]  [timeWeek  按照周的日历]  [timeRange 时间段的日历]
              [radio:单选] [checkbox:多选] [cascader 级联选择器]
            style:样式
            content:下拉框，单选框，复选框的内容(包含name id value)
            format:日历格式
            icon：日历的小图标
            disabledDate:当天之前是否可以选（true 不可选，false 可选
            setValue函数：用于时间段的日历
            isMerge：返回时间的格式  在类型为timeRange(时间段的日历)时使用
                    true返回格式 starTime: '2020-01-01'  endTime: '2020-01-02'
                    false返回格式  time: ['2020-01-01', '2020-01-02']
    columns： 表头
      isLeaveFilter 是否从过滤列表内去除 (默认去除最后一列)
      isHideFilterFiled 是否初始隐藏该字段
      isShowName 增加可多列拼接功能

  * @slot columns相关插槽 根据columns列设置中 scopedSlots customRender进行生成插槽 可以同步在组件列表内部进行操作
      selectCallBtn 多选时候使用 底部按钮插槽 用于替换提交多选结果
  * 后续拓展升级方向:
      1：增加默认删除 排序（接口） 新增 修改 详情（页面跳转 弹窗 以及动态编辑功能）
      2: 增加树结构列表 （显示 操作 单选 多选 排序）
  * @Author 张苗苗
  * @Date 2021-10-25
  * @Update 佟春晓(2022-06-06)
-->
<template>
  <div>
    <div>
      <Search :configure="configure" :searchList="searchList" @serchData="serchData" @getList="getList"></Search>
      <slot name="button"></slot>
      <a-card title="已选择" v-if="configure.isChoice && choseNames.length > 0" style="margin: 10px 0 10px 0">
        <div class="approver-tag">
          <a-tag color="blue" v-for="(item,index) of choseNames" :key="index" closable @close="closeTag(index,$event)">
            {{ item }}
          </a-tag>
        </div>
      </a-card>
      <a-table
        :rowKey="configure.dataIndexId || 'id'"
        :loading="loading"
        :columns="showColumns"
        :data-source="listData"
        :pagination="configure.isPagination == true ? pagination : false"
        :rowSelection="configure.isChoice == true ? rowSelection : null"
        :rowClassName="configure.isRowClassName == true ? setRowClass : setRowClassNull"
        @change="handleTableChange"
      >
        <!-- 表单头部-显示与隐藏 -->
        <!-- 当前插槽可获取数据 slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }" -->
        <div
          slot="filterDropdown"
          style="padding: 8px"
          class="filterDropdown"
          v-if="true"
        >
          <div class="flex-row space-between" v-for="(item, index) in listColumns" :key="index" >
            <template v-if='!item.isLeaveFilter'>
              <span>{{ item.title }}</span><a-switch default-checked @change="onTitleChange($event, index)" />
            </template>
          </div>
        </div>
        <span v-for='(item, i) of listScopedSlots' :key='i' :slot="item.customRender" slot-scope="text, record, index">
          <!-- 如果开启单选 默认显示选择按钮 也可替换单选按钮-->
          <template v-if="!configure.isChoice">
            <slot :name='item.customRender' :text='text' :index='index' :record='record'><a @click="choice(record)">选择</a></slot>
          </template>
          <!-- 如果设置synosis 默认显示解析文本-->
          <template v-else-if="item.customRender === 'synosis'">
            <slot :name='item.customRender' :text='text' :index='index' :record='record'><div v-html="record.description"></div></slot>
          </template>
          <!-- 如果直接使用 则默认成为替换插槽-->
          <template v-else-if="configure.isChoice">
            <slot :name='item.customRender' :text='text' :index='index' :record='record'></slot>
          </template>
        </span>
      </a-table>
    </div>
    <div class="approver-btn" @click="selectCall" v-if="configure.isChoice">
      <slot name='selectCallBtn'>
        <a-button type="primary">设置完成</a-button>
      </slot>
    </div>
  </div>
</template>

<script>
import Search from './Search.vue'
import { Empty } from 'ant-design-vue'
export default {
  name: 'ListTable',
  components: { Search },
  props: {
    // 需要设置的一些属性 isSearch:是否需要搜索  isChoice:是否多选
    configure: {
      type: Object,
      default: null
    },
    // 需要搜索的内容
    searchList: {
      type: Array,
      default: null
    },
    // 表格表头
    columns: {
      type: Array,
      default: null
    },
    // 分类
    cascaderData: {
      type: Array,
      default: null
    },
    // 回显ids
    arrList: {
      type: Object,
      default: null
    }
  },
  data () {
    return {
      loading: false,
      // 查询参数
      choseId: [],
      choseNames: [],
      choseList: [],
      selectedRowKeys: [],
      form: this.$form.createForm(this),
      // 分页
      pagination: {
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        current: 1,
        defaultPageSize: 10,
        total: 0,
        showSizeChanger: true,
        showTotal: (total, range) => `共 ${total} 条记录`
      },
      field: {},
      // 需要展示的名字
      strName: '',
      // 表格数据
      listData: [],
      // 搜索的数据
      searchData: [],
      listColumns: [],
      showColumns: []
    }
  },
  watch: {
    // 监听赋值对象赋值变化
    tableDataCoby (obj) {
      // 设置返回数据并赋值
      this.listColumns = this.columns
      // 初始化列
      this.setColumns()
      // 其它
      const arrShowName = this.columns.filter(v => v.isShowName)
      if (arrShowName.length === 1) this.strName = arrShowName[0].dataIndex
      if (arrShowName.length > 1) this.strName = arrShowName.map(v => v.dataIndex)
      // 判断是否手动获取列表
      if (!this.configure.isManualGet) this.getList()
    },
    arrList (v) {
      this.choseId = this.arrList ? this.arrList.ids : []
      this.choseNames = this.arrList ? this.arrList.names : []
      if (this.configure.isGetChoseItem) this.choseList = this.arrList ? this.arrList.list : []
    }
  },
  created () {
  },
  mounted () {
    this.listColumns = this.columns
    // 初始化列
    this.setColumns()
    // 其它
    const arrShowName = this.columns.filter(v => v.isShowName)
    if (arrShowName.length === 1) this.strName = arrShowName[0].dataIndex
    if (arrShowName.length > 1) this.strName = arrShowName.map(v => v.dataIndex)
    this.choseId = this.arrList ? this.arrList.ids : []
    this.choseNames = this.arrList ? this.arrList.names : []
    if (this.configure.isGetChoseItem) this.choseList = this.arrList ? this.arrList.list : []
    // 判断是否手动获取列表
    if (!this.configure.isManualGet) this.getList()
  },
  beforeCreate () {
    this.simpleImage = Empty.PRESENTED_IMAGE_SIMPLE
  },
  computed: {
    tableDataCoby () {
      return JSON.parse(JSON.stringify(this.configure))
    },
    rowSelection () {
      return {
        selectedRowKeys: this.choseId,
        onChange: (selectedRowKeys, selectedRows) => {
          var choseNames = []
          var choseId = []
          for (var item of selectedRows) {
            if (typeof this.strName === 'string') {
              choseNames.push(item[this.strName])
            } else {
              let str = ''
              this.strName.forEach(v => {
                str += '-' + item[v]
              })
              str = str.substring(1, str.length)
              choseNames.push(str)
            }
            const id = this.configure.dataIndexId || 'id'
            choseId.push(item[id])
          }
          this.setRowData(choseId, choseNames, selectedRows)
        }
      }
    },
    listScopedSlots () {
      const list = []
      this.columns.forEach(item => {
        if (item.scopedSlots) {
          if (!item.scopedSlots.customRender) {
            console.error(new Error('scopedSlots not fount customRender'))
            return []
          }
          list.push(item.scopedSlots)
        }
      })
      return list
    }
  },
  methods: {
    setRowClassNull () {
      return ''
    },
    setRowClass (record) {
      if (record[this.configure.rowClassName.bigType] > record[this.configure.rowClassName.smallType]) return 'rowClass'
      return ''
    },
    // 初始化列名称
    setColumns () {
      if (!this.configure.isHideFilterColumns) {
        this.listColumns[this.listColumns.length - 1].isLeaveFilter = true
        const columns = this.listColumns.filter(v => !v.isHideFilterFiled)
        columns[columns.length - 1].scopedSlots = {
          ...columns[columns.length - 1].scopedSlots,
          ...{ filterDropdown: 'filterDropdown', filterIcon: 'filterIcon' }
        }
        this.showColumns = columns
      } else {
        this.showColumns = this.listColumns
      }
    },
    // 当函数发生变化时，触发该事件
    onTitleChange (e, i) {
      this.listColumns[i].isHideFilterFiled = !e
      this.setColumns()
    },
    // 分页
    handleTableChange (options) {
      this.pagination.current = options.current
      this.pagination.defaultPageSize = options.pageSize
      this.getList()
    },

    // 设置行选中的值
    setRowDataFunction (choseId, choseNames, choseList, nowChoseId, nowChoseNames, nowChoseList, list) {
      let newChoseId = choseId
      let newChoseNames = choseNames
      let newChoseList = choseList
      list.forEach(item => {
        const indexChose = newChoseId.indexOf(item.id)
        if (indexChose > -1) newChoseId.splice(indexChose, 1)
        if (indexChose > -1) newChoseNames.splice(indexChose, 1)
        if (this.configure.isGetChoseItem) if (indexChose > -1) newChoseList.splice(indexChose, 1)
      })
      newChoseId = [...newChoseId, ...nowChoseId]
      newChoseNames = [...newChoseNames, ...nowChoseNames]
      if (this.configure.isGetChoseItem) newChoseList = [...choseList, ...nowChoseList]
      return { newChoseId: newChoseId, newChoseNames: newChoseNames, newChoseList: newChoseList}
    },
    setRowData (choseId, choseNames, list) {
      const obj = this.setRowDataFunction(this.choseId, this.choseNames, this.choseList, choseId, choseNames, list, this.listData)
      this.choseId = obj.newChoseId
      this.choseNames = obj.newChoseNames
      if (this.configure.isGetChoseItem) this.choseList = obj.newChoseList
    },
    // 关闭标签
    closeTag (index, e) {
      this.choseId.splice(index, 1)
      this.choseNames.splice(index, 1)
      this.choseList.splice(index, 1)
      e.preventDefault()
    },
    // 多选选择回调
    selectCall () {
      const choseValue = {}
      choseValue.ids = this.choseId
      choseValue.names = this.choseNames
      if (this.configure.isGetChoseItem) choseValue.list = this.choseList
      this.$emit('selectCall', choseValue)
    },
    // 单选选择回调
    choice (record) {
      this.$emit('singleCall', record)
    },
    // 搜索
    serchData (values, type) {
      this.searchData = values
      this.pagination.current = 1
      this.getList(type)
    },
    // 获取列表
    getList (type) {
      this.loading = true
      var option = {
        page_index: this.pagination.current,
        page_size: this.pagination.defaultPageSize
      }
      if (this.configure.isPagination) {
        if (!this.configure.objPagination) {
          option[this.configure.objPagination.size] = this.pagination.defaultPageSize
          option[this.configure.objPagination.index] = this.pagination.current
        } else {
          option.page_size = this.pagination.defaultPageSize
          option.page_index = this.pagination.current
        }
      }
      if (this.configure.ginseng) {
        option = { ...option, ...this.configure.ginseng }
      }
      if (type !== 'reset') option = { ...option, ...this.configure.params }
      if (this.searchData instanceof Array) {
         for (var v in this.searchData) {
          if (this.searchData[v]) option[v] = this.searchData[v]
        }
      } else if (typeof this.searchData === 'object') {
         for (var i in this.searchData) {
          if (this.searchData[i]) option[i] = this.searchData[i]
        }
      }
      this.configure.getFunction(option).then(res => {
        this.listData = res.data.data
        this.pagination.total = res.data.length || 0
        if (res.data && res.data.data_count) this.pagination.total = res.data.data_count
        if (res.data && res.data.data && res.data.data.data_count) this.pagination.total = res.data.data_count
        this.loading = false
      }).catch(error => {
        console.log(error)
        this.loading = false
      })
    }
  }
}
</script>
<style lang="scss">
  .rowClass{
    color : red
  }
</style>
<style lang="scss" scoped>
  .filterDropdown {
    >.flex-row {
      padding-bottom: 10px;
      >span {
        min-width: 100px;
        color: #333333;
        font-size: 16px;
        padding-right: 20px;
      }
    }
  }
  .approver-tag{
    max-height: 100px;
    overflow-y: auto;
    &::-webkit-scrollbar {
      /*滚动条整体样式*/
      width: 8px; /*高宽分别对应横竖滚动条的尺寸*/
      height: 1px;
    }
    &::-webkit-scrollbar-thumb {
      /*滚动条里面小方块*/
      border-radius: 10px;
      background: #ececec;
    }
    &::-webkit-scrollbar-track {
      /*滚动条里面轨道*/
      border-radius: 10px;
      background: #f7f9fc;
    }
  }
  .ant-tag-blue{
    border-radius: 10px;
    line-height: 25px;
      margin-bottom: 8px;
  }
</style>
