<template>
  <div>
    <el-card>
      <div style="display: flex;justify-content: space-between">
        <el-form
          ref="searchForm"
          :model="searchForm"
          label-width="80px"
          inline
        >
          <el-form-item
            label=""
            prop="input"
          >
            <el-input v-model="searchForm.name" clearable placeholder="设备类型">
              <el-button slot="append" icon="el-icon-search" @click="getDeviceTypeList(1)" />
            </el-input>
          </el-form-item>
        </el-form>
        <div class="buttons-group">
          <el-button type="primary" icon="el-icon-plus" @click="addRow">增加设备类型</el-button>
        </div>
      </div>

      <el-table
        :data="tableData"
        border
      >
        <el-table-column
          type="index"
          label="序号"
          width="50px"
          align="center"
        />
        <el-table-column
          prop="name"
          label="设备类型"
        />
        <el-table-column
          prop="instanceCount"
          label="设备实例数量"
          width="120px"
        />
        <el-table-column
          prop="description"
          label="描述"
        />
        <el-table-column
          label="操作"
          width="180px"
          align="center"
        >
          <template slot-scope="scope">
            <el-button type="text" @click="bindingDataModel(scope.row.id)">数据模型</el-button>
            <el-button type="text" @click="editItem(scope.row)">编辑</el-button>
            <el-popconfirm
              title="确定要删除此条记录吗？"
              style="margin-left: 10px"
              @onConfirm="deleteItem(scope.row.id)"
            >
              <el-button slot="reference" type="text">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        class="margin-top-20 text-align-right"
        :current-page="pageForm.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageForm.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <el-dialog
      :title="add ? '增加设备类型' : '编辑设备类型'"
      :visible.sync="dialogVisible"
      width="700px"
    >
      <el-form
        v-if="dialogVisible"
        ref="addForm"
        :model="addForm"
        label-width="100px"
        :rules="rules"
      >
        <el-form-item
          label="设备类型:"
          prop="name"
        >
          <el-input v-model="addForm.name" />
        </el-form-item>
        <el-form-item
          label="描述:"
          prop="description"
        >
          <el-input
            v-model="addForm.description"
            :autosize="{ minRows: 2, maxRows: 10}"
            type="textarea"
            :row="2"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveSystem">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="关联数据模型"
      :visible.sync="bindingVisible"
      width="700px"
    >
      <el-transfer
        v-model="bindingDataModelIds"
        :data="dataModelList"
        :titles="['未关联数据模型', '已关联数据模型']"
        :button-texts="['取消', '关联']"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelBind">取 消</el-button>
        <el-button type="primary" @click="binding">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDeviceTypeList,
  addDeviceType,
  updateDeviceType,
  deleteDeviceType,
  bindingDataModel,
  getDataModelByDeviceTypeId
} from '@/api/equipment-management/equipment-model'
import { getAllModel } from '@/api/data-visible/dashboard'

export default {
  name: 'EquipmentModel',
  props: {},
  data() {
    return {
      bindingDataModelIds: [],
      bindingVisible: false,
      searchForm: {
        name: null
      },
      add: true,
      dialogVisible: false,
      tableData: [],
      addForm: {
        name: null,
        description: null
      },
      pageForm: {
        pageSize: 10,
        pageNum: 1,
        total: 0
      },
      dataModelList: [],
      currentId: null,
      rules: {
        name: [
          { required: true, message: '请输入设备类型', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 50 个字符以内', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入设备描述', trigger: 'blur' },
          { min: 0, max: 200, message: '长度在 200 个字符以内', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  created() {
    this.getDeviceTypeList(1)
    getAllModel()
      .then(res => {
        this.dataModelList = res.data.map(v => {
          return {
            key: v.id,
            label: v.name
          }
        })
      })
      .catch(err => {
        this.$message.error(err.message)
      })
  },
  mounted() {},
  methods: {
    cancelBind() {
      this.bindingVisible = false
      this.bindingDataModelIds = []
    },
    binding() {
      const params = {
        deviceTypeId: parseInt(this.currentId),
        dataModelId: this.bindingDataModelIds.join(',')
      }
      bindingDataModel(params)
        .then(_ => this.$message.success('操作成功'))
        .then(_ => this.getDeviceTypeList(1))
        .then(_ => {
          this.bindingVisible = false
          this.bindingDataModelIds = []
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    bindingDataModel(id) {
      this.currentId = id
      getDataModelByDeviceTypeId({ id })
        .then(res => {
          if (res.data.length) {
            this.bindingDataModelIds = res.data.map(v => {
              return v.id
            })
          }
          this.bindingVisible = true
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    getDeviceTypeList(pageNum) {
      const params = {
        ...this.searchForm,
        pageNum,
        pageSize: this.pageForm.pageSize
      }
      getDeviceTypeList(params)
        .then(res => {
          const { records, total } = res.data
          this.tableData = records
          this.pageForm.total = total
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    resetForm() {
      this.$refs.searchForm.resetFields()
    },
    addRow() {
      this.addForm = {
        name: null,
        description: null
      }
      this.add = true
      this.dialogVisible = true
    },
    editItem(row) {
      this.add = false
      this.dialogVisible = true
      const { id, name, description } = row
      this.currentId = id
      this.addForm = {
        name,
        description
      }
    },
    deleteItem(id) {
      deleteDeviceType({ id })
        .then(_ => this.$message.success('操作成功'))
        .then(_ => this.getDeviceTypeList(1))
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    saveSystem() {
      this.$refs.addForm.validate()
        .then(_ => {
          return { ...this.addForm }
        })
        .then(params => {
          if (!this.add) { params.id = this.currentId }
          return this.add ? addDeviceType(params) : updateDeviceType(params)
        })
        .then(_ => this.$message.success('操作成功'))
        .then(_ => this.getDeviceTypeList(1))
        .then(_ => {
          this.dialogVisible = false
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    handleSizeChange(val) {
      this.pageForm.pageSize = val
      this.getDeviceTypeList(1)
    },
    handleCurrentChange(val) {
      this.pageForm.pageNum = val
      this.getDeviceTypeList(val)
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
