<template>
  <div class="fullHeight">
    <div class="searchBox whiteBlock">
      <!-- 混凝土拌合站——设备管理 -->
      <el-form :inline="true" ref="searchForm" :model="searchForm" size="medium">
        <el-form-item label="设备名称">
          <el-input v-model="searchForm.devName" placeholder="请输入"></el-input>
        </el-form-item>
        <!-- <el-form-item label="梁场名称">
          <el-input v-model="searchForm.belongBeamField" placeholder="请输入"></el-input>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" plain @click="getList">{{ $t('message.energyManage.waybill.query') }}</el-button>
          <el-button type="warning" plain @click="refresh">{{ $t('message.deviceManage.refresh') }}</el-button>
          <el-button type="primary" size="medium" @click="add">新增</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table_wrap whiteBlock">
      <el-table class="tables" :data="List">
        <!-- <el-table-column prop="image" label="照片" align="center">
          <template slot-scope="scope">
            <img
              :preview="scope.row.image[0] ? scope.row.image[0].url : []"
              :src="scope.row.image[0] ? scope.row.image[0].url : []"
              alt=""
              width="50px"
            />
          </template>
        </el-table-column> -->
        <el-table-column prop="devName" align="center" label="设备名称"></el-table-column>
        <el-table-column prop="devSn" align="center" label="设备编码"></el-table-column>
        <el-table-column prop="belongingMixingStation" align="center" label="所属拌合站"></el-table-column>
        <el-table-column prop="mixingPlantModel" align="center" label="拌合站型号"></el-table-column>
        <el-table-column prop="mixingStationLocation" align="center" label="拌合站位置"></el-table-column>
        <el-table-column prop="dutyUserName" align="center" label="负责人"></el-table-column>
        <el-table-column prop="phoneNumber" align="center" label="负责人电话">
          <!-- <template slot-scope="scope">{{scope.row.politicalStatus==2?'中共预备党员':'.'}}</template> -->
        </el-table-column>
        <!-- <el-table-column prop="joinPartyDeclaration" align="center" label="入党誓言">
          <template slot-scope="scope"
            ><div class="textStyle" :title="scope.row.joinPartyDeclaration">
              {{ scope.row.joinPartyDeclaration }}
            </div></template
          >
        </el-table-column> -->
        <el-table-column label="操作" align="center" width="250px">
          <template slot-scope="scope">
            <div class="tableBtns">
              <div class="operationText" @click.stop="openDetail(scope.row)">
                <i class="el-icon-tickets" style="color: #8dacfa; font-size: 16px; margin-right: 2px"></i>
                <span style="white-space: nowrap;">详情</span>
              </div>
              <div @click="edit(scope.row)" class="operationText">
                <img src="@/assets/images/icon-edit.png" width="15px" height="15px" />
                <span style="white-space: nowrap;">编辑</span>
              </div>
              <div @click="deleteDev(scope.row)" class="operationText">
                <img src="@/assets/images/icon-delete.png" width="15px" height="15px" />
                <span style="white-space: nowrap;">删除</span>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagerBox"
        @size-change="SizeChange"
        @current-change="CurrentChange"
        :current-page="pagInfo.pageNo"
        :page-sizes="$store.state.PAGESIZRS"
        :page-size="pagInfo.pageSize"
        layout="total, sizes, prev, pager, next"
        :total="Number(pagInfo.total)"
        background
      ></el-pagination>
    </div>
    <el-dialog :modal-append-to-body="false" @close="close" :title="title" :visible.sync="dialogShow" width="667px">
      <div class="dialog_content">
        <el-form size="medium" ref="addEditForm" :model="addEditForm" :rules="addEditRules" label-width="120px" class="dialogFormBox">
          <el-form-item label="设备名称" prop="devName">
            <el-input :disabled="isDetail" v-model="addEditForm.devName" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="设备编码" prop="devSn">
            <el-input :disabled="isDetail" v-model="addEditForm.devSn" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="所属拌合站" prop="belongingMixingStation">
            <el-input :disabled="isDetail" v-model="addEditForm.belongingMixingStation" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="拌合站型号" prop="mixingPlantModel">
            <el-input :disabled="isDetail" v-model="addEditForm.mixingPlantModel" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="拌合站位置" prop="mixingStationLocation">
            <el-input :disabled="isDetail" v-model="addEditForm.mixingStationLocation" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="负责人" prop="dutyUserId">
            <el-select v-model="addEditForm.dutyUserId" placeholder="请选择" :disabled="isDetail" @change="dutySelectChange">
              <el-option v-for="(item, index) in dutyList" :key="index" :label="item.realName" :value="item.userId"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="负责人电话" prop="phoneNumber">
            <el-input :disabled="isDetail" v-model="addEditForm.phoneNumber" placeholder="请输入"></el-input>
          </el-form-item>
          <!-- <el-form-item label="进场时间" prop="entryTime">
            <el-date-picker
              :disabled="isDetail"
              value-format="yyyy-MM-dd HH:mm:ss"
              v-model="addEditForm.entryTime"
              type="datetime"
              placeholder="请选择时间"
            >
            </el-date-picker>
          </el-form-item> -->

          <el-form-item label="上传图片">
            <el-upload
              :disabled="isDetail"
              :action="$store.state.UPLOADURL"
              list-type="picture-card"
              multiple
              name="files"
              :limit="1"
              accept=".png, .jpg, .jpeg"
              :file-list="fileUplodList"
              :on-exceed="(file, fileList) => handleExceed(file, fileList)"
              :on-success="(res, file) => handleSuccess(res, file)"
              :on-remove="(file, fileList) => handleRemove(file, fileList)"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>

          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" :disabled="isDetail" v-model="addEditForm.remark" placeholder="请输入"></el-input>
          </el-form-item>
          <div class="dialog-footer">
            <el-button class="cancleBtn" @click="dialogShow = false" icon="el-icon-circle-close" size="medium"
              >{{ $t('message.deviceManage.cancel') }}
            </el-button>
            <el-button type="primary" icon="el-icon-circle-check" @click="submit" size="medium"
              >{{ $t('message.deviceManage.save') }}
            </el-button>
          </div>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  stableWaterMixDevAdd,
  stableWaterMixDevDelete,
  stableWaterMixDevEdit,
  stableWaterMixDevPage,
  getCrewListDataApi // 负责人下拉
} from '@/assets/js/api/concreteMixStation.js'
import { checkPhone } from '@/assets/js/util.js'
export default {
  mounted() {},
  created() {
    this.getList()
    this.getDutyPerson()
  },
  data() {
    return {
      isDetail: false, //是否详情
      dutyList: [], // 负责人
      fileUplodList: [],
      title: '',
      dialogShow: false,
      pagInfo: {
        pageNo: 1, //页数
        pageSize: 10, //条数
        total: 0 //总条数
      },
      List: [],
      addEditForm: {
        belongingMixingStation: '',
        createDate: '',
        devName: '',
        devSn: '',
        image: '',
        mixingPlantModel: '',
        mixingStationLocation: '',
        dutyUserId: '',
        dutyUserName: '',
        phoneNumber: '',
        remark: '',
      },
      addEditRules: {
        devName: [
          {
            required: true,
            message: '必填',
            trigger: 'blur'
          }
        ],
        devSn: [
          {
            required: true,
            message: '必填',
            trigger: 'blur'
          }
        ],
        belongingMixingStation: [
          {
            required: true,
            message: '必填',
            trigger: 'blur'
          }
        ]
      },
      searchForm: {
        devName: ''
      }
    }
  },
  methods: {
    //  负责人下拉回调
    dutySelectChange(e) {
      const item = this.dutyList.find(item => item.userId === e);
      this.addEditForm.dutyUserName = item.realName
      console.log("下拉选择",e,this.addEditForm.dutyUserName);
    },
    //查询负责人下拉
    getDutyPerson() {
      let data = {
        projectSn: this.$store.state.projectSn,
      }
      getCrewListDataApi(data).then(res => {
        if (res.code == 200) {
          this.dutyList = res.result
          console.log('获取负责人下拉', this.dutyList)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    //查询列表
    getList() {
      stableWaterMixDevPage({
        pageNo: this.pagInfo.pageNo,
        pageSize: this.pagInfo.pageSize,
        projectSn: this.$store.state.projectSn,
        devName: this.searchForm.devName,
      }).then(result => {
        if (result.success) {
          // result.result.records.map(item => {
          //   if (item.image.includes('[')) {
          //     item.image = JSON.parse(item.image)
          //     if (item.image.length !== 0 && !item.image[0].url.includes(this.$store.state.FILEURL)) {
          //       item.image[0].url = this.$store.state.FILEURL + item.image[0].url
          //     }
          //   } else {
          //     let url = item.image

          //     if (url.length !== 0 && !url.includes(this.$store.state.FILEURL)) {
          //       item.image = [{}]
          //       item.image[0].url = this.$store.state.FILEURL + url
          //     }
          //   }
          // })
          this.List = result.result.records
          this.pagInfo.total = result.result.total
        }
      })
    },

    add() {
      this.title = '新增设备'
      this.dialogShow = true
      this.fileUplodList = []
      this.close()
    },

    edit(obj) {
      this.title = '编辑设备'
      this.dialogShow = true
      this.addEditForm = JSON.parse(JSON.stringify(obj))
      this.fileUplodList = JSON.parse(obj.image)
    },
    openDetail(obj) {
      this.title = '查看详情'
      this.dialogShow = true
      this.isDetail = true
      this.addEditForm = JSON.parse(JSON.stringify(obj))
      this.fileUplodList = JSON.parse(obj.image)
    },
    submit() {
      // if (this.addEditForm.contactNumber) {
      //   if (!checkPhone(this.addEditForm.contactNumber)) {
      //     this.$message.error('请输入正确的手机号码')
      //     return
      //   }
      // }
      let params = JSON.parse(JSON.stringify(this.addEditForm))
      params.projectSn = this.$store.state.projectSn
      params.image = JSON.stringify(this.fileUplodList)
      // if (this.fileUplodList.length > 0) {
      //   this.$message.error('请上传照片')
      //   return false
      // }
      this.$refs.addEditForm.validate(valid => {
        if (valid) {
          if (this.title == '新增设备') {
            stableWaterMixDevAdd(params).then(result => {
              if (result.success) {
                this.$message.success(result.message)
                this.getList()
              }
            })
          } else if (this.title == '编辑设备') {
            stableWaterMixDevEdit(params).then(result => {
              if (result.success) {
                this.$message.success(result.message)
                this.getList()
              }
            })
          }
          this.dialogShow = false
        } else {
          return false
        }
      })
    },
    deleteDev(obj) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          stableWaterMixDevDelete({ id: obj.id }).then(res => {
            if (res.success) {
              this.getList()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            } else {
              this.$message({
                type: 'error',
                message: res.message
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    // 删除
    handleRemove(file, fileList) {
      this.fileUplodList = fileList
    },
    handleExceed(file, fileList) {
      console.log("超出限制",file)
      this.$message.warning("只能上传一张图片")
    },
    handleSuccess(res, file, type) {
      if (res.status == 'SUCCESS') {
        this.fileUplodList.push({
          name: file.name,
          url: this.$store.state.FILEURL + file.response.data[0].imageUrl
        })
      }
    },
    close() {
      this.isDetail = false
      this.addEditForm = {}
      this.fileUplodList = []
      this.$nextTick(() => {
        this.$refs.addEditForm.clearValidate()
      })
    },
    SizeChange(val) {
      this.pagInfo.pageSize = val
      this.getList()
    },
    CurrentChange(val) {
      this.pagInfo.pageNo = val
      this.getList()
    },
    refresh() {
      this.searchForm = {}
      this.pagInfo.pageNo = 1 //页数
      this.pagInfo.pageSize = 10 //条数
      this.getList()
    }
  }
}
</script>
<style lang="less" scoped>
.tables2 {
  min-height: auto;
}
.textStyle {
  width: 140px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
