<!--文件上传-->
<template>
  <div class="btn-flex" v-if="data.tableHeader && data.tableHeader.length > 0">
    <div class="btn-group" v-for="(item, index) in data.tableHeader" :key="index">
      <span v-if="item.style_self == 'btn'" :class="!item.color ? 'span_color_n' : ''" @click="comBtnClick(item)">{{
        item.name
      }}</span>
      <span v-if="item.style_self == 'btn_n_drag'" :class="item.color ? 'span_color_drag' : ''"
        @click="comBtnClick(item)">{{ item.name }}</span>
      <span v-if="item.style_self == 'btn_checkout'" class="span_checkbox">
        <vxe-checkbox v-model="data.top_btn_checkbox" size="small" :content="item.name"
          @change="comBtnClick(item)"></vxe-checkbox>
      </span>
      <span v-if="item.style_self == 'btn_upload'">
        <el-upload v-model:file-list="data.fileListTableTop" class="upload-demo" :action="item.upload_url"
          :show-file-list="false" :on-success="handleSucessTableTop" multiple :before-upload="handleBeforeUploadTableTop"
          :with-credentials="data.withcredentials" :limit="100000">
          <span class="upload_span">{{ item.name }}</span>
        </el-upload>
      </span>
    </div>
  </div>
  <vxe-table ref="getDomN" class="my-table" border resizable :max-height="tableHeigth" :scroll-x="{ enabled: false }"
    :row-config="{ isHover: true }" :scroll-y="{ enabled: false }" :data="data.list" @checkbox-change="getSelectRow"
    @checkbox-all="getSelectRow" :show-footer="data.showFooter" :merge-footer-items="data.mergeFooterItems"
    :loading="data.loading" keep-source :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }"
    :column-config="{ resizable: true }" :sync-resize="titleTag" :key="titleTag">
    <div v-for=" (item, index) in data.listHeader"
      :key="titleTag ? titleTag : '' + item.field + index + data.headerIndex">
      <!-- 文本 -->
      <vxe-column v-if="item.type == 'text'" :field="item.field" :title="item.title" :width="item.width"
        :align="item.align"></vxe-column>
      <!-- 文本 自定义color 列 -->
      <vxe-column v-if="item.type == 'text_color_column'" :field="item.field" :title="item.title" :width="item.width"
        :align="item.align">
        <template #default="{ row }">
          <span :style="{ 'color': item.color_s }">{{ row[item.field] }}</span>
        </template>
      </vxe-column>
      <!-- 文本 自定义color 行 -->
      <vxe-column v-if="item.type == 'text_color_row'" :field="item.field" :title="item.title" :width="item.width"
        :align="item.align">
        <template #default="{ row }">
          <span :style="{ 'color': row.color_s }">{{ row[item.field] }}</span>
        </template>
      </vxe-column>
      <!-- 上传 -->
      <vxe-column v-if="item.type == 'img_upload'" :field="item.field" :title="item.title" :width="item.width"
        :align="item.align">
        <template #default="{ row }">
          <el-upload :action="data.upLoadUrl" :with-credentials="true" :on-success="function (res, file, file_list) {
            return handleSuccess(res, file, file_list, row)
          }" :show-file-list="false" name="file" :limit="1" :data="data.upLoadQuery" accept=".png, .jpg"
            :on-change="handleChange">
            <img v-if="row.image" :src="row.image" class="avatar" />
            <el-icon v-else class="el-icon-plus"></el-icon>
          </el-upload>
        </template>
      </vxe-column>
      <!-- 操作 -->
      <vxe-column v-if="item.type == 'operation'" :field="item.field" :title="item.title" :width="item.width"
        :align="item.align">
        <template #default="{ row, $rowIndex }">
          <div class="operation_div" v-if="row.isDownLoadShow">
            <vxe-button type="text" class="download" @click="operationDown(row, item.field)">下载</vxe-button>
            <vxe-button type="text" class="delete" @click="operationDel($rowIndex)">删除</vxe-button>
          </div>
          <div class="operation_div" v-if="!row.isDownLoadShow">
            <vxe-button type="text" class="delete" @click="operationDel($rowIndex)">删除</vxe-button>
          </div>
        </template>
      </vxe-column>
      <vxe-column v-if="item.type == 'downLoadUrl'" :field="item.field" :title="item.title" :width="item.width"
        :align="item.align">
        <template #default="{ row }">
          <div class="operation_div">
            <vxe-button type="text" class="download" v-if="!row.isShowCopy"
              @click="operationDown(row, item.field)">下载</vxe-button>
          </div>
          <div class="operation_div">
            <vxe-button type="text" class="download" v-if="row.isShowCopy"
              @click="operationCopy(row[item.field])">复制</vxe-button>
          </div>
        </template>
      </vxe-column>
      <!-- 输入框 -->
      <vxe-column v-if="item.type == 'editable_ipt'" :field="item.field" :title="item.title" show-overflow
        :width="item.width" :align="item.align" :edit-render="{ autofocus: '.vxe-input--inner' }">
        <template #edit="scope">
          <vxe-input v-model.trim="scope.row[item.field]" :disabled="data.isDisabled"
            @blur="clearNull(scope.row[item.field], scope.$rowIndex, item.field)" @change="getDomN.updateStatus(scope)">
          </vxe-input>
        </template>
      </vxe-column>
    </div>
  </vxe-table>
</template>
<script>
import { defineComponent, reactive, getCurrentInstance, ref, onMounted, nextTick, watch } from "vue";
import { downloadzl } from "../../utils/lc";
export default defineComponent({
  name: 'lcwjsc',
  props: {
    listHeader: Array,
    defaultRow: Array,
    tableHeader: Array,
    beforeStrList: Array,
    mergeColData: Array,
    staticList: Object,
    notShowCol: Array,
    singleChangeList: Array,
    singleLabel: String,
    singleTitle: String,
    notice: Number,
    tableHeigth: Number,
    code: String,
    loading: Boolean,
    titleTag: String,
    pageTage: String
  },
  emits: ['getClickBtnType', 'getSingleSelVal', 'getRouteInfo', 'getPushDown', 'uploadAddRow', 'editDataEmit', 'selDataEmit', 'getMhSelectArr'],
  setup (props, context) {
    // 获取、创建实例
    const { proxy } = getCurrentInstance()
    let getDomN = ref(null)
    let getDia = ref(null)
    // 生命周期
    onMounted(() => {
      nextTick(() => {
        data.loading = true
        data.listHeader = props.listHeader
        data.list = props.defaultRow
        data.tableHeader = props.tableHeader
        data.staticList = props.staticList
        data.notShowCol = props.notShowCol
        data.beforeStrList = props.beforeStrList
        data.singleLabel = props.singleLabel
        data.singleTitle = props.singleTitle
        data.listHeader.forEach(el => {
          if (el.type == 'img_upload') {
            data.upLoadUrl = el.upload_url
          }
        });
        // 获取弹窗字段
        data.listHeader.forEach(el => {
          if (el.type != 'checkbox') {
            if (!data.notShowCol.includes(el.title)) {
              data.dialogList.push({ title: el.title, visible: true })
            }
          }
        });
        // 处理选择框默认值、模糊匹配值
        data.beforeStrList.forEach(el => {
          if (el.slice(0, 1) == 'd') {
            data[el + 'list'] = [[]]
          } else {
            data[el + 'list'] = []
            for (const key in data.staticList) {
              if (key.includes(el)) {
                data[el + 'list'] = data.staticList[key]
              }
            }
          }
        });
        if (props.mergeColData) {
          props.mergeColData.length > 0 ? data.mergeFooterItems = props.mergeColData[0].mergeFooterItems : ''
          props.mergeColData.length > 0 ? data.showFooter = true : data.showFooter = false
        }
        data.listHeader.reverse()
        data.listHeader.forEach(el => {
          if (el.children) {
            el.children.reverse()
          }
        });
        if (proxy.$refs.getDomN) {
          setTimeout(() => {
            proxy.$refs.getDomN.loadData(data.list)
            data.loading = false
          }, 1000)
        }
      })
    })
    // 添加行
    let ljlist = reactive([])
    const addRow = reactive({})
    // 变量
    let data = reactive({
      withcredentials: true,
      routerAlive: false,
      sendVal: false,
      top_btn_checkbox: 0,
      isShowColTable: false,
      tableHeader: [],
      listHeader: [],
      list: [],
      loading: false,
      dialogList: [],
      staticList: {},
      beforeStrList: [],
      selectList: [],
      selectListDia: [],
      notShowCol: [],
      mergeFooterItems: [],
      showFooter: false,
      headerIndex: 1,
      isDisabled: false,
      showImgUrl: '',
      top: '',
      dialogColumns: [],
      showColumns: [],
      upLoadUrl: '',
      upLoadQuery: {
        type: 'images',
      },
      refresh: 1,
      delType: '',
      singleIndex: null,
      singleChangeList: [],
      singleIsShow: false,
      singleIndex: null,
      singleLabel: '',
      singleTitle: '',
      fileListTableTop: [],
      getlistDom: []
    })
    // 获取选中的行
    const getSelectRow = (selectList) => {
      data.selectList = []
      data.selectList = selectList.records
      context.emit('selDataEmit', data.selectList)
    }
    // 上传成功
    const handleSuccess = (res, file, files, row) => {
      if (res.status == 200) {
        row.image = res.data.fileurl
      }
    }

    // 图片上传
    const handleChange = () => { }
    // 顶部铵钮点击事件
    const comBtnClick = async (item) => {
      // 新增行
      if (item.type == 'add') {
        const row = -1
        const $table = getDomN.value
        data.beforeStrList.forEach(el => {
          if (el.substr(0, 1) == 'd') {
            data[el + 'list'].push([])
          }
        });
        data.listHeader.forEach(el => {
          if (el.type !== 'checkout') {
            if (el.type == 'router' || el.type == 'pushDown') {
              addRow[el.field] = data.list[0] ? data.list[0][el.field] : ''
            } else {
              addRow[el.field] = ''
            }
          }
        });
        addRow.index = data.list.length + 1
        data.list.push(JSON.parse(JSON.stringify(addRow)))
        const { row: newRow } = await $table.insertAt(JSON.parse(JSON.stringify(addRow)), row)
        await $table.setActiveCell(newRow, data.listHeader[2].field)
        await $table.loadData(data.list)
        // 删除行 
      } else if (item.type == 'del') {
        if (data.selectList.length > 0) {
          data.delType = 'many'
          data.sendVal = true
          data.refresh = data.refresh + 1
        } else {
          proxy.$message({ type: 'error', message: '请选择需要删除的行!' })
        }
        // 显示列
      } else if (item.type == 'popup') {
        data.isShowColTable = true
      } else if (item.type == 'sel_single') {
        if (data.selectList.length > 0) {
          data.singleIsShow = true
          data.singleIndex = data.singleIndex + 1
        } else {
          proxy.$message({ type: 'error', message: '请选择需要操作的行!' })
        }
      } else {
        if (item.type != 'check_box') {
          context.emit('getClickBtnType', item.type, data.selectList, props.code, data.list)
        } else {
          // 处理传递的数据 1 || 0
          let value = data.top_btn_checkbox ? '1' : '0'
          context.emit('getClickBtnType', item.type, data.selectList, value)
        }
      }
    }
    // 列显示 - 重置、还原
    const colShowReset = () => {
      // 用props传递的请求数据重置初始状态
      nextTick(() => {
        const $table = getDomN.value
        data.loading = true
        // 获取dialog选择 - 需要配置列
        data.dialogColumns = data.dialogList
        setTimeout(() => {
          // 设置为默认值
          data.dialogColumns.forEach(dialogCol => {
            dialogCol.visible = true
          })
          // 操作 表格列显示隐藏
          data.dialogColumns.forEach(dialogCol => {
            data.showColumns.forEach(showCol => {
              if (dialogCol.title == showCol.title) {
                showCol.visible = dialogCol.visible
              }
            })
          });
          if ($table) {
            $table.refreshColumn()
          }
          // 清空集合
          data.selectListDia = []
          data.loading = false
        }, 800)
        data.isShowColTable = false
      })
    }
    // 表格行删除
    const operationDel = async (index) => {
      data.list.splice(index, 1)
      data.delType = 'single'
      data.sendVal = true
      data.singleIndex = index
      data.refresh = data.refresh + 1
    }
    // 表格行下载
    const operationDown = (row) => {
      downloadzl(row.url, row.title)
    }
    // 获取所有列配置
    setTimeout(() => {
      nextTick(() => {
        data.showColumns = getDomN.value.getColumns()
      })
    }, 100)
    // 复制
    const operationCopy = (copyValue) => {
      var input = document.createElement("input");
      input.value = copyValue;
      document.body.appendChild(input);
      input.select();
      document.execCommand("Copy");
      document.body.removeChild(input);
      proxy.$message.success('复制成功')
    }
    // 顶部 文件上传
    const handleSucessTableTop = (res, file, file_list) => {
      if (res.status == 200) {
        context.emit('uploadAddRow', { name: file.name, date: getCurrentDate(), table_list: data.list, url: file.response.data.fileurl }, props.code)
      } else {
        proxy.$message.error(res.message)
      }
      data.loading = false
    }
    const handleBeforeUploadTableTop = (file) => {
      data.loading = true
      const isLt2M = file.size / 1024 / 1024 < 20
      if (!isLt2M) {
        proxy.$message.error('上传文件大小不能超过 20MB!')
        data.loading = false
        return false
      }
    }
    // 获取时间日期
    const getCurrentDate = () => {
      const date = new Date();
      const Y = date.getFullYear() + '/';
      const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '/';
      const D = date.getDate() + ' ';
      const h = date.getHours() + ':';
      const m = date.getMinutes() + ':';
      const s = date.getSeconds();
      const dateString = Y + M + D + h + m + s;
      return dateString;
    }
    // 监听
    watch(() => props.notice, () => {
      data.headerIndex = data.headerIndex + 1
    })
    watch(() => props.defaultRow, async (v1) => {
      if (v1.length > 0 && v1[0].data) {
        v1.forEach((el, ind) => {
          ljlist[ind] = el.data
        });
      }
      data.list = v1
      data.selectList = []
      if (getDomN.value) {
        const $table = getDomN.value
        await $table.loadData(data.list)
      }
    })
    watch(() => props.singleChangeList, (v1) => {
      data.singleChangeList = v1
    })
    watch(() => props.staticList, async (v1) => {
      data.staticList = v1
      data.beforeStrList.forEach(el => {
        if (el.slice(0, 1) == 'd') {
          data[el + 'list'] = [[]]
        } else {
          data[el + 'list'] = []
          for (const key in data.staticList) {
            if (key.includes(el)) {
              data[el + 'list'] = data.staticList[key]
            }
          }
        }
      });
      const $table = getDomN.value
      await $table.loadData(data.list)
    }, { deep: true })
    watch(() => props.loading, (v1) => {
      data.loading = v1
    })
    watch(() => data.list, (v1) => {
      context.emit('editDataEmit', v1, props.code)
    }, { deep: true })
    return {
      data,
      addRow,
      ljlist,
      props,
      proxy,
      getDomN,
      getDia,
      context,
      operationDown,
      operationDel,
      colShowReset,
      getSelectRow,
      handleChange,
      handleSuccess,
      comBtnClick,
      operationCopy,
      handleSucessTableTop,
      handleBeforeUploadTableTop,
      getCurrentDate,
    }
  }
})
</script>

<style scoped lang="scss">
.operation_div {
  display: flex;
  justify-content: center;
  align-items: center;
}

.operation_div .download {
  color: #409EFF;
}

.operation_div .delete {
  color: #E73235;
  margin-left: 0px !important;
}

.el-dialog__title {
  color: #303133;
  font-weight: 700;
}

.el-overlay {
  background-color: rgba(237, 230, 230, 0.01) !important;
}

.btn-flex {
  display: flex;
  margin-bottom: 16px;
  align-items: center;
}

.btn-group {
  display: flex;
  margin-right: 10px;
}

.dialog-span {
  display: flex;
  margin-bottom: 10px;
}

.el-dialog__body {
  padding-top: 0 !important;
}

.dialog-span span:nth-child(2) {
  flex: 1;
  border: 1px solid #FFF;
}

.dialog-span span:nth-child(1):hover,
.dialog-span span:nth-child(3):hover,
.dialog-span span:nth-child(4):hover {
  color: #fff;
  background: #409EFF;
}

.dialog-span span {
  color: #409EFF;
  margin-right: 10px;
  font-size: 14px;
  cursor: pointer;
  padding: 4px 8px;
  border: 1px solid #409EFF;
  border-radius: 3px;
}

.dialog-span span:nth-child(4) {
  margin-right: 0px !important;
}

.upload_span {
  color: #409eff;
  font-size: 14px;
  cursor: pointer;
  padding: 4px 8px;
  border: 1px solid #409EFF;
  border-radius: 3px;
}

.upload_span:hover {
  color: #fff;
  background: #409EFF;
}

.btn-group>.span_color_n {
  color: #409eff;
  font-size: 14px;
  cursor: pointer;
  padding: 4px 8px;
  border: 1px solid #409EFF;
  border-radius: 3px;
}

.btn-group>.span_color {
  background: #409eff;
  color: #fff;
  font-size: 14px;
  cursor: pointer;
  padding: 4px 8px;
  border: 1px solid #409EFF;
  border-radius: 3px;
}

.btn-group>.span_color:hover {
  background: #fff;
  color: #409eff;
  font-size: 14px;
  cursor: pointer;
  padding: 4px 8px;
  border: 1px solid #409EFF;
  border-radius: 3px;
}

.btn-group>.span_color_drag {
  background: #409eff;
  color: #fff;
  font-size: 14px;
  cursor: pointer;
  padding: 4px 8px;
  border: 1px solid #409EFF;
  border-radius: 3px;
}

.btn-group>.span_color_drag:hover {
  background-color: #79bbff;
  border-color: #79bbff;
  color: #fff;
  font-size: 14px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 3px;
}

.btn-group>.span_color_n:hover {
  color: #fff;
  background: #409EFF;
}

.router-links {
  color: #409eff;
  cursor: pointer;
}

::v-deep(.avatar) {
  width: 40px;
  height: 40px;
  padding-top: 5px;
  padding-bottom: 5px;
}

::v-deep(.el-icon-plus) {
  width: 40px;
  height: 40px;
  border-radius: 2px;
  line-height: 40px;
  border: 1px dashed rgba(0, 0, 0, 0.1);
}

.img-show {
  width: 150px;
  height: 150px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  overflow: hidden;
  z-index: 9;
  background-color: #fff;
  vertical-align: middle;
  margin-top: -60px;
  text-align: center;
}

.img-show img {
  z-index: 10;
  max-width: 150px;
  vertical-align: middle;
}

.operation_div .vxe-button {
  width: 80px;
}

.span_checkbox {
  display: flex;
  justify-content: center;
  align-items: center;
}

.vxe-toolbar {
  padding: 4px 8px !important;
}

::v-deep(.el-button) {
  padding: 18px !important;
}

::v-deep(.el-popper) {
  width: 114px !important;
}

::v-deep(.el-dropdown-menu__item) {
  justify-content: center;
}

.btn-flex_span {
  display: flex;
  align-items: center;
  padding: 2px 0;
}

.btn_div {
  padding: 6px 10px;
  font-size: 14px;
  background: #409EFF;
  border-radius: 3px;
  color: #EBEEF5;
  display: inline-block;
  align-items: center;
  cursor: pointer;
}

::v-deep(.el-button:focus,
  .el-button:hover) {
  background-color: #409EFF;
}

.icons-down {
  display: block;
  margin-left: 8px;
}

::v-deep(.el-upload .el-button) {
  padding: 6px 10px !important;
}

::v-deep(.el-button) {
  padding: 6px 10px !important;
}
</style> 