<template>
  <el-card shadow="never" class="roomBox">
    <div>
      <div slot="header" class="roomHeadSpan">
        <span>会客厅管理</span>
        <el-button
          style="float: right; padding: 5px 5px"
          type="primary"
          icon="el-icon-circle-plus-outline"
          @click="addRooom"
          >新增</el-button
        >
      </div>
      <el-table border style="width: 100%" :data="tableData">
        <el-table-column
          label="会客厅名称"
          prop="name"
          header-align="center"
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="房间号"
          prop="num"
          header-align="center"
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="面积（m²）"
          prop="area"
          header-align="center"
          align="center"
        ></el-table-column>
        <el-table-column
          label="可容纳人数（人）"
          prop="capacity"
          header-align="center"
          align="center"
        ></el-table-column>
        <el-table-column
          :label="$t('handle')"
          fixed="right"
          header-align="center"
          align="center"
          width="150"
        >
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="taskDetails(scope.row)"
              >详情</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="taskUpdate(scope.row)"
              >{{ $t('update') }}</el-button
            >
            <el-button
              type="text"
              size="small"
              @click="taskDelete(scope.row)"
              >{{ $t('delete') }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
        :destroy-on-close="true"
        :close-on-click-modal="false"
        @close="outDialog"
        :title="
          flge === 'add'
            ? '会客厅新增'
            : flge === 'look'
            ? '会客厅详情'
            : '会客厅修改'
        "
        :visible.sync="dialogFormVisible"
      >
        <el-form
          :model="ruleForm"
          :label-position="labelPosition"
          size="small"
          :rules="rules"
          ref="ruleForm"
          :disabled="flge === 'look' ? true : flge === 'edit' ? false : false"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="会客厅名称"
                prop="name"
                :label-width="formLabelWidth"
              >
                <el-input v-model="ruleForm.name" style="width: 90%"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="房间号"
                prop="num"
                :label-width="formLabelWidth"
              >
                <el-input v-model="ruleForm.num" style="width: 90%"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="会客厅面积(m²)"
                prop="area"
                :label-width="formLabelWidth"
              >
                <el-input
                  v-model.number="ruleForm.area"
                  style="width: 90%"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="可容纳人数(人)"
                prop="capacity"
                :label-width="formLabelWidth"
              >
                <el-input
                  v-model.number="ruleForm.capacity"
                  style="width: 90%"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item
                label="描述"
                prop="description"
                :label-width="formLabelWidth"
              >
                <el-input
                  type="textarea"
                  v-model="ruleForm.description"
                  style="width: 96%"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item
                label="会客厅图片"
                prop="pic"
                :label-width="formLabelWidth"
              >
                <div v-if="flge != 'look'">
                  <span slot="tip" class="el-upload__tip">
                    支持图片jpg、jpeg、png类型，只能上传一张图片且不超过100MB
                  </span>
                </div>
                <!-- :file-list="fileList" -->
                <el-upload
                  v-if="flge != 'look'"
                  class="upload-demo"
                  accept=".jpg, .jpeg, .png"
                  :action="apiURL"
                  :on-preview="handlePictureCardPreview"
                  :on-success="onSuccess"
                  :on-remove="onRemove"
                  :on-exceed="beforeUpload"
                  :file-list="fileList"
                  list-type="picture-card"
                  :limit="1"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible" append-to-body>
                  <img width="100%" :src="picImg" alt="" />
                </el-dialog>
                <div
                  class="block"
                  style="width: 15rem; height: 10rem"
                  v-if="flge == 'look' && picImg != ''"
                >
                  <el-image :src="picImg"></el-image>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <!-- <el-button @click="dialogFormVisible = false">取 消</el-button> -->
          <el-button
            type="primary"
            v-if="flge != 'look'"
            @click="submitForm('ruleForm', flge)"
            >保 存</el-button
          >
        </div>
      </el-dialog>
      <el-pagination
        :current-page="page"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="limit"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
  </el-card>
</template>
<script>
import Cookies from 'js-cookie'
export default {
  data () {
    // let validatorImg = (rule, value, callback) => {
    //   console.log(value, 11111111)
    //   //验证器
    //   if (!this.checkImgSuccess) {
    //     //为true代表图片在  false报错
    //     callback(new Error('请上传图片'))
    //   } else {
    //     callback()
    //   }
    // }
    return {
      apiURL:
        window.SITE_CONFIG.apiURL + '/upload?token=' + Cookies.get('ucsToken'),
      labelPosition: 'left',
      dialogFormVisible: false,
       // dialogImageUrl: '',
      ruleForm: {
        name: '',
        num: '',
        area: 0,
        capacity: '',
        pic: '',
        id: ''
      },
      limit: 10,
      page: 1,
      total: 0,
      picImg: '',
      tableData: [],
      fileList: [],
      rules: {
        name: [
          { required: true, message: '请输入会客厅名称', trigger: 'blur' },
          { min: 1, trigger: 'blur' }
        ],
        area: [
          { required: true, message: '请输入会客厅面积', trigger: 'blur' }
          // { min: 1, message: '请输入数字', type: 'number', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请填写描述内容', trigger: 'blur' },
          {
            min: 1,
            max: 255,
            message: '长度在 1 到 255 个字符',
            trigger: 'blur'
          }
        ]
      },
      formLabelWidth: '120px',
      checkImgSuccess: true,
      dialogVisible: false,
      flge: ''
    }
  },
  mounted () {
    this.queryData()
  },
  methods: {
    // 页面查询接口
    queryData () {
      this.$http
        .get(`/meeting/page?limit=${this.limit}&page=${this.page}`)
        .then(({ data: res }) => {
          this.total = res.data.total
          this.tableData = res.data.list
        })
    },
    // 分页
    handleSizeChange (val) {
      this.limit = val
      this.queryData()
    },
    handleCurrentChange (val) {
      this.page = val
      this.queryData()
    },
    // 新增
    addRooom () {
      this.dialogFormVisible = true
      this.flge = 'add'
      this.ruleForm = {}
      this.fileList = []
    },
    handlePictureCardPreview (file) {

      this.picImg = file.url
      this.dialogVisible = true
    },
    // 上传个数限制
    beforeUpload (file, fileList) {
     this.$message.error('最多只能上传一张图片！')
    },
    // 图片上传成功时钩子
    onSuccess (response, file, fileList) {
      const isLt2M = file.size / 1024 / 1024 < 100
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过100MB！')
        this.fileList = []
      } else {
        this.ruleForm.pic = response.data
        //   this.$refs.ruleForm.clearValidate() //上传成功清除校验
        this.checkImgSuccess = true
      }
    },
    // 图片删除时钩子
    onRemove (file, fileList) {
      this.$nextTick(() => {
        if (fileList.length == 0) {
          this.checkImgSuccess = false // 检查图片是否加载成功
          //   this.$refs.ruleForm.validate() //删除图片,重新触发校验
        }
      })
    },
    // 保存
    submitForm (formName, i) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (i === 'add') {
            this.dialogFormVisible = false
            this.$http.post('/meeting', this.ruleForm).then(({ data: res }) => {
              if (res.msg === 'success') {
                this.queryData()
              } else {
                this.$message.error('保存接口调用失败')
              }
            })
          } else if (i === 'edit') {
            this.dialogFormVisible = false
            this.$http.put('/meeting', this.ruleForm).then(({ data: res }) => {
              this.ruleForm = res.data
              const imgUrl = { name: res.data.name, url: res.data.pic }
              this.fileList.push(imgUrl)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 详情
    taskDetails (row) {
      this.ruleForm = {}
      this.fileList = []
      this.flge = 'look'
      this.$http.get(`/meeting/${row.id}`).then(({ data: res }) => {
        this.dialogFormVisible = true
        this.ruleForm = res.data
        if (res.data.pic != null) {
          //   let imgUrl = { name: res.data.name, url: res.data.pic }
          //   this.fileList.push(imgUrl)
          this.picImg = res.data.pic
        } else {
          this.picImg = ''
        }
      })
    },
    // 修改
    taskUpdate (row) {
      this.dialogFormVisible = true
      this.fileList = []
      this.flge = 'edit'
      this.ruleForm = row
      if (row.pic != null) {
        const imgUrl = { name: row.name, url: row.pic }
        this.fileList.push(imgUrl)
      } else {
        this.fileList = []
      }
    },
    // 删除图片
    taskDelete (row) {
      this.$confirm('此操作将永久删除该会客厅, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$http.put('/meeting', { delFlag: 1, id: row.id }).then(() => {
            this.queryData()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 监听关闭按钮时间
    outDialog () {}
  }
}
</script>
<style scoped lang="scss">
.roomBox {
  min-height: calc(calc(100vh - 50px - 38px - 30px));
  .roomHeadSpan {
    font-weight: 600;
  }
}
::v-deep .el-dialog__footer {
  text-align: center;
}
::v-deep .el-image {
  width: 100%;
  height: 100%;
}
</style>
