<template>
  <el-container class="content-height-fit">
    <inner-sidebar>
      <project-tree @node-click="handleTreeClick" />
    </inner-sidebar>
    <el-container class="resize-fit-container">
      <div class="app-container">
        <!-- 搜索框 -->
        <div class="filter-container blue-top-border">
          <el-select
            v-model="listQuery.deviceType"
            placeholder="设备类型"
            class="filter-item "
            clearable
            @clear="delValue('deviceType')"
            @change="getList"
          >
            <el-option
              v-for="item in deviceTypes"
              :key="item.key"
              :value="item.key"
              :label="item.name"
            />
          </el-select>
          <el-button
            v-waves
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            size="small"
            @click="handleFilter"
          >查询</el-button>
          <el-button
            v-if="$requirePermission('BSET.DVMG.C')"
            v-waves
            class="filter-item"
            type="primary"
            icon="el-icon-edit"
            size="small"
            @click="handleCreate"
          >新增监测因素</el-button>
        </div>
        <!-- 左侧列表 -->
        <div class="content-container" style="width: 45%">
          <el-table
            v-loading="listLoading"
            row-key="id"
            :data="list"
            border
            fit

            highlight-current-row
            style="width: 100%"
            height="calc(100vh - 276px)"
            row-style="getRowStyle"
            @row-click="leftHandleRowClick"
          >
            <div slot="empty">
              <span v-if="listQuery.projectId">没有数据</span>
              <span v-else>请选择项目</span>
            </div>
            <!-- 设备列表 -->
            <el-table-column label="序号" type="index" width="80" align="center" />
            <el-table-column label="名称" prop="name" :show-overflow-tooltip="true" align="center" />
            <el-table-column label="类型" prop="deviceTypeStr" align="center" />
            <el-table-column
              label="操作"
              align="center"
              width="200"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="{ row }">
                <el-button
                  v-if="$requirePermission('BSET.DVMG.C')"
                  v-waves
                  type="primary"
                  size="mini"
                  @click="handleItemCreate(row)"
                >新增监测</el-button>

                <el-button
                  v-if="$requirePermission('BSET.DVMG.U')"
                  type="primary"
                  size="mini"
                  @click="handleUpdate(row)"
                >修改</el-button>
                <el-button
                  v-if="$requirePermission('BSET.DVMG.D')"
                  size="mini"
                  type="danger"
                  @click="handleDelete(row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            :total="total"
            :skip-count.sync="listQuery.skipCount"
            :max-result-count.sync="listQuery.maxResultCount"
            @pagination="getList"
          />
        </div>
        <!-- 右侧详情 -->
        <div class="content-container" style="width: 55%;padding-bottom: 72px;">
          <el-table
            v-loading="listItemLoading"
            row-key="id"
            :data="itemList"
            border
            fit
            highlight-current-row
            style="width: 100%"
            height="calc(100vh - 276px)"
          >
            <div slot="empty">
              <span>没有数据</span>
            </div>
            <el-table-column label="物理量" align="center">
              <el-table-column label="名称" prop="name" :show-overflow-tooltip="true" align="center" />
              <el-table-column label="字段号" prop="field" :show-overflow-tooltip="true" align="center" />
              <el-table-column label="单位" prop="unit" :show-overflow-tooltip="true" align="center" />
              <el-table-column label="标准值" prop="standardValue" :show-overflow-tooltip="true" align="center" />
              <el-table-column
                label="操作"
                align="center"
                width="110"
                class-name="small-padding fixed-width"
              >
                <template slot-scope="{ row }">
                  <el-button
                    v-if="$requirePermission('BSET.DVMG.U')"
                    type="primary"
                    size="mini"
                    @click="handleItemUpdate(row)"
                  >修改</el-button>
                  <el-button
                    v-if="$requirePermission('BSET.DVMG.D')"
                    size="mini"
                    type="danger"
                    @click="handleItemDelete(row)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table-column>

          </el-table>
        </div>
        <el-dialog
          :title="textMap[dialogStatus]"
          :close-on-click-modal="false"
          :visible.sync="dialogFormVisible"
        >
          <el-form
            ref="dataForm"
            v-loading="formLoading"
            :rules="rules"
            :model="entity"
            label-position="right"
            label-width="120px"
          >
            <el-row :gutter="16">
              <el-col :span="12">
                <el-form-item label="名称" prop="name">
                  <el-input v-model="entity.name" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="类型" prop="deviceType">
                  <el-select v-model="entity.deviceType" class="w100p">
                    <el-option
                      v-for="item in deviceTypes"
                      :key="item.key"
                      :value="item.key"
                      :label="item.name"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button
              :disabled="formLoading"
              @click="dialogFormVisible = false"
            >取消</el-button>
            <el-button
              :disabled="formLoading"
              type="primary"
              @click="dialogStatus === 'create' ? createData() : updateData()"
            >确认</el-button>
          </div>
        </el-dialog>
        <el-dialog
          :title="textMap[dialogStatus]"
          :close-on-click-modal="false"
          :visible.sync="dialogItemFormVisible"
        >
          <el-form
            ref="dataItemForm"
            v-loading="formItemLoading"
            :rules="rules"
            :model="entityItem"
            label-position="right"
            label-width="120px"
          >
            <el-row :gutter="16">
              <el-col :span="12">
                <el-form-item label="名称" prop="name">
                  <el-input v-model="entityItem.name" :show-overflow-tooltip="true" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="字段号" prop="field">
                  <el-input v-model="entityItem.field" :show-overflow-tooltip="true" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="12">
                <el-form-item label="度量单位" align="left">
                  <el-input v-model="entityItem.unit" align="left" controls-position="right" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="标准值">
                  <el-input v-model="entityItem.standardValue" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="12">
                <el-form-item label="A级预警值" align="left">
                  <el-input v-model="entityItem.warningValueA" align="left" controls-position="right" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="B级预警值">
                  <el-input v-model="entityItem.warningValueB" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="16">
              <el-col :span="12">
                <el-form-item label="C级预警值" align="left">
                  <el-input v-model="entityItem.warningValueC" align="left" controls-position="right" style="width: 100%;" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="D级预警值" align="left">
                  <el-input v-model="entityItem.warningValueD" align="left" controls-position="right" style="width: 100%;" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button
              :disabled="formItemLoading"
              @click="dialogItemFormVisible = false"
            >取消</el-button>
            <el-button
              :disabled="formItemLoading"
              type="primary"
              @click="dialogStatus === 'create' ? createItemData() : updateItemData()"
            >确认</el-button>
          </div>
        </el-dialog>
      </div>
    </el-container>
  </el-container>
</template>

<script>
import * as interfaceApi from '@/api/early-warning-configuration.js'
import * as interfaceBillApi from '@/api/early-warning-configuration-bill.js'
import ProjectTree from '@/views/projects/components/ProjectTree'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import InnerSidebar from '@/components/InnerSidebar'

export default {
  name: 'EarlyWarningManageMng',
  directives: { waves },
  components: { Pagination, ProjectTree, InnerSidebar },
  data() {
    return {
      list: [],
      itemList: [],
      deviceTypes: [
        { key: 1, name: '架桥机' },
        { key: 2, name: '运梁车' }
      ],
      entity: {
        id: undefined,
        projectId: undefined,
        name: undefined,
        deviceType: undefined
      },
      entityItem: {
        id: undefined,
        earlyWarningConfigurationId: undefined,
        projectId: undefined,
        name: undefined,
        field: undefined,
        unit: undefined,
        standardValue: undefined,
        warningValueA: undefined,
        warningValueB: undefined,
        warningValueC: undefined,
        warningValueD: undefined
      },
      total: 0,
      listLoading: false,
      listItemLoading: false,
      listQuery: {
        projectId: undefined,
        deviceType: undefined,
        skipCount: 0,
        maxResultCount: 20
      },
      dialogFormVisible: false,
      dialogItemFormVisible: false,
      dialogStatus: '',
      formLoading: false,
      textMap: {
        update: '修改',
        create: '创建'
      },
      sections: [],
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { max: 64, message: '长度必须少于64个字符', trigger: 'blur' }
        ],
        deviceType: [
          { required: true, message: '请选择设备类型', trigger: 'blur' }
        ],
        field: [
          { required: true, message: '请输入字段号', trigger: 'blur' },
          { max: 64, message: '长度必须少于12个字符', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
  },
  mounted() {
    this.getList()
    // this.getItemList()
  },
  methods: {
    // 设置row样式
    getRowStyle(row, index) {
      let style = {}
      style = { 'background-color': '#000',
        'color': '#87b9f17d' }
      return style
    },

    // 树形事件
    handleTreeClick(data, node) {
      this.listQuery.projectId = data.id
      this.getList()
    },
    // 清空下拉
    delValue(parameter) {
      this.listQuery[parameter] = undefined
    },
    // 获取左侧数据
    getList() {
      this.listLoading = true
      interfaceApi
        .getList(this.listQuery)
        .then(res => {
          this.list = res.items
          if (this.list.length > 0) {
            this.getItemList(this.list[0])
          } else {
            this.itemList = []
          }
          this.total = res.totalCount
        })

        .finally(() => {
          this.listLoading = false
        })
    },
    getItemList(row) {
      this.listItemLoading = true
      interfaceBillApi
        .getList(this.listQuery)
        .then(res => {
          this.itemList = res.items
          this.total = res.totalCount
        })

        .finally(() => {
          this.listItemLoading = false
        })
    },

    // 点击左侧表格行时候自动刷新右侧数据
    leftHandleRowClick(row) {
      this.listItemLoading = true
      this.listQuery.EarlyWarningConfigurationId = row.id
      // this.listQuery.ProjectId = row.projectId

      interfaceBillApi
        .getList(this.listQuery)
        .then(res => {
          this.itemList = res.items
        })
        .finally(() => {
          this.listItemLoading = false
        }
        )
    },
    // 标题查询
    handleFilter() {
      this.listQuery.skipCount = 0
      this.getList()
    },
    // 创建左侧表单
    resetStation() {
      this.entity = {
        id: undefined,
        projectId: this.listQuery.projectId,
        name: undefined,
        deviceType: undefined
      }
    },
    // 初始化右侧表单
    resetStationItem() {
      this.entityItem = {
        id: undefined,
        earlyWarningConfigurationId: undefined,
        projectId: undefined,
        name: undefined,
        field: undefined,
        measureUnit: undefined,
        standardValue: undefined,
        warningValueA: undefined,
        warningValueB: undefined,
        warningValueC: undefined,
        warningValueD: undefined
      }
    },
    // 创建左侧列表添加点击事件
    handleCreate() {
      if (!this.listQuery.projectId) {
        this.verificationTips('请选择项目')
        return
      }
      this.resetStation()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.formLoading = false
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 表单提交数据
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.formLoading = true
          interfaceApi
            .create(this.entity)
            .then(() => {
              this.getList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
            .finally(() => {
              this.formLoading = false
            })
        }
      })
    },
    // 右侧提交数据
    createItemData() {
      this.$refs['dataItemForm'].validate(valid => {
        if (valid) {
          this.listItemLoading = true
          interfaceBillApi
            .create(this.entityItem)
            .then(() => {
              this.getList()
              this.listItemLoading = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
              this.getItemList()
            })
            .finally(() => {
              this.dialogItemFormVisible = false
            })
        }
      })
    },
    // 物理量修改提交方法
    updateItemData() {
      this.$refs['dataItemForm'].validate(valid => {
        if (valid) {
          this.listItemLoading = true
          interfaceBillApi
            .update(this.entityItem.id, this.entityItem)
            .then(() => {
              this.getItemList()
              this.listItemLoading = false
              this.$notify({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            })
            .finally(() => {
              this.dialogItemFormVisible = false
            })
        }
      })
    },
    // 提示信息对话框
    verificationTips(message) {
      this.$notify({
        title: '提示',
        message: message,
        type: 'error',
        duration: 2000
      })
    },

    // 左侧列表修改按钮点击事件
    handleUpdate(row) {
      this.entity = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.formLoading = false
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    // 左侧修改
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.entity.categoryName = this.deviceTypes.find(t => t.key === this.entity.deviceType).name
          const submitData = Object.assign({}, this.entity)
          this.formLoading = true
          interfaceApi
            .update(submitData.id, submitData)
            .then(() => {
              this.getList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
            })
            .finally(() => {
              this.formLoading = false
            })
        }
      })
    },
    // 左侧删除
    handleDelete(row) {
      this.$confirm('此操作将删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        interfaceApi
          .remove(row.id)
          .then(() => {
            this.getList()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
          .finally(() => {
            this.listLoading = false
          })
      })
    },

    // 创建物理量
    handleItemCreate(row) {
      this.resetStationItem()
      this.entityItem.projectId = row.projectId
      this.entityItem.earlyWarningConfigurationId = row.id
      this.dialogStatus = 'create'
      this.dialogItemFormVisible = true
      this.formItemLoading = false
      this.$nextTick(() => {
        this.$refs['dataItemForm'].clearValidate()
      })
    },
    // 物理量 修改按钮点击事件
    handleItemUpdate(row) {
      this.entityItem = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogItemFormVisible = true
      this.formItemLoading = false
      this.$nextTick(() => {
        this.$refs['dataItemForm'].clearValidate()
      })
    },

    // 右侧删除按钮
    handleItemDelete(row) {
      this.$confirm('此操作将删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listItemLoading = true
        interfaceBillApi
          .remove(row.id)
          .then(() => {
            this.getItemList({
              ProjectId: row.projectId,
              EarlyWarningConfigurationId: row.earlyWarningConfigurationId
            })
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            // this.getItemList()
          })
          .finally(() => {
            this.listItemLoading = false
          })
      })
    }

  }
}
</script>

<style  scoped>
.content-container{
  float: left;
}

</style>
