<template>
  <div class="videoManage manage-page">
    <div class="flex-view flex-title">
      <div class="table-title">
        <img src="../../assets/manageImg/userInfoControl.png" alt=""> {{ $t('userManagement.title') }}
      </div>
      <div class="table-title-btn blue" @click="openModel({}, 0)">
        <img src="../../assets/manageImg/add-btn.png" alt="">{{$t('text.add')}}
      </div>
    </div>
    <div class="flex-view ">
      <div class="manage-input  w-180">
        <span class="input-title">{{ $t('userManagement.tableHeaders.nickname') }}:</span>
        <input class="search-input" type="text" v-model="searchName" placeholder="">
      </div>
      <div class="table-title-btn blue" @click="dataInit">
        {{$t('text.search')}}
      </div>
    </div>
    <div class="table-view">
      <el-table :data="tableList" :row-class-name="tableRowClassName" height="540" style="width: 100%">
        <el-table-column prop="userName" v-model="nowData.userName" :label="$t('userManagement.tableHeaders.username')">
        </el-table-column>
        <el-table-column prop="nickName" v-model="nowData.nickName" :label="$t('userManagement.tableHeaders.nickname')">
        </el-table-column>
        <el-table-column prop="phonenumber" v-model="nowData.phonenumber" :label="$t('userManagement.tableHeaders.phone')">
        </el-table-column>
        <el-table-column :label="$t('text.operations')">
          <template slot-scope="scope">
            <div class="table-flex">
              <div class="table-operate blue" @click="openModel(scope.row, 1)">
                <img src="../../assets/manageImg/table-edit.png" alt="">{{$t('text.edit')}}
              </div>
              <div class="table-operate red" @click="openPassword(scope.row, 1)">
                <img src="../../assets/manageImg/table-edit1.png" alt=""> {{ $t('userManagement.tableHeaders.changePassword') }}
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100, 200, 500, 1000, 1500]" :page-size="pageSize"
        layout="->,total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog  :close-on-click-modal="false" title="提示" top="10vh" :visible.sync="passwordModel" width="460px" class="vrcode-model manage-model"
      :append-to-body="true">
      <div class="vrcode-model-title">
         {{ $t('userManagement.tableHeaders.changePassword') }}
      </div>
      <div class="vrcode-content">
        <div class="manage-left">
        <div class="manage-input w-400">
            <div class="input-title">{{ $t('userManagement.placeholders.oldPassword') }}</div>
            <input type="text" v-model="pwdData.oldPassword" 
                   :placeholder="$t('userManagement.placeholders.oldPassword')">
          </div>
          <div class="manage-input w-400">
            <div class="input-title">{{ $t('userManagement.placeholders.newPassword') }}</div>
            <input type="text" v-model="pwdData.password" 
                   :placeholder="$t('userManagement.placeholders.newPassword')">
          </div>
          <div class="manage-input w-400">
            <div class="input-title">{{ $t('userManagement.placeholders.confirmPassword') }}</div>
            <input type="text" v-model="confirmPwd" 
                   :placeholder="$t('userManagement.placeholders.confirmPassword')">
          </div>
        </div>
        <!-- <div class="manage-right">
           
              </div> -->
      </div>
      <span slot="footer" class="dialog-footer">
        <div class="vrcode-btn blue-btn w-100" @click="confirmPwdBtn">{{$t('index.confirm')}}</div>
        <div class="vrcode-btn cancle-btn w-100" @click="passwordModel = false">{{$t('index.cancel')}}</div>
      </span>
    </el-dialog>
    <el-dialog  title="提示" top="10vh" :visible.sync="addDeviceModel" width="460px" class="vrcode-model manage-model"
      :append-to-body="true" :close-on-click-modal="false">
      <div class="vrcode-model-title">
        {{$t('realTime.addDevice')}}
      </div>
      <div class="vrcode-content">
        <div class="manage-left">
          <div class="manage-input  w-400">
            <div class="input-title">{{$t('text.deviceCode')}}</div>
            <input type="text" v-model="openData.deviceId" :placeholder="$t('placeholder.deviceCodePlaceholder')">
          </div>
          <!-- <div class="manage-input  w-400">
            <div class="input-title">设备类型</div>
            <input type="text" v-model="openData.password" placeholder="请输入新密码">
          </div> -->
          <div class="manage-input-sel w-400" style="margin-right: 0;">
            <div class="input-title">{{$t('text.deviceType')}}</div>
            <el-dropdown @command="handleCommand1">
              <div class="el-dropdown-link">
                <input v-model="deviceType" type="text" class="input-input" :placeholder="$t('placeholder.deviceTypePlaceholder')">
                <div class="arrow"><img src="../../assets/image/arrow.png" alt=""></div>
              </div>
              <el-dropdown-menu slot="dropdown" class="manage-dropdown w-400">
                <el-dropdown-item v-for="item, index in deviceSel
                " :key="index" :command="item.label">{{ item.label }}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <div class="manage-input  w-400">
            <div class="input-title">{{$t('text.sortOrder')}}</div>
            <input type="text" v-model="openData.equipmentStatu" :placeholder="$t('placeholder.sortOrderPlaceholder')">
          </div>
        </div>
        <!-- <div class="manage-right">
           
              </div> -->
      </div>

      <span slot="footer" class="dialog-footer">
        <div class="vrcode-btn blue-btn w-100" @click="addDevice">{{$t('index.confirm')}}</div>
        <div class="vrcode-btn cancle-btn w-100" @click="addDeviceModel = false">{{$t('index.cancel')}}</div>
      </span>
    </el-dialog>
    <el-dialog title="提示" top="10vh" :visible.sync="addModel" width="760px" class="vrcode-model manage-model"
      :append-to-body="true" :close-on-click-modal="false">
      <div class="vrcode-model-title">
        {{ modelName }}
      </div>
        <div class="vrcode-content">
        <div class="manage-left">
          <div class="manage-input w-350">
            <div class="input-title">{{ $t('userManagement.tableHeaders.username') }}</div>
            <input type="text" v-model="nowData.userName" 
                   :placeholder="$t('placeholder.username')">
          </div>
          <div class="manage-input w-350">
            <div class="input-title">{{ $t('userManagement.tableHeaders.phone') }}</div>
            <input type="text" v-model="nowData.phonenumber" 
                   :placeholder="$t('placeholder.phone')">
          </div>
        </div>
        <div class="manage-right">
          <div class="manage-input w-350">
            <div class="input-title">{{ $t('userManagement.tableHeaders.nickname') }}</div>
            <input type="text" v-model="nowData.nickName" 
                   :placeholder="$t('placeholder.nickname')">
          </div>
          <div class="manage-input-sel w-350" style="margin: 0;">
            <div class="input-title">{{ $t('userManagement.tableHeaders.role') }}</div>
            <el-dropdown @command="handleCommand">
              <div class="el-dropdown-link">
                <input v-model="role" type="text" class="input-input" 
                       :placeholder="$t('placeholder.role')">
                <div class="arrow"><img src="../../assets/image/arrow.png" alt=""></div>
              </div>
              <el-dropdown-menu slot="dropdown" class="manage-dropdown w-350">
                <el-dropdown-item v-for="(item, index) in typeSelList" :key="index" :command="item.label">
                  {{ item.label }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
      </div>
      <div class="vrcode-content" style="padding-top: 0;" v-if="modelName!= $t('text.add')">
        <div class="manage-left">

        </div>
        <div class="manage-right">
          <div class="table-title-btn blue" @click="openaddDeviceModel">
            {{$t('text.add')}}
          </div>
        </div>
      </div>
      <div class="table-view" style="margin-top: 5px;"  v-if="modelName!=$t('text.add')">
        <el-table :data="nowData.equipments" :row-class-name="tableRowClassName" height="300" style="width: 100%">
          <el-table-column prop="deviceId" v-model="nowData.userName" :label="$t('text.deviceCode')">
          </el-table-column>
          <el-table-column prop="equipmentName" v-model="nowData.nickName" :label="$t('text.deviceType')">
            <template slot-scope="scope">
              <div>{{ getEquipmentName(scope.row.equipmentName) }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="equipmentStatu" v-model="nowData.phonenumber" :label="$t('text.sortOrder')">
          </el-table-column>
          <el-table-column :label="$t('text.operations')">
            <template slot-scope="scope">
              <div class="table-flex">
                <el-popconfirm @confirm="delDevice(scope.row, scope.$index)" :title="$t('text.deleteContent')" icon-color="red">
                  <div class="table-operate red" slot="reference">
                    <img src="../../assets/manageImg/table-delete.png" alt="">{{$t('text.delete')}}
                  </div>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <div class="vrcode-btn blue-btn w-100" @click="confirmEdit">{{$t('index.confirm')}}</div>
        <div class="vrcode-btn cancle-btn w-100" @click="addModel = false">{{$t('index.cancel')}}</div>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      currentPage: 1,
      pageSize: 10,
      tableList: [],
      total: 0,
      modelName: this.$t('text.add'),
      addModel: false,//编辑弹窗
      passwordModel: false,//修改密码弹窗
      addDeviceModel: false,//添加设备弹窗
      nowData: {
      },
      role: '',

      openData: {},
      searchName: '',
      deviceList: [],
      pwdData: {
        "oldPassword": "",
        "password": "",
        "id": ''
      },
      confirmPwd: '',
      deviceType:'',
    }
  },
      computed:{
         deviceSel(){
            var device=[
        { label: this.$t('deviceManage.deviceTypes.controller'), value: 10 },
        { label: this.$t('deviceManage.deviceTypes.fertilizer'), value: 1 },
        { label: this.$t('deviceManage.deviceTypes.weatherStation'), value: 30 },
        { label: this.$t('deviceManage.deviceTypes.smartController'), value: 20 },
        { label: this.$t('deviceManage.deviceTypes.dataCollector'), value: 40 },
      ]
           
            return  device
         },
         typeSelList(){
            var device=[{ label: this.$t('userManagement.roles.admin'), value: 1, }, 
            { label: this.$t('userManagement.roles.user'), value: 2, }]
           
            return  device
         },
    },
  mounted() { this.dataInit() },
  methods: {
    dataInit() {

      this.pageSize = 10
      this.currentPage = 1
      setTimeout(() => {
        this.getData()
      }, 0);
    },
    addDevice() {
      if (!this.openData.deviceId) {
        this.$message.error(this.$t('message.deviceCodeRequired'));
        return
      }
      if (!this.openData.equipmentName) {
        this.$message.error(this.$t('message.deviceTypeRequired'));
        return
      }
      if (!this.openData.equipmentStatu) {
        this.$message.error(this.$t('message.sortRequired'));
        return
      }
      // if(this.modelName==this.$t('text.add')){
      //   this.nowData.equipments.push(this.openData)
       
      // }else{
       
      // }
        this.api.addUserByid({...this.openData,userId:this.nowData.id}).then(res=>{
        
          if (res.data.code == 200) {
            this.nowData.equipments.push({...this.openData,userId:this.nowData.id})
          this.addDeviceModel=false
          this.getData()
          this.$message.success(res.data.msg);
          
        } else {
          this.$message.error(res.data.msg);
        }
        })

    },
    //弹窗删除设备
    delDevice(item, index) {
      var data = { deviceId: item.deviceId }

      this.api.delUserByid(data).then(res => {
        if (res.data.code == 200) {
          this.nowData.equipments.splice(index, 1)
          this.getData()
          this.$message.success(res.data.msg);
          
        } else {
          this.$message.error(res.data.msg);
        }
      })
    },
    getEquipmentName(e) {
      if (e == 10) {
        return this.$t('deviceManage.deviceTypes.controller')
      } else if (e == '1') {
        return this.$t('deviceManage.deviceTypes.fertilizer')
      } else if (e == '30') {
        return  this.$t('deviceManage.deviceTypes.weatherStation')
      } else if (e == '20') {
        return this.$t('deviceManage.deviceTypes.smartController')
      } else if (e == '40') {
        return  this.$t('deviceManage.deviceTypes.dataCollector')
      }else {
        return ''
      }
    },
    getData() {
      var data = {
        page: this.currentPage,
        pageSize: this.pageSize,
        nickName: this.searchName
      }
      this.loading = this.$loading({
        lock: true,
        text: this.$t('message.loading'),
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.api.adminAll(data).then(res => {
        this.loading.close()
        if (res.data.code == 200) {
          this.tableList = res.data.data.user
          this.total = res.data.data.total
        } else {
          this.$message.error(res.data.msg);
        }
      })
    },
    confirmEdit() {
      if (!this.nowData.userName) {
        this.$message.error(this.$t('message.usernameRequired'));
        return
      }
      if (!this.nowData.phonenumber) {
        this.$message.error(this.$t('message.phoneRequired'));
        return
      }
      if (!this.nowData.nickName) {
        this.$message.error(this.$t('message.nicknameRequired'));
        return
      }
      if (!this.nowData.role) {
        this.$message.error(this.$t('message.roleRequired'));
        return
      }
    
      if (this.modelName == this.$t('text.add')) {
        this.api.addUser(this.nowData).then(res=>{
          if (res.data.code == 200) {
            this.getData()
            this.$message.success(res.data.msg);
            this.addModel = false
          } else {
            this.$message.error(res.data.msg);
            this.addModel = false
          }
        })
      } else {
        if (!this.nowData.equipments.length) {
        this.$message.error(this.$t('message.deviceRequired'));
        return
      }
        this.api.updateUser(this.nowData).then(res => {
          if (res.data.code == 200) {
            this.getData()
            this.$message.success(res.data.msg);
            this.addModel = false
          } else {
            this.$message.error(res.data.msg);
            this.addModel = false
          }
        })
      }

    },
    getRole(e) {
      if (e == this.$t('userManagement.roles.admin')) {
        return 1
      } else {
        return 2
      }
    },
    handleCommand(e) {
      this.nowData.role = this.getRole(e)
      this.role = e
    },
    getDeviceType(e) {
       if (e ==  this.$t('deviceManage.deviceTypes.controller')) {
        return 10;
      } else if (e ==  this.$t('deviceManage.deviceTypes.fertilizer')) {
        return 1;
      } else if (e ==  this.$t('deviceManage.deviceTypes.weatherStation')) {
        return 30;
      } else if (e ==  this.$t('deviceManage.deviceTypes.smartController')) {
        return 20;
      } else if (e ==  this.$t('deviceManage.deviceTypes.dataCollector')) {
        return 40;
      }
    },
    handleCommand1(e) {
      this.openData.equipmentName = this.getDeviceType(e)
      this.deviceType = e
    },
    confirmPwdBtn() {
      if (this.confirmPwd != this.pwdData.password) {
        this.$message.error(this.$t('message.passwordMismatch'));
        return
      }
      this.api.updatePwd(this.pwdData).then(res => {
        if (res.data.code == 200) {
          this.$message.success(res.data.msg);
          this.passwordModel = false
        } else {
          this.$message.error(res.data.msg);
          this.passwordModel = false
        }
      })
    },
    openaddDeviceModel(){
   
      this.deviceType=''
      this.openData={}
         this.addDeviceModel = true
      this.$forceUpdate()
    },
    openModel(item, type) {
      if (type == 0) {
        this.modelName = this.$t('text.add')
   
        this.nowData = {
          equipments: [],
        }

        this.role = ''
             this.addModel = true
        this.$forceUpdate()
      } else {
        this.modelName = this.$t('text.edit')
        this.addModel = true

        // const deviceIds = this.deviceList.map(device => device.deviceId);

        // // 使用 join 方法将 deviceId 连接成一个字符串，以逗号隔开
        // const deviceIdString = deviceIds.join(',');
        this.nowData = JSON.parse(JSON.stringify(item))
        if (this.nowData.role == 1) {
          this.role = this.$t('userManagement.roles.admin')
        } else {
          this.role =this.$t('userManagement.roles.user')
        }
        if(!this.nowData.role){
          this.nowData.role=2
        }
      }
    },
    openPassword(item) {
      this.pwdData = {
        "oldPassword": "",
        "password": "",
        "id": item.id
      }
      this.passwordModel = true
    },
    handleSizeChange(val) {
      this.pageSize = val
      setTimeout(() => {
        this.getData()
      }, 0);
    },
    handleCurrentChange(val) {
      this.currentPage = val
      setTimeout(() => {
        this.getData()
      }, 0);
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 == 1) {
        return 'warning-row';
      } else if (rowIndex % 2 == 0) {
        return 'success-row';
      }
      return '';
    }
  },

}
</script>
<style lang="scss"></style>