<template>
  <div class="aainer">
    <div class="wit-b">
      <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 label="" prop="deviceAb">
          <el-select
            v-model="queryParams.deviceAb"
            clearable
            placeholder="请选择设备功能"
          >
            <el-option label="打印小票" value="打印小票"/>
            <el-option label="语音播报" value="语音播报"/>
          </el-select>
        </el-form-item>
        <el-form-item label="" prop="staffIds">
          <el-select
            v-model="queryParams.staffIds"
            clearable
            placeholder="请选择关联员工"
          >
            <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="" prop="acquiesce">
          <el-select
            v-model="queryParams.acquiesce"
            clearable
            placeholder="请选择设备状态"
          >
            <el-option label="启用" value="1"/>
            <el-option label="停用" value="0"/>
          </el-select>
        </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>
      <div style="width: 100%; height: 674px; overflow: auto; ">
        <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="acquiesce" label="设备状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.acquiesce"
                disabled
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
            </template>
          </el-table-column>

          <el-table-column align="center" prop="remark" label="备注"></el-table-column>
          <el-table-column align="center" prop="createTime" label="创建时间"></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>
      </div>


      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

    </div>
    <el-dialog center :title="title" :close-on-click-modal="false" :before-close="handleCancel" :visible.sync="open" width="30%"
               append-to-body >

        <el-form :model="deviceInfo" :rules="rules" ref="deviceForm" label-width="95px">
          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="deviceInfo.deviceName" ></el-input>
          </el-form-item>
          <el-form-item label="设备品牌" prop="deviceSi">
            <el-input v-model="deviceInfo.deviceSi" ></el-input>
          </el-form-item>
          <el-form-item label="设备功能" prop="deviceAb">
            <el-checkbox-group v-model="deviceInfo.deviceAb">
              <el-checkbox name="deviceAb" label="打印小票"></el-checkbox>
              <el-checkbox name="deviceA1b" label="语音播报"></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="设备终端号" prop="machineCode">
            <el-input v-model="deviceInfo.machineCode"></el-input>
          </el-form-item>
          <el-form-item label="设备密钥" prop="msign">
            <el-input v-model="deviceInfo.msign"></el-input>
          </el-form-item>
          <el-form-item label="选择员工" prop="staffId">
            <el-select
              v-model="staffIds"
              clearable
              placeholder=""
              style="width: 100%"
              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="所属机构" prop="deptId">
            <el-select
              v-model="deviceInfo.deptId"
              clearable
              placeholder=""
              style="width: 100%"
              collapse-tags
            >
              <el-option
                v-for="item in deptListSelect"
                :key="item.deptId"
                :label="item.deptName"
                :value="item.deptId"
              ></el-option>
            </el-select>
          </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="remark">
            <el-input type="textarea" v-model="deviceInfo.remark" ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="" @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="submitForm('deviceForm')">提交</el-button>
          </el-form-item>
        </el-form>

    </el-dialog>

  </div>
</template>

<script>

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

export default {
  name: "printIndex",

  data() {
    return {
      tableData: [],
      staffIds: '',
      staffList: [],
      deptListSelect:[],
      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
      },
      rules: {
        deviceName: [
          {required: true, message: '设备名称不能为空', trigger: 'blur'}
        ],
        deptId: [
          {required: true, message: '机构不能为空', trigger: 'blur'}
        ],
        deviceSi: [
          {required: true, message: '设备品牌不能为空', trigger: 'blur'}
        ],
        deviceAb: [ {required: true, message: '设备功能不能为空', trigger: 'blur'}],
        machineCode: [
          {required: true, message: '设备终端号不能为空', trigger: 'blur'}
        ],
        msign: [
          {required: true, message: '设备密钥不能为空', trigger: 'blur'}
        ],
        staffId: [
          {required: false, message: '请选择员工', trigger: 'change'}
        ]
      },
      // 是否显示弹出层
      open: false,
      title: "",
      total: 0,
      // 查询参数
      queryParams: {
        page: 1,
        pageSize: 10,
        deviceName: '',
      },
    };
  },
  created() {
    this.getList()
    this.getStaffList()
    this.selectChildByDeptIdApi()
  },
  methods: {
    // 查询
    selectChildByDeptIdApi() {
      selectChildByDeptId().then(res => {
        this.deptListSelect = res.data
      })
    },
    getList() {
      getListByPageApi(this.queryParams).then(res => {
        this.tableData = res.data.records;
        this.total = res.data.total
      })

    }, handleCancel() {
      this.$refs.deviceForm.resetFields(); // 重置表单
      this.open = false;
    },

    // 获取员工
    getStaffList() {
      queryStaffs().then(response => {
        this.staffList = response.data;
      })
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 表单验证通过，可以提交数据
          // 示例：调用 API 提交数据
          this.deviceInfo.deviceAb = this.deviceInfo.deviceAb.join(',')
          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
      this.deviceInfo.deviceAb = this.deviceInfo.deviceAb.split(",")
      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
        deviceAb: ['打印小票']
      }
      // this.deviceInfo.deviceAb = []
    },
  }
};
</script>
<style lang="scss" scoped>
.common-dialog > > > .el-upload--picture-card {
  width: 60px;
  height: 50px;
  line-height: 60px;
}
.aainer{
  background: #f5f7f8;
  box-sizing: border-box;
  padding: 10px;
}

.wit-b{
  background: #fff;
  border-radius: 8px;
  box-sizing: border-box;
  padding: 15px;
  height: 87vh;
}
</style>

