<template>
  <div v-if="pageLoading" class="resi-container">
    <el-card class="resi-card-table">
      <div class="resi-row-btn">
        <el-select
        v-model="value"
          placeholder="请选择"
          size="small"
          clearable
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-select
        v-model="value"
          placeholder="请选择"
          size="small"
          clearable
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-button type="primary" size="mini" @click="handleSearch">查询</el-button>
      </div>
      <el-table
        :data="tableData"
        row-key="id"
        v-loading="tableLoading"
        border
        style="width: 100%"
        class="resi-table"
      >
        <el-table-column label="序号" type="index" align="center" width="50">
        </el-table-column>
        <el-table-column
          v-for="item in tableHeader"
          :key="item.columnName"
          :prop="item.columnName"
          :label="item.label"
          align="center"
          width="180"
        >
          <template slot-scope="scope">
            <el-image
            v-if="filterImage(item.columnName)"
            style="width: 70px; height: 70px"
            :src="handleFilterSpan(scope.row, item) "
            fit="fill"></el-image>
            <span v-else>{{ handleFilterSpan(scope.row, item) }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="120">
          <template slot-scope="scope">
            <el-button
              @click="handleLook(scope.row)"
              type="text"
              size="small"
              class="btn-color-look"
              >{{(scope.row.status === 'show'&&'隐藏') || '显示'}}</el-button
            >
            <el-button
                @click="handleEdit(scope.row)"
                type="text"
                size="small"
                class="btn-color-edit"
                >编辑</el-button
              >
          </template>
        </el-table-column>
      </el-table>
      <div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-sizes="[20, 50, 100, 200]"
          :page-size="pageSize"
          layout="sizes, prev, pager, next"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <el-dialog
      title="居民类别配置"
      :visible.sync="dialogVisible"
      width="40%"
      append-to-body
      :close-on-click-modal="false"
      :before-close="handlerCancle"
    >
      <el-form label-width="100px" :model="form" :rules="rules" ref="ruleForm">
        <el-form-item label="类别名称">
          <el-input v-model="form.label" size="small" style="width: 180px;" disabled></el-input>
        </el-form-item>
        <el-form-item label="管理平台图标" prop="managementIcon">
          <el-upload class="avatar-uploader"
            :action="uploadUlr"
            :data="{customerId:customerId}"
            :show-file-list="false"
            :on-success="(response, file, fileList) => handleImgSuccess('managementIcon', response, file, fileList)"
            :before-upload="beforeImgUpload">
            <img v-if="form.managementIcon"
              :src="form.managementIcon"
              style="width:70px;height:70px"
              class="function-icon">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="数据平台图标" prop="dataIcon">
          <el-upload class="avatar-uploader"
            :action="uploadUlr"
            :data="{customerId:customerId}"
            :show-file-list="false"
            :on-success="(response, file, fileList) => handleImgSuccess('dataIcon', response, file, fileList)"
            :before-upload="beforeImgUpload">
            <img v-if="form.dataIcon"
              :src="form.dataIcon"
              style="width:70px;height:70px"
              class="function-icon">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="房屋显示图标" prop="houseShowIcon">
          <el-upload class="avatar-uploader"
            :action="uploadUlr"
            :data="{customerId:customerId}"
            :show-file-list="false"
            :on-success="(response, file, fileList) => handleImgSuccess('houseShowIcon', response, file, fileList)"
            :before-upload="beforeImgUpload">
            <img v-if="form.houseShowIcon"
              :src="form.houseShowIcon"
              style="width:70px;height:70px"
              class="function-icon">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="是否预警">
          <el-switch v-model="form.warn"></el-switch>
        </el-form-item>
        <el-form-item label="黄色预警">
          <el-input-number v-model="form.level1" :min="0" size="small" label="描述文字"></el-input-number> 人/楼宇
        </el-form-item>
        <el-form-item label="红色预警">
          <el-input-number v-model="form.level2" :min="0" size="small" label="描述文字"></el-input-number> 人/楼宇
        </el-form-item>
      </el-form>
      <div class="resi-btns">
        <el-button size="small" @click="handlerCancle">取消</el-button>
        <el-button
          type="primary"
          size="small"
          :loading="btnLoading"
          @click="handleSUbmit"
          >提交</el-button
        >
      </div>
    </el-dialog>

  </div>
</template>

<script>
import axios from 'axios'
import Sortable from 'sortablejs'
export default {
  data() {
    return {
      tableLoading: false,
      btnLoading: false,
      disabled: false,
      pageLoading: false,
      dialogVisible: false,
      uploadUlr: window.SITE_CONFIG['apiURL'] + '/oss/file/uploadqrcodeV2',
      currentPage: 1,
      pageSize: 20,
      total: null,
      conditions: [],
      tableData: [],
      value: '',
      options: [
        {
          label: '是',
          value: 1
        },{
          label: '否',
          value: 2
        }
      ],
      tableHeader: [
        {
          label: '类别名称',
          columnName: 'label'
        }, {
          label: '管理平台图标',
          columnName: 'managementIcon'
        }, {
          label: '数据平台图标',
          columnName: 'dataIcon'
        }, {
          label: '房屋显示图标',
          columnName: 'houseShowIcon'
        }, {
          label: '状态',
          columnName: 'status',
          options: [{
            value: 'show',
            label: '显示'
          }, {
            value: 'hidden',
            label: '隐藏'
          }]
        }, {
          label: '是否预警',
          columnName: 'warn',
          options: [{
            value: '1',
            label: '是'
          }, {
            value: '0',
            label: '否'
          }]
        }, {
          label: '黄色预警',
          columnName: 'level1'
        }, {
          label: '红色预警',
          columnName: 'level2'
        }
      ],
      customerId: '',
      form: {
        label: '',
        dataIcon: '',
        managementIcon: '',
        houseShowIcon: '',
        warn: '',
        level1: '',
        level2: ''
      },
      rules: {
        managementIcon: [{ required: true, message: '管理平台图标不能为空', trigger: 'blur' }],
        dataIcon: [{ required: true, message: '数据平台图标不能为空', trigger: 'blur' }],
        houseShowIcon: [{ required: true, message: '房屋显示图标不能为空', trigger: 'blur' }]
      }
    }
  },
  async created() {
    this.customerId = localStorage.getItem('customerId')
    this.getTableData()
    this.pageLoading = true
  },
  mounted() {
    this.rowDrop()
  },
  methods: {
    rowDrop() {
      const tbody = document.querySelector('.el-table__body-wrapper tbody')
      const _this = this
      Sortable.create(tbody, {
        onEnd({ newIndex, oldIndex }) {
          const currRow = _this.tableData.splice(oldIndex, 1)[0]
          _this.tableData.splice(newIndex, 0, currRow)
          console.log('rowdrap', newIndex, oldIndex)
          if (newIndex || newIndex === 0) _this.sortData()
          // 
        }
      })
    },
    computedWidth(label) {
      const wd = 20 * label.length
      return wd > 80 ? wd : 80
    },
    filterImage(item) {
      const arr = ['managementIcon', 'dataIcon', 'houseShowIcon']
      return arr.includes(item)
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageSize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.currentPage = val
      this.getTableData()
    },
    handleFilterSpan(row, item) {
      let _val = ''
      if (item.options && item.options.length > 0) {
        item.options.forEach((n) => {
          if (n.value === row[item.columnName]) _val = n.label
        })
      }
      return _val || row[item.columnName]
    },
    handleSearch(val) {
      console.log('searchhh--', val)
      this.currentPage = 1
      this.conditions = val
      this.getTableData()
    },
    
    handlerCancle() {
      this.dialogVisible = false
    },
    beforeImgUpload (file) {
      const isPNG = (file.type === 'image/png') || (file.type === 'image/jpeg')
      const isLt1M = file.size / 1024 / 1024 < 1

      if (!isPNG) {
        this.$message.error('上传图片只能是 PNG 格式!')
      }
      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过 1MB!')
      }
      return isPNG && isLt1M
    },
    handleImgSuccess (type, res, file) {
      if (res.code === 0 && res.msg === 'success') {

        console.log('type', type)
        console.log('res.data.url', res.data.url)
        this.form[type] = res.data.url

      } else {
        this.$message.error(res.msg)
      }
    },
    async handleLook(row) {
      const _show = {
        show: 'hidden',
        hidden: 'show'
      }
      const params = {
        id: row.id,
        status: _show[row.status]
      }
      this.$http
        .post('/oper/customize/resicategorystatsconfig/updatestatus', params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            this.getTableData()
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },
    async handleEdit(row) {
      
      this.form = { ...row }
      this.dialogVisible = true
    },
    async handleSUbmit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.btnLoading = true
          const _form = {
            ...this.form,
            warn: (this.form.warn && 1) || 0
          }
          await this.$http
            .post('/oper/customize/resicategorystatsconfig/update', _form)
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg)
              } else {
                this.dialogVisible = false
                this.getTableData()
              } 
            })
            .catch(() => {
              return this.$message.error('网络错误')
            })
            this.btnLoading = false
        } else {
          console.log('error submit!!');
          return false;
        }
      });
      
    },
    handleDel(row) {
      let params = {
        formCode: 'resi_base_info',
        icResiUserId: row.icResiUserId
      }
      console.log('row1', row)
      this.$http
        .post('/epmetuser/icresiuser/delete', params)
        .then(({ data: res }) => {
          console.log('row2', row)
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            console.log('row3', row)
            this.$message.success('删除成功')
            this.getTableData()
          }
        })
        .catch((err) => {
          console.log('row4', err)
          return this.$message.error('网络错误')
        })
    },
    sortData() {
      const _data = this.tableData.map((item, index)=> {
        return {
          id: item.id,
          sort: index
        }
      })
      this.$http
        .post('/oper/customize/resicategorystatsconfig/updatesort', _data)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            // this.getTableData()
          }
        })
        .catch((err) => {
          console.log('row4', err)
          return this.$message.error('网络错误')
        })
    },
    getTableHeader() {
      this.$http
        .post('/oper/customize/icform/tableheaders', {
          formCode: 'resi_base_info'
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            this.tableHeader = res.data
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },
    async getTableData() {
      this.tableLoading = true
      let params = {
        // formCode: 'resi_base_info',
        pageNo: this.currentPage,
        pageSize: this.pageSize
      }
      await this.$http
        .post('/oper/customize/resicategorystatsconfig/list', params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            this.tableData = res.data
            this.total = res.data.total
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
      this.tableLoading = false
    }
    
  }
}
</script>

<style lang="scss" scoped>
.resi-container .resi-card-table {
  ::v-deep .el-table th {
    color: #fff;
    background-color: rgba(33, 149, 254, 1);
    border-right: 1px solid rgba(33, 149, 254, 1);;
  }
}
.resi-table {
  ::v-deep .el-button--text {
    text-decoration: underline;
  }
  ::v-deep .btn-color-del {
    margin-left: 10px;
    color: rgba(213, 16, 16, 1);
  }
  ::v-deep .btn-color-edit {
    color: rgba(0, 167, 169, 1);
  }
}
</style>

<style lang="scss" scoped>
.resi-row-btn {
  display: flex;
  margin-bottom: 13px;
  ::v-deep .el-button {
    // margin-left: 10px;
    border: 0;
  }
  ::v-deep .el-select {
    margin-right: 10px;
  }
}
.avatar-uploader {
  ::v-deep
  .el-upload {
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar {
    width: 70px;
    height: 70px;
    display: block;
  }
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    font-size: 28px;
    color: #8c939d;
    width: 70px;
    height: 70px;
    line-height: 70px;
    text-align: center;
  }
}
  
  

.resi-btns {
  margin-top: 20px;
  text-align: center;
}
</style>
