// 多选框,表格,批量操作的组件
<template>
  <div>
    <div class="portalTableOperates">
      <MutSelect
        v-if="customKeyEnable=='true'"
        :maxLength="maxLength"
        :nowNum="nowNum"
        :selKeysList="selKeysList"
        :allKeys="allKeys"
        :columns="$parent.columns"
        :tblName="tbl"
        @changeColumnsList="changeColumnsList"
        @selKeysNew ="selKeysNew"
      />
        <p style="textAlign:left;margin:-10px;marginLeft:10px;" v-if="$route.name == 'basicInfo'">
          小区总数: {{pagination.total != '' ? pagination.total+'个': '暂无数据'}},&nbsp;&nbsp;&nbsp;
          房屋总面积: {{pagination.totStCnstArea != '0' ? pagination.totStCnstArea+'平方米': '暂无数据'}} ,&nbsp;&nbsp;&nbsp;
          总门牌数: {{pagination.totUnits != '0' ? pagination.totUnits+'幢': '暂无数据'}} ,&nbsp;&nbsp;&nbsp;
          总分户数: {{pagination.totHous != '0' ? pagination.totHous+'户': '暂无数据'}}&nbsp;&nbsp;&nbsp;
        </p>
        <a-table class="portalTable"
          size="small"
          :rowSelection="rowSelection"
          rowKey="id"
          :pagination="pagination"
          :columns="customKeyEnable=='true' ? newColumns: $parent.columns"
          :dataSource="tableData"
          bordered
          >
          <span slot="action" slot-scope="text, record">
            <span class="actionBtn" @click="$parent.toView(record)" v-if="$permission(formatPermission())">查看 </span>
            <a-dropdown :trigger="['click']" v-if="customKeyEnable == 'true' || $route.name=='basicInfo' || $route.name=='propertyInfo' || $route.name=='indCous'">
                <a class="ant-dropdown-link" href="#">| 更多 <a-icon type="down" /></a>
                <a-menu slot="overlay">
                  <a-menu-item key="0" v-if="$route.name == 'basicInfo' || $route.name == 'nonResidents'">
                  <a  @click="$parent.toBul(record)" v-if="$permission('00010103')"> 门牌幢 </a>
                  </a-menu-item>
                  <!-- <a-menu-item key="1" v-if="$route.name == 'basicInfo'">
                  <a @click="$parent.toShebei(record)"> 设施设备 </a>
                  </a-menu-item> -->
                  <a-menu-item key="2" v-if="$route.name == 'indCous'">
                  <a @click="$parent.toMem(record)" v-if="$permission('00010202')"> 成员列表 </a>
                  </a-menu-item>
                  <a-menu-item key="3" v-if="$route.name == 'propertyInfo'&&$permission('00010302')">
                  <a @click="$parent.toList(record.cspId)"> 小区列表 </a>
                  </a-menu-item>
                  <a-menu-item key="4" v-if="customKeyEnable == 'true'">
                    <a @click="showModal(record)"  v-if="$permission('00010104')"> 拓展信息维护</a>
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
          </span>
        </a-table>
        <zdyModal ref="modal" :selectedRowKeys="selectedRowKeys" :searchParams="searchParams" :isSingle="isSingle" :resourceId="resourceId" :tbl="tbl" :extList="extList" :isAll="isAll" @saveSingleKeys="saveSingleKeys" @saveSomeKeys="saveSomeKeys"/>
        <BatchOperation v-if="customKeyEnable== 'true'" @choose="choose" @chooseAll="chooseAll"/>
    </div>
  </div>
</template>

<script>
export default {
  name: 'tableAndMut',
  props: {
    tableData: {
      type: Array
    },
    pagination: {
      type: Object
    },
    tbl: {
      type: String
    },
  },
  data(){
    return {
      formTab: this.$form.createForm(this),
      // form : this.$form.createForm(this),
      nowNum: 0, // 当前已选字段的数量
      newColumns: [], // 开启自定义字段展示的列(根据多选框变化的展示列)
      allKeys: [], // 所有可展示的字段(对象数组,含keyname 和key)
      selKeys: [], // 选中展示字段(含key和keyName)
      selKeysList: [], // 选中展示字段(仅key), 给多选框用
      maxLength: 6, // 最大展示的数量
      customKeyEnable: false, // cookie里存的 是否开启自定义字段
      extList: [], // ext请求到的所有自定义字段列表
      resourceId: '', // 当前小区的id
      selectList: [], // 批量操作小区id数组
      isSingle: true, // 批量还是单个
      isAll: true, // 全量还是已选中
      searchList: [], // 动态渲染的搜索列表
      keyCodeList: [], // 动态搜索的keycode列表
      searchParams: {}, // 搜索的列表
      selectedRowKeys: []
    }
  },
  created () { // 进页面获取数据
    this.customKeyEnable=this.$cookie.get('customKeyEnable')
    if(this.customKeyEnable && this.customKeyEnable == 'true'){
      this.getKeys()
      this.getAllKeys()
      // this.$parent.getList()
    }else {
      this.$parent.getList()
    }
  },
  mounted(){
  },
  computed: {
    rowSelection() {
      const { selectedRowKeys } = this
      return {
        selectedRowKeys,
        onChange: this.onSelectChange,
        onSelection: this.onSelection,
      }
    },
  },
  methods: {
    formatPermission(){
      let permissionNum = null
      switch (this.$route.name) {
      case 'basicInfo':
        permissionNum = '00010101'
        break
      case 'indCous':
        permissionNum = '00010201'
        break
      case 'propertyInfo':
        permissionNum = '00010301'
        break
      case 'cmDivision':
        permissionNum = '00010401'
        break
      case 'managers':
        permissionNum = '00010501'
        break
      case 'feiju':
        permissionNum = '000201'
        break
      case 'neighborhoodCommittees':
        permissionNum = '00010601'
        break
      default:
        break
      }
      return permissionNum
      
    },
    selKeysNew(val) { //重新赋值选中项数组
      this.selKeysList = val
    },
    /**
     * 重新赋值展示的列 和当前选中数
     */
    changeColumnsList(value){
      // 当前已选中数
      this.nowNum = value.length-1
      // 重新赋值给展示的列  newColumns
      this.newColumns = value
      // 存入cookie
      this.$com.saveColumnsCookie(this.tbl, this.selKeysList, this.allKeys)
    },

    onSelectChange(selectedRowKeys) { // 被勾选的数据
      this.selectedRowKeys = selectedRowKeys
    },

    getKeys(){ // 获取可显示全部表格字段 和 maxlength
      this.$ajax.get({
        url: this.$api.GET_KEYS.replace('{table}', this.tbl),
      }).then(res => {
        if (res.code == 200) {
          this.maxLength = !!this.$com.confirm(res, 'data.content.maxLength', []) ? this.$com.confirm(res, 'data.content.maxLength', []) : this.maxLength
          this.allKeys = this.$com.confirm(res, 'data.content.allKeys', []) // 全部字段存入allkeys
          // 优先获取本地已选字段,没有则取allkeys里面的
          this.selKeys = this.$cookie.get(this.tbl) ? JSON.parse(this.$cookie.get(this.tbl)) : this.allKeys.slice(0, this.maxLength)

          // 判断本地的已选字段是否在全部字段当中,被删除的自定义字段会被删除 (处理可能被删除的自定义字段)
          const newArr= []
          this.selKeys.forEach(col => {
            this.allKeys.forEach(item => {
              if (col.key == item.key) {
                newArr.push(col)
                return
              }
            })
          })
          // 重新赋值已选中字段 (处理可能被删除的自定义字段)
          this.selKeys = newArr
          // 此时得到了allkeys和selkeys (带key 和 keyName)  需要变成 只有key的数组(多选框要用)
          this.selKeys.forEach(col => {
            this.selKeysList.push(col.key)
          })
          // 已选中的数根据selkeys的长度实时展示
          this.nowNum = this.selKeys.length
          // 1.根据allkeys重写全部的列
          this.$parent.columns = []
          this.allKeys.forEach(col => {
            if(col.key.indexOf('&') != -1){ // 如果有& 就取xx.xx
              this.$parent.columns.push( {
                title: col.keyName,
                dataIndex: col.key.split('&')[0] +'.'+ col.key.split('&')[1],
                key: col.key.split('&')[0] +'.'+ col.key.split('&')[1]
              }, )
            }else{
              this.$parent.columns.push( {
                title: col.keyName,
                dataIndex: col.key,
                key: col.key
              }, )
            }
          })

          // 2.根据selkeys重写选中的列
          this.newColumns = []
          this.selKeys.forEach(col => {
            if(col.key.indexOf('&') != -1){ // 如果有& 就取xx.xx
              this.newColumns.push( {
                title: col.keyName,
                dataIndex: col.key.split('&')[0] +'.'+ col.key.split('&')[1],
                key: col.key.split('&')[0] +'.'+ col.key.split('&')[1]
              }, )

            }else{
              this.newColumns.push( {
                title: col.keyName,
                dataIndex: col.key,
                key: col.key
              }, )
            }
          })
          // 增加 操作
          this.newColumns.push({
            title: '操作',
            dataIndex: 'action',
            width: 160,
            scopedSlots: {
              customRender: 'action'
            }
          })
          this.newColumns.forEach(col => {
            if(col.key == 'addrFrst'){
              col.width = '30%'
            }
          })
        }
      })
    },
    showModal(row) { //展开模态框
      this.resourceId = row.id
      this.isAll = false
      this.isSingle = true
      this.getExtKey(row)
    },
    async getExtKey(row){
      //  处理过的返回数值
      await this.$ajax.get({
        url: this.$api.GET_SAFE_EXT.replace('{table}', this.tbl).replace('{id}', row.id),
      }).then(res => {
        if (res.code == 200) {
          this.extList = this.$com.confirm(res, 'data.content', [])

          this.$refs.modal.isShow = true
        }
      })
      this.$refs.modal.seeData()
    },
    async getAllKeys(){ // 获取当前列表下所有的自定义字段
      await this.$ajax.get({
        url: this.$api.GET_TBLS_KEYS,
        params: {
          tbl: this.tbl,
          pageSize: 10000
        }
      }).then(res => {
        if (res.code == 200) {
          this.searchList = []
          this.extList = this.$com.confirm(res, 'data.content', [])
          this.extList.forEach(col => { // 遍历所有字段拿到 支持搜索的所有字段
            if (col.canSearch==true) {
              if (col.compntType == 'checkbox' || col.compntType == 'radio'||col.compntType == 'date'||col.compntType == 'select') {
              } else {
                col.keyCode = col.keyCode+ '_l'
              }
              this.searchList.push(col)
            }
          })
          this.keyCodeList =[]
          this.searchList.forEach(col => { // 支持搜索的字段遍历,取出keyCode
            this.keyCodeList.push(col.keyCode)
          })
          this.$parent.searchList = this.searchList
          this.$parent.keyCodeList = this.keyCodeList
        }
      })
    },
    saveSingleKeys(params){ // post保存一条自定义数据
      this.$ajax.post({
        url: this.$api.POST_EXT,
        params: params,
      }).then(() => {
        this.$parent.getList()
        this.$refs.modal.isShow = false
        this.$refs.modal.formExt.resetFields()
      })
    },
    saveSomeKeys(params){ // 批量post保存自定义
      this.$ajax.post({
        url: this.$api.POST_EXT_BATCH,
        params: params,
      }).then(res => {
        if (res.code== '200') {
          this.$refs.modal.formExt.resetFields()
          this.$parent.getList()
          this.$refs.modal.isShow = false
        }
      })
    },
    chooseAll(){
      this.isAll = true
      this.isSingle = false
      this.$refs.modal.isShow = true
      this.$refs.modal.seeData() // 打开弹窗恢复默认的选项
    },
    choose(){
      this.isAll = false
      this.isSingle = false
      if (this.selectedRowKeys.length <1) {
        this.$message.error('请勾选至少一条数据')
      }else{
        this.$refs.modal.isShow = true
      }
      this.$refs.modal.seeData() // 打开弹窗恢复默认的选项
    },
  },
}
</script>

<style>

</style>
