<template>
  <div>
    <template>
      <vxe-modal title="回收站" :close-on-click-modal="false" v-model="visible" lock-scroll transfer width="70%" height="70%">
        <vxe-grid
          :size="'mini'"
          ref="xGrid"
          height="560"
          :keep-source="true"
          resizable
          align="left"
          showHeaderOverflow
          showOverflow
          :row-config="{ isCurrent: true, isHover: true }"
          :columns="formConfig"
          :column-config="{ minWidth: 100 }"
          :data="tableData"
          :loading="listLoading"
          :showFooter="false"
          :printConfig="{}"
          :merge-cells="mergeCells"
          @checkbox-change="handleSelectionChange"
          @checkbox-all="handleSelectionChange"
        >
          <template #seq="{ row, column, rowIndex }">
            {{ rowIndex + 1 }}
          </template>
          <template #operate="scope">
            <template>
              <el-button type="text" size="small" @click="recycleClick(scope.row)">恢复</el-button>
            </template>
          </template>
          <!--          <template v-slot:pager>-->
          <!--            <vxe-pager-->
          <!--              v-if="columnData.hasPage"-->
          <!--              background-->
          <!--              border-->
          <!--              :layouts="['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"-->
          <!--              :current-page.sync="listQuery.currentPage"-->
          <!--              :page-size.sync="listQuery.pageSize"-->
          <!--              :total="total"-->
          <!--              :page-sizes="[5, 10, 20, 50, 100, 500]"-->
          <!--              @page-change="refreshTableLayout"-->
          <!--            >-->
          <!--            </vxe-pager>-->
          <!--          </template>-->
        </vxe-grid>
        <!--        <el-table v-loading="listLoading" :data="tableData" border :height="550"-->
        <!--                  @selection-change="handleSelectionChange"-->
        <!--                   style="width: 100%;">-->
        <!--          <el-table-column-->
        <!--            type="selection"-->
        <!--            width="55" fixed>-->
        <!--          </el-table-column>-->
        <!--          <el-table-column label="序号" align="center" width="50" fixed>-->
        <!--            <template slot-scope="scope">-->
        <!--              {{(scope.$index + 1) + size * (current - 1 ) }}-->
        <!--            </template>-->
        <!--          </el-table-column>-->
        <!--          <el-table-column prop="operator" label="操作人" align="center" fixed></el-table-column>-->
        <!--          <el-table-column prop="createTime" label="删除时间" align="center" fixed></el-table-column>-->
        <!--          <template v-for="(item,index) in config" >-->
        <!--            <el-table-column :label="item.label"  align="center">-->
        <!--              <template slot-scope="scope">-->
        <!--                &lt;!&ndash;                如果有值&ndash;&gt;-->
        <!--                <div v-if="editCurrentClick(scope.row,item)">-->
        <!--                  &lt;!&ndash;                  判断类型&ndash;&gt;-->
        <!--                  <div v-if="item.jnpfKey === 'numInput'">-->
        <!--                    {{ editCurrentClick(scope.row,item) === 0 ? '0' : editCurrentClick(scope.row,item) }}-->
        <!--                  </div>-->
        <!--                  <div v-else-if="item.jnpfKey === 'uploadImg' || item.jnpfKey === 'uploadFz'">-->
        <!--                    <template v-if="item.jnpfKey === 'uploadFz'">-->
        <!--                      <span style="color: #1890ff" v-for="(i,k) in getImgFun(editCurrentClick(scope.row,item))" :key="k">{{i.name}}</span>-->
        <!--                    </template>-->
        <!--                    <template v-if="item.jnpfKey === 'uploadImg'">-->
        <!--                      <template v-for="(imgEle,imgKey) in getImgFun(editCurrentClick(scope.row,item))">-->
        <!--                        <el-image v-if="imgKey < 3" :key="imgKey"-->
        <!--                                  style="width: 50px; height: 50px;margin-right: 10px"-->
        <!--                                  :src="getImgUrl() + imgEle.url" >-->
        <!--                        </el-image>-->
        <!--                      </template>-->
        <!--                      <el-tag style="vertical-align: text-bottom" v-if="getImgFun(editCurrentClick(scope.row,item)).length > 3" type="info"> + {{getImgFun(editCurrentClick(scope.row,item)).length - 3}}</el-tag>-->
        <!--                    </template>-->
        <!--                  </div>-->
        <!--                  <div  v-else-if="item.jnpfKey === 'radio' || item.jnpfKey === 'select' || item.jnpfKey === 'checkbox'">-->
        <!--                    {{getOptionData(editCurrentClick(scope.row,item),item.propId)}}-->
        <!--                  </div>-->
        <!--                  <div v-else-if="item.jnpfKey === 'date' || item.jnpfKey === 'datetime'">-->
        <!--                    {{getSetData(editCurrentClick(scope.row,item),item.propId,'format')}}-->
        <!--                  </div>-->
        <!--                  <div v-else>-->
        <!--                    {{ editCurrentClick(scope.row,item) }}-->
        <!--                  </div>-->
        <!--                </div>-->
        <!--              </template>-->
        <!--            </el-table-column>-->
        <!--          </template>-->
        <!--          <el-table-column  label="操作" align="center" width="100" fixed="right">-->
        <!--            <template slot-scope="scope">-->
        <!--              <el-button type="text" size="small" @click="recycleCurrentClick(scope.row)">详情</el-button>-->
        <!--              <el-button type="text" size="small" @click="recycleClick(scope.row)">恢复</el-button>-->
        <!--            </template>-->
        <!--          </el-table-column>-->
        <!--        </el-table>-->
        <div style="margin-top: 9px; float: left">
          <el-button type="primary" size="mini" @click="toggleSelection()">批量恢复</el-button>
          <el-button v-if="assemblyOptions.includes('comDelete')" type="primary" size="mini" @click="toggleSelectionDelete()">彻底删除</el-button>
        </div>
        <template>
          <pagination :total="total" :page.sync="current" :limit.sync="size" @pagination="init()" />
        </template>
        <el-dialog class="JNPF-dialog JNPF-dialog_center" title="详细信息" :visible.sync="innerVisible" append-to-body>
          <el-table :data="innerData" border :height="500" style="width: 100%">
            <template v-for="(item, index) in innerList">
              <el-table-column v-if="item.value" :label="item.label" align="center">
                <template slot-scope="scope">
                  {{ item.value }}
                </template>
              </el-table-column>
            </template>
          </el-table>
        </el-dialog>
      </vxe-modal>
    </template>
  </div>
</template>

<script>
import { recycleModelDelete, recycleModelList, recycleModelrecovery } from '@/api/onlineDev/visualDev'
import moment from 'moment/moment'
export default {
  name: 'recycleList',
  props: ['modelId', 'assemblyOptions', 'config', 'formData'],
  data() {
    return {
      visible: false,
      innerVisible: false,
      listLoading: false,
      tableData: [],
      current: 1,
      size: 10,
      total: 0,
      SelectionList: [],
      innerData: [],
      innerList: [],
      mergeCells: [],
      formConfig: [...this.config, { field: 'operator', title: '操作人' }, { field: 'createTime', title: '操作时间' }]
    }
  },
  methods: {
    //初始化数据
    init() {
      this.visible = true
      this.listLoading = true
      let parmes = {
        current: this.current,
        size: this.size,
        modelId: this.modelId
      }
      recycleModelList(parmes).then((res) => {
        this.tableData = res.data.data.records
        this.getDataList(this.tableData)
        this.total = 1
        this.listLoading = false
      })
    },
    // 组装数据
    getDataList(data) {
      data.forEach((item, index) => {
        item.seq = index + 1
      })
      this.mergeCells = []
      let list = []
      const columnListTable = g.T.toTable(this.formConfig, 'children').filter((i) => i.jnpfKey !== 'table')
      let dataView = data && data.length ? JSON.parse(data[0].dataView) : []
      const foreignKeys = Object.keys(dataView).filter((key) => key.startsWith('FOREIGN_KEY_'))
      list = data.map((v, index) => {
        let records = JSON.parse(v.dataView)
        const mergedPageData = []
        let defaultData = { operator: v.operator, createTime: v.createTime, id: v.id, seq: v.seq }
        if (foreignKeys.length > 0) {
          const foreignKeysLength = []
          for (let foreignKey of foreignKeys) {
            if (records[foreignKey] && records[foreignKey].pageData) {
              foreignKeysLength.push(records[foreignKey].pageData.length)
            }
          }
          if (foreignKeysLength.length === 0) {
            mergedPageData.push({ records, ...defaultData })
          } else {
            const numItems = Math.max(...foreignKeysLength)
            for (let i = 0; i < numItems; i++) {
              let mergedItem = {}
              // 循环合并在此索引位置的所有FOREIGN_KEY的pageData对象
              for (let foreignKey of foreignKeys) {
                if (records[foreignKey].pageData && records[foreignKey].pageData[i]) {
                  mergedItem = { ...mergedItem, ...records[foreignKey].pageData[i] }
                }
              }
              // 添加合并后的对象到结果数组
              mergedPageData.push({ ...records, ...mergedItem, ...{ mergeRow: numItems, row: index }, ...defaultData })
            }
          }
        } else {
          let z = Object.assign({}, records, defaultData)
          mergedPageData.push(z)
        }
        return mergedPageData
      })
      let num = 0
      const newList = list.flat()
      // if (this.oldList.length === 0) {
      //   this.oldList = g.Copy(newList)
      // }
      let fields = {}
      this.config.forEach((i, index) => {
        if (i.children && i.children.length < 1) {
          fields[i.field] = columnListTable.findIndex((o) => o.field === i.field)
        }
      })
      list
        .filter((v) => v)
        .forEach((item) => {
          item.forEach((i, index) => {
            for (const iKey in i) {
              if (fields[iKey]) {
                this.mergeCells.push({
                  row: num,
                  col: fields[iKey],
                  rowspan: i.mergeRow,
                  colspan: 1
                })
              }
            }
            this.mergeCells.push({
              row: num,
              col: columnListTable.findIndex((o) => o.type === 'checkbox'),
              rowspan: i.mergeRow,
              colspan: 1
            })
            this.mergeCells.push({
              row: num,
              col: columnListTable.findIndex((o) => o.field === 'operator'),
              rowspan: i.mergeRow,
              colspan: 1
            })
            this.mergeCells.push({
              row: num,
              col: columnListTable.findIndex((o) => o.field === 'createTime'),
              rowspan: i.mergeRow,
              colspan: 1
            })
            this.mergeCells.push({
              row: num,
              col: columnListTable.findIndex((o) => o.title === '序号'),
              rowspan: i.mergeRow,
              colspan: 1
            })
            // 操作列合并
            this.mergeCells.push({
              row: num,
              col: columnListTable.findIndex((o) => o.title === '操作'),
              rowspan: i.mergeRow,
              colspan: 1
            })
          })
          num += item.length
        })
      // 数组拍平
      this.tableData = newList
    },
    //多选
    handleSelectionChange({ records }) {
      if (records && records.length) {
        this.SelectionList = records.map((i) => {
          return i.id
        })
      } else {
        this.SelectionList = []
      }
    },
    //批量恢复
    toggleSelection() {
      if (!this.SelectionList.length) return this.$message({ message: '至少选择一条数据', type: 'warning' })

      recycleModelrecovery(this.SelectionList).then((res) => {
        if (res.data.code === 200) {
          this.$message({ message: '恢复成功', type: 'success' })
          this.init()
          this.$emit('recycleDataList')
        }
      })
    },
    toggleSelectionDelete() {
      if (!this.SelectionList.length) return this.$message({ message: '至少选择一条数据', type: 'warning' })

      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          recycleModelDelete(this.SelectionList).then((res) => {
            if (res.data.code === 200) {
              this.$message({ message: '操作成功', type: 'success' })
              this.init()
            }
          })
        })
        .catch(() => {})
    },
    //恢复
    recycleClick(row) {
      recycleModelrecovery([row.id]).then((res) => {
        if (res.data.code === 200) {
          this.$message({ message: '恢复成功', type: 'success' })
          this.init()
          this.$emit('recycleDataList')
        }
      })
    },
    //行点击事件
    recycleCurrentClick(val) {
      this.innerData = []
      if (val.dataView) {
        try {
          const toObj = JSON.parse(val.dataView)
          if (Array.isArray(toObj) && toObj.length) {
            this.innerList = toObj
            this.innerData.unshift({})
            this.innerVisible = true
          }
        } catch {
          if (Array.isArray(val.dataView) && val.dataView.length) {
            this.innerData.unshift({})
            this.innerList = val.dataView
          }
        }
      }
    },
    //行点击事件
    editCurrentClick(val, row) {
      if (val.dataView) {
        try {
          const toObj = JSON.parse(val.dataView)
          if (Array.isArray(toObj) && toObj.length) {
            let aa = toObj.find((o) => o.fieldId === row.propId)
            return aa.value
          }
        } catch {
          if (Array.isArray(val.dataView) && val.dataView.length) {
            let aa = val.dataView.find((o) => o.fieldId === row.propId)
            return aa.value
          }
        }
      }
    },
    //下拉属性的组件  如果key和value值不相同 查询title
    getOptionData(v, id) {
      let list = []
      let str = v
      this.formData.fields.forEach((item) => {
        if (item.__vModel__ === id) {
          list = item.__slot__.options
        }
      })
      if (list.length) {
        let obj = list.find((i) => i.id == v)
        if (obj) str = obj.fullName
      }
      return str
    },
    //图片类型处理
    getImgFun(value) {
      try {
        const toObj = JSON.parse(value)
        if (Array.isArray(toObj) && toObj[0].url) {
          return toObj
        }
      } catch {}
      return value
    },
    getImgUrl() {
      let ImgUrl
      if (process.env.NODE_ENV === 'development') {
        ImgUrl = this.define.comUrl
      } else {
        ImgUrl = document.location.origin
      }
      return ImgUrl + '/'
    },
    getSetData(val, propId, type) {
      let str = this.getFormat(propId, type)
      if (str === 'yyyy-MM-dd') {
        str = 'yyyy-MM-DD'
      } else if (str === 'yyyy-MM-dd HH:mm:ss') {
        str = 'yyyy-MM-DD HH:mm:ss'
      }
      return moment(val).format(str)
    },
    //获取时间值类型
    getFormat(id, type) {
      let str
      this.formData.fields.forEach((item) => {
        if (item.__vModel__ === id) {
          if (type === 'format') {
            str = item.format
          }
        }
      })
      return str
    }
  }
}
</script>

<style lang="scss" scoped>
.JNPF-dialog_center {
  >>> .el-dialog__body {
    padding: 20px !important;
  }
}
::v-deep .el-table {
  .el-table__fixed {
    // 左固定列
    height: auto !important;
    bottom: 18px; // 改为自动高度后，设置与父容器的底部距离，高度会动态改变，值可以设置比滚动条的高度稍微大一些
  }
  .el-table__fixed-right {
    // 右固定列
    height: auto !important;
    bottom: 18px; // 改为自动高度后，设置与父容器的底部距离，高度会动态改变，值可以设置比滚动条的高度稍微大一些
  }
}
</style>
