<template>
  <div id="spaceTarget-management">
    <div
      class="spaceTarget-management-body"
      v-loading.fullscreen.lock="fullscreenLoading"
    >
      <div class="order-management-body">
        <div class="order-management-inner">
          <div class="base-info">
            <el-input
              style="width: 220px"
              v-model="searchKey"
              placeholder="输入版本号进行搜索"
            ></el-input>
            <el-button type="primary" @click="_searchOrderData(1)" color="red"
              >搜索</el-button
            >
          </div>
        </div>

        <div class="spaceTarget-management_bottom">
          <div class="order-management-table">
            <div class="order-check_tab">
              <ul>
                <li
                  v-for="(item, index) in tabs"
                  :key="index"
                  :class="{ 'order-check_tab_li_active': item.idx == tabIndex }"
                  @click="clickTabItem(item.idx)"
                >
                  {{ item.name
                  }}<span
                    v-if="item.idx != 2"
                    style="margin: 0 10px; color: #999; font-weight: normal"
                    >/</span
                  >
                </li>
              </ul>
              <div style="float: right; vertical-align: middle">
                <!-- <el-select v-model="selectValue" placeholder="请选择">
                  <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select> -->
                <el-button type="success" @click="openMarks" color="red">上传</el-button>
              </div>
            </div>
            <el-table
              cell-class-name="hh"
              ref="order_table"
              class="e-table"
              :data="orders"
              style="width: 100%"
            >
              <!-- <el-table-column type="index">
              </el-table-column> -->
              <el-table-column
                :ref="item.label == '版本更新说明' ? 'version_desc' : ''"
                :min-width="item.label == '版本更新说明' ? '200px' : '100px'"
                v-for="(item, i) in tableHeader"
                :key="i"
                :prop="item.name"
                :label="item.label"
              >
                <template slot-scope="scope">
                  <span v-if="item.label == '状态'">
                    <span v-if="scope.row.status == 1">已发布</span>

                    <span v-if="scope.row.status == 0">未发布</span>
                    <span v-if="scope.row.status == 2">已下架</span>
                  </span>
                  <span v-if="item.label == '置顶'">
                    <span v-if="scope.row.isTop">是</span>
                    <span v-if="!scope.row.isTop">否</span>
                  </span>
                  <!-- <span v-if="item.label=='版本更新说明' && scope.row[item.name]!=''" :style="`max-width:${columnWidth}px;`" class="fixed_Box">
                    {{scope.row[item.name]}}
                  </span> -->
                  <span
                    v-if="item.label != '置顶' && item.label != '状态'"
                    class="desc"
                    >{{ scope.row[item.name] || "-" }}</span
                  >
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150px">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    @click="del(scope.row.id)"
                    class="delete_btn"
                    :disabled="
                      (scope.row.isTop == 1 && scope.row.status == 1) ||
                      scope.row.status == 1
                    "
                    >删除</el-button
                  >
                  <el-button type="text" @click="editRow(scope.row)" class="edit_btn"
                    >编辑</el-button
                  >
                  <el-button
                    v-if="scope.row.status != 1"
                    type="text"
                    @click="pushData(scope.row.id)"
                    class="edit_btn"
                    >发布</el-button
                  >
                  <el-button
                    v-if="scope.row.status == 1"
                    :disabled="scope.row.isTop == 1 && scope.row.status == 1"
                    type="text"
                    @click="pushDown(scope.row.id)"
                    class="edit_btn"
                    >下架</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="order-management-pagination">
            <el-pagination
              @current-change="handleCurrentChange"
              :current-page.sync="currentPage"
              :page-size="10"
              layout="total, prev, pager, next, jumper"
              :total="total"
            >
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      width="750px"
      title="上传"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="active"
    >
      <el-form :model="ruleForm" ref="el_form" :rules="rules" label-width="100px">
        <el-form-item label="平台类型" width="100%">
          <el-radio
            :disabled="(isEdit && ruleForm.platformType != 1) || loading"
            v-model="ruleForm.platformType"
            :label="1"
            >Unity</el-radio
          >
          <el-radio
            :disabled="(isEdit && ruleForm.platformType != 2) || loading"
            v-model="ruleForm.platformType"
            :label="2"
            >UE4</el-radio
          >
        </el-form-item>
        <el-form-item label="版本号" width="100%" prop="version">
          <el-input
            @input="limitInput"
            placeholder="请输入数字、英文或符号"
            :disabled="isEdit || loading"
            v-model="ruleForm.version"
          ></el-input>
        </el-form-item>
        <el-form-item label="版本更新说明" width="100%">
          <span
            @click="chooseDescType(1)"
            class="sdkdesc"
            :class="descType == 1 ? 'active' : ''"
            >CH</span
          >
          <span
            @click="chooseDescType(2)"
            class="sdkdesc"
            :class="descType == 2 ? 'active' : ''"
            >EH</span
          >
          <el-input
            :disabled="loading"
            placeholder="请输入中文版本更新说明"
            v-if="descType == 1"
            type="textarea"
            maxlength="200"
            resize="none"
            v-model="ruleForm.imprintCh"
            :rows="5"
          ></el-input>

          <el-input
            :disabled="loading"
            placeholder="请输入英文版本更新说明"
            v-else
            type="textarea"
            maxlength="200"
            resize="none"
            v-model="ruleForm.imprintEn"
            :rows="5"
          ></el-input>
        </el-form-item>
        <el-form-item ref="uploadFile" label="文件" width="100%" prop="file">
          <p v-if="isEdit">
            <i class="el-icon-paperclip" style="margin-right: 10px"></i
            >{{ ruleForm.fileName }}
          </p>
          <div v-else class="upload-file">
            <el-button type="primary" :disabled="loading">文件上传</el-button>
            <input
              type="file"
              :disabled="loading"
              @change="changeFile($event)"
              ref="file"
            />
            <p v-if="ruleForm.file != ''">
              <i class="el-icon-paperclip" style="margin-right: 10px"></i
              >{{ ruleForm.file.name }}
            </p>
            <el-progress v-if="loading" :percentage="complete"></el-progress>
          </div>
        </el-form-item>
        <el-form-item label="官网置顶" width="100%">
          <el-checkbox :disabled="loading" v-model="ruleForm.isTop"
            >（勾选此项，将在四维看看官网置顶）</el-checkbox
          >
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <div class="bottomBox">
          <span class="editLastTime" v-show="isEdit"
            >上次编辑：{{ ruleForm.updateTime }}</span
          >
          <div class="bottomBtn">
            <el-button @click="close_dialog">取 消</el-button>
            <el-button
              v-if="!isEdit"
              type="primary"
              :loading="loading"
              @click="uploadMaker"
              >确 定</el-button
            >
            <el-button v-else type="primary" :loading="loading" @click="updateMaker"
              >确 定</el-button
            >
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
const tableHeader = [
  {
    name: 'version',
    label: '版本号'
  },
  {
    name: 'imprintCh',
    label: '版本更新说明'
  },
  {
    name: 'publishTime',
    label: '首次发布时间'
  },
  {
    name: 'isTop',
    label: '置顶'
  },
  {
    name: 'status',
    label: '状态'
  }
]
export default {
  data () {
    var validateFile = (rule, value, callback) => {
      console.log(value)
      if (value === '') {
        callback(new Error('请上传文件'))
      } else {
        // if (this.ruleForm.checkPass !== '') {
        //   this.$refs.ruleForm.validateField('file')
        // }
        callback()
      }
    }

    return {
      loading: false,
      complete: 0,
      descType: 1,
      columnWidth: '',
      ruleForm: {
        platformType: 1,
        version: '',
        imprintCh: '',
        imprintEn: '',
        file: '',
        isTop: false
      },
      rules: {
        version: [{ required: true, message: '版本号不能为空', trigger: 'blur' }],
        file: [{ required: true, validator: validateFile, trigger: 'change' }]
      },
      isEdit: false,
      active: false,
      currentPage: 1,
      total: 0,
      tabIndex: 1,
      fullscreenLoading: false,
      searchKey: '',
      imprintCh: '',
      imprintEn: '',
      tableHeader,
      tabs: [
        { name: 'Unity', idx: 1 },
        { name: 'UE4', idx: 2 }
      ],
      orders: [
        // {
        //   id: 1,
        //   type: 1,
        //   isTop: true,
        //   file: 'sss.zip',
        //   version: 1,
        //   imprintEn: 'sdsadsadasdas',
        //   imprintCh: '',
        //   fristPushTime: '2021-06-01',
        //   status: 0 // 0 未发布，1 已发布，2 ，已下架
        // },
        // {
        //   id: 2,
        //   type: 2,
        //   isTop: false,
        //   version: 3,
        //   file: '111.zip',
        //   imprintEn: 'sdsadsadasdas',
        //   imprintCh: 'asd',
        //   fristPushTime: '2021-06-01',
        //   status: 1
        // },
        // {
        //   id: 3,
        //   type: 2,
        //   isTop: false,
        //   version: 2,
        //   file: '1234.zip',
        //   imprintEn: 'sdsadsadasdas',
        //   imprintCh:
        //     '全部更新说明全部更新说明全部更新说明全部更新说明全部更新说明全部更新说明全部更新说明全部更新说明全部更新说明全部更新说明全部更新说明全部更新说明全部更新说明',
        //   fristPushTime: '2021-06-01',
        //   status: 2
        // }
      ]
    }
  },
  watch: {},
  methods: {
    limitInput () {
      this.ruleForm.version = this.ruleForm.version.replace(
        /[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/g,
        ''
      )
    },
    openMarks () {
      this.active = true
      this.descType = 1
    },
    chooseDescType (type) {
      this.descType = type
    },
    editRow (data) {
      let res = JSON.stringify(data)

      this.ruleForm = JSON.parse(res)
      console.log(this.ruleForm)
      this.ruleForm.platformType = this.ruleForm.platformType - 0
      if (this.ruleForm.isTop == 1) {
        this.ruleForm.isTop = true
      } else {
        this.ruleForm.isTop = false
      }
      this.isEdit = true
      this.active = true
    },
    close_dialog () {
      if (!this.isEdit) {
        this.$refs.file.value = ''
      }
      this.$refs['el_form'].clearValidate()
      this.$refs['el_form'].resetFields()
      this.isEdit = false
      this.active = false
      this.complete = 0
      this.ruleForm = {
        platformType: this.tabIndex,
        version: '',
        imprintCh: '',
        imprintEn: '',
        file: '',
        isTop: false
      }
    },
    del (id) {
      this.openConfirm({
        title: '是否确定删除该文件?',
        name: '删除',
        confirmText: '确认删除',
        ok: async () => {
          let res = await this.$http.post('/manager/sdk/del', {
            id: id
          })
          if (res.code === 0) {
            this.searchKey = ''
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
          let page
          if (this.orders.length == 1) {
            if (this.currentPage > 1) {
              page = this.currentPage - 1
            } else {
              page = this.currentPage
            }
          } else {
            page = this.currentPage
          }
          this._searchOrderData(page)
        },
        no: () => {}
      })
    },
    pushData (id) {
      this.openConfirm({
        title: '是否确定发布该文件? 发布后将在官网展示。',
        name: '发布',
        confirmText: '确认发布',
        ok: async () => {
          let res = await this.$http.post('/manager/sdk/online', {
            id: id,
            status: 1
          })
          if (res.code === 0) {
            this.searchKey = ''
            this.$message({
              type: 'success',
              message: '发布成功!'
            })
          }
          this._searchOrderData(this.currentPage)
        },
        no: () => {}
      })
    },
    pushDown (id) {
      this.openConfirm({
        title: '下架后官网将不展示该 SDK?',
        name: '下架',
        confirmText: '确认下架',
        ok: async () => {
          let res = await this.$http.post('/manager/sdk/online', {
            id: id,
            status: 2
          })
          if (res.code === 0) {
            this.searchKey = ''
            this.$message({
              type: 'success',
              message: '下架成功!'
            })
          }
          this._searchOrderData(this.currentPage)
        },
        no: () => {}
      })
    },
    changeFile (e) {
      // this.ruleForm.file = e.target.value
      this.ruleForm.file = e.target.files[0]
      this.$refs['uploadFile'].clearValidate()
    },
    async uploadMaker () {
      try {
        let valid = await this.$refs['el_form'].validate()
        console.log(valid)
        if (valid) {
          var formData = new FormData()
          formData.append('file', this.ruleForm.file)
          formData.append('version', this.ruleForm.version)
          formData.append('imprintCh', this.ruleForm.imprintCh)
          formData.append('imprintEn', this.ruleForm.imprintEn)
          let isTop
          if (this.ruleForm.isTop) {
            isTop = 1
          } else {
            isTop = 0
          }
          formData.append('isTop', isTop)
          formData.append('platformType', this.ruleForm.platformType)
          try {
            // this.fullscreenLoading = true

            this.loading = true
            let res = await this.$http({
              url: '/manager/sdk/upload',
              method: 'post',
              data: formData,
              onUploadProgress: (progressEvent) => {
                this.complete = ((progressEvent.loaded / progressEvent.total) * 100) | 0
                console.log('上传 ' + this.complete)
              },
              processData: false,
              contentType: false
            })
            if (res) {
              this.loading = false
              if (res.code === 0) {
                this.close_dialog()
                this.tabIndex = this.ruleForm.platformType
                this.searchKey = ''
                this.$message({
                  type: 'success',
                  message: '上传成功!'
                })
              }

              // this.fullscreenLoading = false
            }
          } catch (err) {
            this.loading = false
            // this.fullscreenLoading = false
          }

          this.active = false
          this.$refs.file.value = ''
          this._searchOrderData(1)
        }
      } catch (err) {}
    },
    async updateMaker () {
      try {
        let valid = await this.$refs['el_form'].validate()
        console.log(valid)
        let res = JSON.stringify(this.ruleForm)

        let params = JSON.parse(res)
        if (params.isTop) {
          params.isTop = 1
        } else {
          params.isTop = 0
        }
        if (valid) {
          try {
            // this.fullscreenLoading = true

            this.loading = true
            let res = await this.$http({
              url: '/manager/sdk/update',
              method: 'post',
              data: params
            })
            if (res) {
              this.loading = false
              // this.fullscreenLoading = false
              if (res.code === 0) {
                this.close_dialog()
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                })
              }
            }
          } catch (err) {
            this.loading = false
            // this.fullscreenLoading = false
          }

          this.active = false
          this._searchOrderData(this.currentPage)
        }
      } catch (err) {}
    },
    handleCurrentChange (val) {
      let page = val
      if (this.total > 0 && !this.hasClickSearch) {
        this._searchOrderData(page)
      } else {
        this._searchOrderData(page)
      }
    },
    // handleMouseEnter (row, column, cell, event) {
    //   console.log(row)
    //   // cell.classList.add(style)
    // },
    clickTabItem (idx) {
      this.tabIndex = idx
      this.hasClickSearch = false
      this.total = 0
      this.currentPage = 1
      this.status = this.tabIndex === -1 ? null : this.tabIndex
      this.searchKey = ''
      this.ruleForm.platformType = this.tabIndex
      // if (
      //   !this.searchDate ||
      //   this.expressNum ||
      //   !this.userName ||
      //   !this.orderNum
      // ) {
      this._searchOrderData(1)
      // }
    },
    async _searchOrderData (page) {
      this.hasClickSearch = true

      // this.fullscreenLoading = true
      try {
        let data = (
          await this.$http.post('/manager/sdk/list', {
            pageNum: page,
            pageSize: 10,
            platformType: this.tabIndex,
            searchKey: this.searchKey
          })
        ).data

        this.fullscreenLoading = false
        let temp = data.list
        this.orders = temp
        this.currentPage = page
        this.total = data.total
        this.getColumnWidth()
      } catch (error) {
        this.getColumnWidth()
      }
    },
    openConfirm (opts) {
      return new Promise((resolve, reject) => {
        this.$confirm(opts.title, '提示', {
          confirmButtonText: opts.confirmText,
          cancelButtonText: '取消',
          type: 'warning'
        })

          .then(() => {
            // this.$message({
            //   type: 'success',
            //   message: opts.name + '成功!'
            // })

            resolve(opts.ok())
          })
          .catch(() => {
            // this.$message({
            //   type: 'info',
            //   message: '已取消' + opts.name
            // })
            reject(opts.no())
          })
      })
    },
    getColumnWidth () {
      // console.log(document.querySelector('.has-gutter >tr >th:nth-of-type(2)').offsetWidth)

      this.columnWidth = document.querySelector(
        '.has-gutter >tr >th:nth-of-type(2)'
      ).offsetWidth
    }
  },
  created () {},
  mounted () {
    this._searchOrderData(1)
    window.onresize = () => {
      // 定义窗口大小变更通知事件
      this.getColumnWidth()
    }
  }
}
</script>
<style lang="css" scoped>
@import "./style.css";
</style>
<style type="text/css">
.sdkdesc {
  cursor: pointer;
  margin-right: 10px;
}
.sdkdesc.active {
  color: #409eff;
}
.el-table__expand-icon > i {
  display: none !important;
}

.edit_btn span {
  color: #09e1c0;
}
.edit_btn.is-disabled span {
  color: #999;
}

.delete_btn span {
  color: #f56c6c;
}
.delete_btn.is-disabled span {
  color: #999;
}
.el-table .el-table__body tr td:nth-of-type(2) {
  position: relative;
}
.desc {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.fixed_Box {
  text-align: left;
  position: fixed;
  left: auto;
  top: auto;
  max-width: 300px;
  height: auto;
  background: #fff;
  z-index: 10;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  -moz-box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  -webkit-box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  padding: 8px;
  font-size: 14px;
  display: none;
}
.el-table .el-table__body tr td:nth-of-type(2):hover .fixed_Box {
  display: block;
  text-align: left;
  position: fixed;
  left: auto;
  top: auto;
  max-width: 300px;
  height: auto;
  background: #fff;
  z-index: 10;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  -moz-box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  -webkit-box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  padding: 8px;
  font-size: 14px;
}
/* .el-table {
  overflow: auto;
}
.el-table__body-wrapper {
  overflow: auto;
} */
.dialog-footer .bottomBox {
  /* display: flex;
  align-items: center;
  justify-content: space-between; */
  overflow: hidden;
}
.editLastTime {
  font-size: 12px;
  color: #999;
  float: left;
  line-height: 40px;
}
.bottomBtn {
  float: right;
}
</style>
