<template>
  <div id="cloud-balance">
    <el-button @click="clickAdd">添加</el-button>
    <div class="table">
      <el-table
        v-if="tableData.length"
        height="100%"
        border
        style="width: 100%"
        :data="tableData"
        :row-class-name="tableRowClassName"
      >
        <el-table-column
          v-for="(prop, index) of tableProps"
          :key="index"
          :prop="prop"
          align="center"
          :label="tableHeaders[index]"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              v-if="prop === 'uid'"
              @click="clickUID(scope.row)"
            >{{scope.row[prop]}}</el-button>
            <img
              v-else-if="prop === 'url'"
              :src="scope.row[prop]"
              alt="url"
              style="display: block; width: 100px; height: 80px;"
            >
            <section class="ctrls" v-else-if="prop === 'ctrls'">
              <el-button type="text" @click="clickEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button type="text" @click="clickDel(scope.$index, scope.row)">删除</el-button>
            </section>
            <span v-else>{{scope.row[prop]}}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog title="添加展示" :visible.sync="centerDialogVisible" width="50%" center>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="UID" prop="uid">
          <el-input type="number" v-model="ruleForm.uid" :disabled="isEdit"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="order">
          <el-input type="number" v-model="ruleForm.order"></el-input>
        </el-form-item>
        <el-form-item label="配图" prop="url">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/developer/uploadImg"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="ruleForm.url" :src="ruleForm.url" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="clickSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

const tableHeaders = [
  'ID',
  '昵称',
  '排序',
  '配图',
  '添加时间',
  '操作',
]
const tableProps = [
  'uid',
  'nickname',
  'order',
  'url',
  'create_date',
  'ctrls',
]

export default {
  data() {
    return {
      // 是否是编辑入口
      isEdit: false,
      ruleForm: {},
      rules: {
        id: [
          { required: true, message: '请填写开发者ID', trigger: 'blur' },
        ],
        url: [
          { type: 'string', required: true, message: '请上传配图', trigger: 'change' }
        ],
      },
      // 弹框
      centerDialogVisible: false,
      // 数据总条目
      totalCount: 0,
      currentPage: 1,
      // 列表头显示内容
      tableHeaders,
      // 列表头字段
      tableProps,
      // 列表数据
      tableData: []
    }
  },
  mounted() {
    this.getTableData()
  },
  methods: {
    // 点击新增或编辑框的确认
    async clickSubmit() {
      let url = '/api/admin/developer/addRecommendDeveloper';
      if(this.isEdit) url = '/api/admin/developer/editRecommendDeveloper';
      const res = await this.$post(url, this.ruleForm);
      const data = res.data;
      this.getTableData();
      this.centerDialogVisible = false;
    },
    // 点击添加
    clickAdd() {
      this.ruleForm = {};
      this.isEdit = false;
      this.centerDialogVisible = true;
    },
    handleAvatarSuccess(res, file) {
      // this.ruleForm.url = res.data.file_url_abs;
      this.$set(this.ruleForm, 'url', res.data.file_url_abs);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if(!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
      }
      if(!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // 点击删除
    clickDel(i, item) {
      const id = item.id
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await this.$post('/api/admin/developer/deleteRecommendDeveloper', { id });
        if(!res) return;
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.getTableData()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 点击编辑
    clickEdit(i, { uid, order, url, id }) {
      // 获取编辑信息, 现在自带的全, 暂时不用了
      // 接口：/api/admin/developer/getRecommendDeveloper
      // 参数：id int 列表每条记录的id（不是uid）
      this.ruleForm = { uid, order, url, id };
      this.isEdit = true;
      this.centerDialogVisible = true;
    },
    // 点击用户
    clickUID(i) {
      window.open(i.seo_uri)
    },
    // 根据状态显示图表样式
    tableRowClassName({ row, rowIndex }) {
      let className = ''
      if(row.p_status_name === '已结算') className = 'success-row'
      return className
    },
    // 格式化列表数据
    formatTableData(data) {
      return data.map(i => ({
        ...i,
      }))
    },
    // 获取列表数据
    async getTableData(page = 1) {
      this.tableData = []
      const res = await this.$post('/api/admin/developer/getRecommendList', { page, page_size: 9 }) // page_size 解决一个迷 bug, 后端要求添加
      // console.log(res)
      const data = res.data.list
      this.tableData = this.formatTableData(data)
      this.totalCount = Number(data.total)
      this.totalPage = data.totalPage
    }
  }
}
</script>

<style scoped>
.table {
  height: calc(100% - 40px);
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
