<template>
  <div>
    <el-dialog
      title="常用语配置"
      :visible.sync="CommonFormDia"
      width="85%"
      height="600px"
      :before-close="handleClose"
    >
      <div style="margin: 10px 0">
        <el-button
          size="mini"
          icon="el-icon-plus"
          type="primary"
          @click="addAcount"
          >添加</el-button
        >
        <el-button
          size="mini"
          icon="el-icon-delete"
          type="danger"
          @click="deletAcount"
          >删除</el-button
        >
      </div>

      <el-table
        :row-key="getRowKey"
        ref="multipleSelection"
        border
        :data="informations.data"
        :row-style="{height: '61px'}"
        style="width: 100%"
        @selection-change="handleChanges"
        :header-cell-style="{'text-align': 'center'}"
        :cell-style="{'text-align': 'center'}"
      >
        <el-table-column type="selection" width="55" :reserve-selection="true">
        </el-table-column>
        <el-table-column type="index" width="55" label="序号" prop="conuntNum">
        </el-table-column>
        <el-table-column
          v-for="(v, key) in informations.rowData"
          :key="key"
          :prop="v.field"
          :label="v.title"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.isSet">
              <el-input
                size="mini"
                placeholder="请输入巡检对象异常的内容"
                v-model="informations.sel[v.field]"
                type="textarea"
                rows="2"
              >
              </el-input>
            </span>
            <span v-else>{{ scope.row[v.field] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button
              :type="scope.row.isSet ? 'primary' : 'warning'"
              style="width: 80px"
              size="mini"
              @click="pwdChange(scope.row, scope.$index, true)"
            >
              {{ scope.row.isSet ? '保存' : '修改' }}
            </el-button>
            <!-- <span
              class="el-tag el-tag--info el-tag--mini"
              style="cursor: pointer"
              @click="pwdChange(scope.row, scope.$index, true)"
            >
              {{ scope.row.isSet ? '保存' : '修改' }}
            </span>
            <span
              v-if="!scope.row.isSet"
              class="el-tag el-tag--danger el-tag--mini"
              style="cursor: pointer"
            >
              删除
            </span>
             <span
              v-else
              class="el-tag el-tag--mini"
              style="cursor: pointer"
              @click="pwdChange(scope.row, scope.$index, false)"
            >
              取消
            </span> -->
          </template>
        </el-table-column>
      </el-table>

      <!-- <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="pwdChange()">保 存</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </span> -->
    </el-dialog>
  </div>
</template>
<script>
import dsmInsPosition from '@/api/resIns/dsmInsPosition.js'
import req from '@/request.js'
export default {
  name: 'deviceForm-dialog',
  props: {
    CommonFormDia: {
      type: Boolean,
      default: false,
    },
    pId: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      //数据
      informations: {
        sel: null, //是否选中行

        rowData: [
          //一行的数据
          {field: 'content', title: '巡检对象结果异常描述'},
        ],
        data: [], //添加数据后展示的地
      },
      isSet: false, //切换状态
      total: 0,
      multipleSelection: [], //id
      rules: {
        content: [
          {
            required: true,
            message: '请输入巡检对象结果常用描述',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  created() {
    // this.getDetailInfo()
    // this.getList()
    // this.getSysDict()
    this.getDeviant()
  },
  methods: {
    //获取数据
    getDeviant() {
      dsmInsPosition.deviant({positionId: this.pId}, (res) => {
        this.informations.data = res.value
        this.total = res.value.length
        this.informations.data.forEach((item) => {
          item.isSet = false
        })
      })
    },
    //读取表格数据
    readMasterUser() {
      //根据实际情况，自己改下啊
      this.informations.rowData.map((i) => {
        i.id = this.multipleSelection
        i.isSet = false //给后台返回数据添加`isSet`标识
        return i
      })
    },
    //添加
    addAcount() {
      //当我们第二次点击的时候，会判断是否为真，如果为真，表示没有填数据，弹出框
      //第一次点击的时候，data为空数据，是不会循环，直接跳过的。
      for (let i of this.informations.data) {
        //查找该数据，是否保存，如果没保存，就弹出框提示
        // console.log(this.informations.data)
        if (i.isSet) return this.$message.warning('请先保存当前编辑项')
      }
      this.conuntNum++
      let j = {
        content: '',
        // sn: 0,
        isSet: true,
        positionId: this.pId,
      }
      this.informations.data.push(j)
      this.informations.sel = JSON.parse(JSON.stringify(j))
    },
    //保存
    //点击保存或者修改
    pwdChange(row, index, cg) {
      // 点击修改 判断是否已经保存所有操作
      for (let i of this.informations.data) {
        if (i.isSet && i.id != row.id) {
          this.$message.warning('请先保存当前编辑项')
          return false
        }
      }
      //提交数据
      if (row.isSet) {
        if (!row.id) {
          console.log('新数据')
          let data = JSON.parse(JSON.stringify(this.informations.sel))
          console.log(this.informations.sel['content'])
          // data.sn = index + 1
          //上传数据
          dsmInsPosition.addAbnormal(data, (response) => {
            if (response.state) {
              this.$message({
                type: 'success',
                message: '新增成功',
                duration: 2000,
              })
              this.$emit('refList')
              this.$set(this.informations.data)
              row.isSet = false
              this.getDeviant()
            }
          })
        } else {
          console.log('更新数据')
          //修改数据
          let data = JSON.parse(JSON.stringify(this.informations.sel))
          dsmInsPosition.Revise(data, (response) => {
            if (response.state) {
              console.log('更新成功', data, this.informations.data)
              this.$set(this.informations.data)
              row.isSet = false
              this.getDeviant()
            }
          })
        }
        //然后这边重新读取表格数据
        // this.readMasterUser()
      } else {
        row.isSet = false
        this.informations.sel = JSON.parse(JSON.stringify(row))
        this.informations.data[index].isSet = true
        this.$set(this.informations.data)
        row.isSet = true
        // row.isSet = true
        // this.informations.data[index].isSet = true
      }
    },
    //关闭
    // closeFormDiao() {
    //   this.showFormDia = false
    //   this.getDeviant()
    // },
    //删除
    deletAcount() {
      let multipleSelection = []

      this.multipleSelection.forEach((item) => {
        if (item.content) {
          multipleSelection.push(item.id)
        } else {
          this.$confirm('是否取消操作？', '提示', {
            confirmButtonText: '确 定',
            cancelButtonText: '取 消',
            type: 'warning',
          }).then(() => {
           this.informations.data.pop();
            // this.getDeviant()
          })

          multipleSelection = []
        }
      })
      if (multipleSelection.length) {
        this.$confirm('确定删除选中数据？', '提示', {
          confirmButtonText: '确 定',
          cancelButtonText: '取 消',
          type: 'warning',
        })
          .then(() => {
            dsmInsPosition
              .removeAbn(multipleSelection, (res) => {
                if (res.state) {
                  this.$notify({
                    type: 'success',
                    message: '删除成功',
                    duration: 2000,
                  })
                  this.$refs.multipleSelection.clearSelection()
                  this.getDeviant()
                }
              })
              .catch((res) => {
                this.$notify({
                  type: 'error',
                  message: res.message,
                  duration: 2000,
                  offset: 80,
                })
                this.getDeviant()
              })
          })
          .catch(() => {})
      }
    },
    arrayRepeat(array1, array2) {
      var result = []
      for (var i = 0; i < array2.length; i++) {
        var obj = array2[i]
        var num = obj.ident
        var isExist = false
        for (var j = 0; j < array1.length; j++) {
          var aj = array1[j]
          var n = aj.ident
          if (n === num) {
            isExist = true
            break
          }
        }
        if (!isExist) {
          result.push(obj)
        }
      }
      return result
    },
    //指定一个key标识这一行的数据
    getRowKey(row) {
      return row.id
    },
    handleChanges(val) {
      this.multipleSelection = val.map((item, index) => {
        return item
      })
    },

    handleClose() {
      this.params = {
        content: null,
      }
      this.$emit('closeFormDiao')
    },
    // goInfo(e) {
    //   dsmInsPosition.addAbnormal(
    //     {...this.informations.data[sn]},
    //     (response) => {
    //       if (response.state) {
    //         this.$notify({
    //           type: 'success',
    //           message: '新增成功',
    //           duration: 2000,
    //           // offset: 80
    //         })
    //         this.$emit('closeFormDiao')
    //         this.$emit('refList')
    //       } else {
    //       }
    //     }
    //   )

    // if (this.title === '修改') {
    // dsmInsPosition.upData(this.params, (response) => {
    // if (response.state) {
    //   this.$notify({
    //     type: 'success',
    //     message: '修改成功',
    //     duration: 2000,
    //     // offset: 80
    //   })
    //   this.$emit('closeFormDiao')
    //   this.$emit('refList')
    // } else {
    // }
    // })
    // },
    // } else {
    //   return false
    // }
  },
}
</script>
<style lang="scss" scoped>
.el-divider--horizontal {
  margin: 24px 0 5px 0;
  height: 7px !important;
  background: #88b4dd !important;
  .el-divider__text {
    font-size: 16px !important;
  }
}

// ::v-deep .el-input__inner {
//   border: 1px solid orange;
// }
// ::v-deep .el-textarea__inner {
//   border: 1px solid orange;
// }
</style>
