<template>
  <div class="app-container">
    <el-card >
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
        <el-form-item label="" prop="name">
          <el-input
            v-model="queryParams.deviceName"
            placeholder="设备名称"
            clearable
            style="width: 240px;"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item style="float: right; margin-right: 0px">
          <el-button type="primary" icon="el-icon-search"  @click="handleQuery">搜索</el-button>
                    <el-button icon="el-icon-refresh"  @click="resetQuery">重置</el-button>
          <el-button type="primary" icon="el-icon-search"  @click="handleAdd">新增设备</el-button>

        </el-form-item>
      </el-form>

      <el-table :data="tableData" style="width: 100%" border>
      <el-table-column  align="center" type="index" label="序号"></el-table-column>
        <el-table-column align="center" prop="deviceName" label="设备名称"></el-table-column>
        <el-table-column align="center" prop="deviceSi" label="品牌"></el-table-column>
        <el-table-column align="center" prop="deviceAb" label="设备功能"></el-table-column>
        <el-table-column align="center" prop="deptName" label="所属机构"></el-table-column>
        <el-table-column align="center" prop="staffIds" label="关联员工">
          <template slot-scope="scope">
            {{jsonChange(scope.row.staffIds)}}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="machineCode" label="设备终端号"></el-table-column>
        <el-table-column align="center" prop="msign" label="设备密钥"></el-table-column>

<!--      <el-table-column  align="center" prop="userId" label="用户id"></el-table-column>-->
<!--      <el-table-column prop="appKey" label="应用id(APP_KEY)"></el-table-column>-->
<!--      <el-table-column prop="appSecret" label="应用密钥(APP_SECRET)"></el-table-column>-->
<!--      <el-table-column prop="appPublicKey" label="应用公钥(key)"></el-table-column>-->
<!--      <el-table-column prop="platformPublicKey" label="平台公钥(publicKey)"></el-table-column>-->
<!--      <el-table-column prop="accessToken" label="token"></el-table-column>-->
<!--      <el-table-column prop="isAcquiesce" label="isAcquiesce">-->
<!--        <template slot-scope="scope">-->
<!--          <el-switch-->
<!--            v-model="scope.row.isAcquiesce"-->
<!--            @change="submitDeviceInfo(scope.row)"-->
<!--            active-color="#13ce66"-->
<!--            inactive-color="#ff4949">-->
<!--          </el-switch>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="edit(scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="del(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    </el-card>

    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="30%" append-to-body>
      <el-form ref="form" :model="deviceInfo" label-width="80px">
        <el-form :model="deviceInfo" ref="deviceForm" label-width="120px">
          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="deviceInfo.deviceName" style="width: 300px"></el-input>
          </el-form-item>
          <el-form-item label="设备品牌" prop="deviceSi">
            <el-input v-model="deviceInfo.deviceSi" style="width: 300px"></el-input>
          </el-form-item>
          <el-form-item label="设备功能" prop="deviceAb">
            <el-radio-group v-model="deviceInfo.deviceAb">
              <el-radio label="打印小票"></el-radio>
              <el-radio label="语音播报"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="设备终端号" prop="machineCode">
            <el-input v-model="deviceInfo.machineCode" style="width: 300px"></el-input>
          </el-form-item>
          <el-form-item label="设备密钥" prop="msign">
            <el-input v-model="deviceInfo.msign" style="width: 300px"></el-input>
          </el-form-item>
          <el-form-item label="选择员工" prop="staffId">
            <el-select
              v-model="staffIds"
              clearable
              placeholder=""
              style="width: 300px"
              multiple
              collapse-tags
            >
              <el-option v-for="item in staffList" :key="item.id" :label="item.realName" :value="item.id+''">
                <span style="float: left">{{ item.realName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.mobile }}</span>
              </el-option>
            </el-select>
          </el-form-item>
<!--          <el-form-item label="用户id" prop="userId">-->
<!--            <el-input v-model="deviceInfo.userId"></el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="应用id" prop="appKey">-->
<!--            <el-input v-model="deviceInfo.appKey"></el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="应用密钥" prop="appSecret">-->
<!--            <el-input v-model="deviceInfo.appSecret"></el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="应用公钥" prop="appPublicKey">-->
<!--            <el-input v-model="deviceInfo.appPublicKey"></el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="平台公钥" prop="platformPublicKey">-->
<!--            <el-input v-model="deviceInfo.platformPublicKey"></el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="token" prop="accessToken">-->
<!--            <el-input v-model="deviceInfo.accessToken"></el-input>-->
<!--          </el-form-item>-->
          <el-form-item label="启用状态" prop="isAcquiesce">
            <el-switch
              v-model="deviceInfo.acquiesce"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
          </el-form-item>

          <el-form-item label="备注" prop="appPublicKey">
            <el-input  type="textarea" v-model="deviceInfo.appPublicKey" style="width: 300px"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="" @click="open = false">取消</el-button>
            <el-button type="primary" @click="submitForm('deviceForm')">提交</el-button>
          </el-form-item>
        </el-form>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>

import {addPrintDeviceApi, delPrintDeviceApi, editPrintDeviceApi, getListByPageApi} from "@/api/print";
import {queryStaffs} from "@/api/order/staff";

export default {
  name: "printIndex",

  data() {
    return {
      tableData: [],
      staffIds: '',
      staffList:[],

      deviceInfo: {
        id: null,            // 自增id
        machineCode: '',     // 设备终端号
        msign: '',           // 设备密钥
        deviceName: '',      // 设备名称
        userId: null,        // 用户id
        appKey: '',          // 应用id(APP_KEY)
        appSecret: '',       // 应用密钥(APP_SECRET)
        appPublicKey: '',    // 应用公钥(key)
        platformPublicKey: '', // 平台公钥(publicKey)
        accessToken: '',   // token
        deviceSi: '',   // 设备品牌
        staffIds: '',   // 员工
        deviceAb: '',   // 设备功能
        staffName: '',   // 设备员工名字
        acquiesce: false      // token
      },
      // 是否显示弹出层
      open: false,
      title:"",
      total:0,
      // 查询参数
      queryParams: {
        page: 1,
        pageSize: 10,
        deviceName:'',
      },
    };
  },
  created() {
    this.getList()
    this.getStaffList()
  },
  methods: {
    getList(){
      getListByPageApi(this.queryParams).then(res=>{
        this.tableData = res.data.records;
        this.total = res.data.total
      })
    },

    // 获取员工
    getStaffList(){
      queryStaffs().then( response => {
        this.staffList = response.data;
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 表单验证通过，可以提交数据
          // 示例：调用 API 提交数据
          this.submitDeviceInfo();
        } else {
          // 表单验证失败，不执行任何操作
          return false;
        }
      });
    },
    submitDeviceInfo() {
      let staff = [];

      this.staffIds.forEach(id => {
        let matchingStaff = this.staffList.find(staff => staff.id === Number(id));
        let names = {
          id: id,
          realName: matchingStaff ? matchingStaff.realName : id
        }
        staff.push(names)
      });

      this.deviceInfo.staffIds = JSON.stringify(staff)
      // 在这里调用接口提交设备信息数据
      console.log('提交设备信息数据:', this.deviceInfo);
      if (this.deviceInfo.id) {
        editPrintDeviceApi(this.deviceInfo).then(res=>{
          if(res.code === 200) {
            this.getList()
            this.open = false
          }
        })
      }else {
        console.log("staffIds",this.staffIds)
        addPrintDeviceApi(this.deviceInfo).then(res=>{
          if(res.code === 200) {
            this.getList()
            this.open = false
          }
        })
      }
    },

    jsonChange(data) {
      if (data) {
        let a = JSON.parse(data);
        let b = a.map(res => res.realName).join(',');
        return b
      }else {
        return '--'
      }

    },

    handleQuery(){
      this.getList()
    },
    resetQuery(){
      this.queryParams = {
        page: 1,
        pageSize: 10,
        deviceName:'',
      },
      this.getList()
    },
    handleAdd(e) {
      this.clean()
      this.open = true;
      this.title = "增加设备"
    },
    edit(e) {
      this.clean()
      this.open = true;
      this.title = "编辑设备"
      console.log("eeeeeeee",e)
      if (e.staffIds) {
        let a = JSON.parse(e.staffIds)
        this.staffIds = a.map(res => res.id)
      }
      this.deviceInfo = e
      console.log('提交设备信息数据:', this.deviceInfo);

    },
    del(e) {

      this.$confirm('此操作将永久删除该设备, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delPrintDeviceApi({id:e.id}).then(res=>{
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList()
          }
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });



    },
    clean() {
      this.staffIds = []
      this.deviceInfo= {
        id: null,            // 自增id
        machineCode: '',     // 设备终端号
        msign: '',           // 设备密钥
        deviceName: '',      // 设备名称
        userId: null,        // 用户id
        appKey: '',          // 应用id(APP_KEY)
        appSecret: '',       // 应用密钥(APP_SECRET)
        appPublicKey: '',    // 应用公钥(key)
        platformPublicKey: '', // 平台公钥(publicKey)
        accessToken: '' ,     // token
        acquiesce: false      // token
      }
    },
  }
};
</script>
<style lang="scss" scoped>
.common-dialog >>> .el-upload--picture-card {
  width: 60px;
  height: 50px;
  line-height: 60px;
}
</style>

