<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
         <el-form-item label="护照柜名称" prop="deviceName">
          <el-input
            v-model="queryParams.deviceName"
            placeholder="请输入护照柜名称"
            clearable maxlength="20"
            style="width: 300px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="护照柜类型" prop="deviceType">
            <el-select v-model="queryParams.deviceType" placeholder="护照柜类型" clearable>
                <el-option label="小型" value="1"/>
                <el-option label="中型" value="2"/>
                <el-option label="大型" value="3"/>
            </el-select>
        </el-form-item>
        <el-form-item label="关键字" prop="keyWord">
          <el-input
            v-model="queryParams.keyWord"
            placeholder="请输入"
            clearable maxlength="20"
            style="width: 300px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >新增</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <el-table v-loading="loading" :data="tableListData" height="800">
        <el-table-column label="序号" align="center" width="80" type="index">
            <template slot-scope="scope">
                <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
            </template>
        </el-table-column>
        <el-table-column label="护照柜名称" align="center" prop="deviceName" :show-overflow-tooltip="true" width="180"/>
        <el-table-column label="护照柜类型" align="center" prop="deviceType" :show-overflow-tooltip="true" width="100">
            <template slot-scope="scope">
                <!-- <dict-tag :options="dict.type.dev_status" :value="scope.row.deviceState"/> -->
                <span v-if="scope.row.deviceType==1" >小型</span>
                <span v-if="scope.row.deviceType==2" >中型</span>
                <span v-if="scope.row.deviceType==3" >大型</span>
            </template>
        </el-table-column>
        <el-table-column label="设备地址" align="center" prop="deviceAddr" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="设备编号" align="center" prop="deviceNumber" :show-overflow-tooltip="true" width="120"/>
        <el-table-column label="是否在线" align="center" prop="deviceState" :show-overflow-tooltip="true" width="100">
            <template slot-scope="scope">
                <!-- <dict-tag :options="dict.type.dev_status" :value="scope.row.deviceState"/> -->
                <span v-if="scope.row.onlineState==1" style="color: green;">在线</span>
                <span v-if="scope.row.onlineState==2" style="color: red;">离线</span>
            </template>
        </el-table-column>
        <el-table-column label="槽位数" align="center" prop="soltNum" :show-overflow-tooltip="true"/>
        <el-table-column label="已存放数" align="center" prop="soltUsedNum" :show-overflow-tooltip="true"/>
        <el-table-column label="空余数" align="center" prop="" :show-overflow-tooltip="true">
            <template slot-scope="scope">
                <span>{{Number(scope.row.soltNum)-Number(scope.row.soltUsedNum)}}</span>
            </template>
        </el-table-column>
        <el-table-column label="所属单位" align="center" prop="deptName" :show-overflow-tooltip="true"></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"
              @click="handleUpdate(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              style="color: red;"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

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

      <!-- 添加或修改参数配置对话框 -->
      <el-dialog :title="title+'设备'" :visible.sync="open" width="700px" append-to-body>
        <el-form ref="baseForm" :model="baseForm" :rules="baseFormRules" label-width="100px" label-position="center">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="设备名称" prop="deviceName">
                    <el-input  v-model="baseForm.deviceName" placeholder="请输入设备名称" maxlength="30" clearable/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="护照柜类型" prop="deviceType">
                        <el-select v-model="baseForm.deviceType" placeholder="护照柜类型" clearable>
                            <el-option label="小型" value="1"/>
                            <el-option label="中型" value="2"/>
                            <el-option label="大型" value="3"/>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12" v-if="baseForm.deptId !== 0">
                    <el-form-item label="单位" prop="deptId" style="width: 100%;">
                        <treeselect
                            v-model="baseForm.deptId"
                            :options="deptOptions"
                            :normalizer="normalizer"
                            placeholder="选择单位"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="设备地址" prop="deviceAddr">
                        <el-input  v-model="baseForm.deviceAddr" placeholder="请输入安装地址" maxlength="30" clearable/>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="设备Ip" prop="deviceIp">
                        <el-input  v-model="baseForm.deviceIp" placeholder="请输入设备Ip" maxlength="30" clearable/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="功能接口" prop="funImp">
                    <el-input  v-model="baseForm.funImp" placeholder="请输入功能接口" maxlength="30" clearable/>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="设备Sn" prop="deviceSn">
                        <el-input  v-model="baseForm.deviceSn" placeholder="请输入设备Sn" maxlength="30" clearable/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="设备key" prop="deviceKey">
                        <el-input  v-model="baseForm.deviceKey" placeholder="请输入设备key" maxlength="30" clearable/>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="设备Mac" prop="deviceMac">
                        <el-input  v-model="baseForm.deviceMac" placeholder="请输入设备Mac" maxlength="30" clearable/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="网关" prop="deviceGateway">
                        <el-input  v-model="baseForm.deviceGateway" placeholder="请输入网关" maxlength="30" clearable/>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="密码" prop="devicePwd">
                        <el-input  v-model="baseForm.devicePwd" placeholder="请输入密码" maxlength="30" clearable/>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>

  <script>
    import {
        listDept,
        getDept,
        delDept,
        addDept,
        updateDept,
        listDeptExcludeChild,
    } from '@/api/system/dept'
    import { systemAreaTreeApi,getCanteenByAreaApi,getStallByCanteenApi } from "@/api/base/stall";
    import { getDeviceListPageApi,addDeviceApi, updateDeviceApi, deleteDeviceApi,getMenuRecipeDetailApi,uploadApkApi } from "@/api/device/index";
    import base64 from 'base-64';
    import { getToken } from '@/utils/auth'
    import Treeselect from '@riophae/vue-treeselect'
    import '@riophae/vue-treeselect/dist/vue-treeselect.css'
    export default {
        name: "",
        dicts: ["dev_comm_status","dev_status"],
        components: { Treeselect },
        data() {
            return {
                // 遮罩层
                loading: true,
                // 选中数组
                ids: [],
                // 非单个禁用
                single: true,
                // 非多个禁用
                multiple: true,
                // 显示搜索条件
                showSearch: true,
                // 总条数
                total: 0,
                //表格数据
                tableListData: [],
                deptOptions: [],
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                checked: false,
                statusOptions:[{id:"1",name:"在线"},{id:"2",name:"离线"}],
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    deviceName:"",
                    deviceType:"",
                    keyWord:"",//关键字
                },
                activeName:"baseSetting",
                deviceData:{},
                // 表单参数
                baseForm: {
                    areaId:null,
                    canteenId:null,
                    stallId:null,
                    deviceNumber:"",
                    deviceName:"",
                    deviceSn:"",
                    deviceIp:"",
                    deviceKey:"",
                    deviceAddr:"",
                    deviceMac:"",
                    deviceGateway:"",
                    devicePwd:""
                },
                // 表单校验
                baseFormRules: {
                    deptId: [
                        { required: true, message: "单位不能为空", trigger: "blur" }
                    ],
                    deviceType: [
                        { required: true, message: "设备类型不能为空", trigger: "blur" }
                    ],
                    funImp: [
                        { required: true, message: "设备编号不能为空", trigger: "blur" }
                    ],
                    deviceName: [
                        { required: true, message: "设备名称不能为空", trigger: "blur" }
                    ],
                    deviceIp: [
                        { required: true, message: "设备IP不能为空", trigger: "blur" }
                    ]
                },
                metadata:{
                    "voiceRemindSuccess": "1",
                    "showPaySuccessTime": "3",
                    "offlineTotalCount": "10000",
                    "faceSize": "100",
                    "faceRecognitionScore": "80",
                    "printIsor": "2",
                    "payOnceHighMoney": "100000",
                    "ruleCardQRTran": "0",
                    "offlineTotalMoney": "10000",
                    "showNoSubBalance": "1",
                    "showNoNutrition": "2",
                    "identityCard": "1",
                    "paySamePersonSameMoneyTime": "10",
                    "identityQR": "1",
                    "voiceRemindFail": "1",
                    "offlineAllow": "2",
                    "identityFace": "1"
                },
                openLog:false,
                dialogQueryParams:{//异常查询条件
                    pageNum: 1,
                    pageSize: 10,
                },
                logTableData:[],//异常弹窗
                // 总条数
                dialogTotal: 0,
                //当前菜谱
                openMenu:false,
                menuData:[],
                menuSubData:[],
                openApp:false,
                appForm:{
                    version:null,
                    versionName:null,
                    apkName:null,
                    apkPath:null,
                    updateContent:null,
                    type:1,//1食堂APP   2超市APP
                },
                 //导入参数
                upload: {
                    // 是否禁用上传
                    isUploading: false,
                    // 设置上传的请求头部
                    headers: { Authorization: 'Bearer ' + getToken() },
                    // 上传的地址
                    url: process.env.VUE_APP_BASE_API + '/file/upload',
                },
            };
        },
        mounted(){
            this.getList()
        },
        methods: {
            /** 搜索按钮操作 */
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery() {
                this.resetForm("queryForm");
                this.handleQuery();
            },
            /** 查询列表 */
            getList() {
                this.loading = true;
                let param = {
                    "pageNum":this.queryParams.pageNum,
                    "pageSize":this.queryParams.pageSize,
                    "deviceName":this.queryParams.deviceName,
                    "deviceType":this.queryParams.deviceType,
                    "searchValue":this.queryParams.keyWord
                }
                console.log("param",param)
                // let str = base64.encode(JSON.stringify(param))
                // console.log({"content":str})
                getDeviceListPageApi(param).then(response => {
                    this.tableListData = response.rows;
                    this.total = Number(response.total);
                    this.loading = false;
                });
            },
            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            // 表单重置
            reset() {
                this.baseForm = {
                    areaId:null,
                    canteenId:null,
                    stallId:null,
                    deviceNumber:"",
                    deviceName:"",
                    deviceSn:"",
                    deviceIp:"",
                    deviceKey:"",
                    deviceAddr:"",
                    deviceMac:"",
                    deviceGateway:"",
                    devicePwd:""
                };
                this.resetForm("baseForm");
            },
            /** 新增按钮操作 */
            handleAdd() {
                this.reset();
                this.open = true;
                this.title = "新增";
                listDept().then((response) => {
                    this.deptOptions = this.handleTree(response.data, 'deptId');
                    console.log("this.deptOptions",this.deptOptions)
                })
            },
            /** 转换部门数据结构 */
            normalizer(node) {
                if (node.children && !node.children.length) {
                    delete node.children
                }
                return {
                    id: node.deptId,
                    label: node.deptName,
                    children: node.children,
                }
            },
            /** 修改按钮操作 */
            handleUpdate(row) {
                this.reset();
                this.open = true;
                this.baseForm = Object.assign({}, row)
                // this.$set(this,"metadata",row.deviceMetadata)
                this.title = "修改";
                listDept().then((response) => {
                    this.deptOptions = this.handleTree(response.data, 'deptId')
                })
            },
            handleTabClick(tab, event) {
                console.log(tab, event);
            },
            //基础设置-选择区域
            handleTreeChange2(val){
                setTimeout(()=>{
                    // 选择区域后获取相应食堂
                    getCanteenByAreaApi({areaId:val,canteenType: 1}).then((response) => {
                        this.canteenOptions2=response.rows||[]
                        this.stallOptions2=[]
                        this.$set(this.baseForm,"canteenId",null)
                        this.$set(this.baseForm,"stallId",null)
                    });
                },300)
            },
            //选择食堂后获取档口编号
            chosenCanteen(e){
                console.log(e)
                this.$set(this.baseForm,"canteenId",e)
                this.$refs['baseForm'].clearValidate(['canteenId']);
                let param= {
                    canteenId:e
                }
                getStallByCanteenApi(param).then((response) => {
                    this.stallOptions2=response.rows||[]
                    this.baseForm.stallId=null
                });
            },
            //选择食堂后获取档口编号
            chosenStall(e){
                console.log(e)
                this.baseForm.stallId=e
                this.$refs['baseForm'].clearValidate(['stallId']);
                this.$forceUpdate()
            },
            /** 提交按钮 */
            submitForm: function() {
                console.log(this.baseForm)
                this.$refs["baseForm"].validate(valid => {
                if (valid) {
                    // this.baseForm.metadata=this.metadata
                    if (this.baseForm.deviceId != undefined) {
                        updateDeviceApi(this.baseForm).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addDeviceApi(this.baseForm).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
                });
            },
            /** 删除按钮操作 */
            handleDelete(row) {
                // const dictIds = row.dictId || this.ids;
                this.$modal.confirm('是否确认删除数据项？').then(function() {
                    return  deleteDeviceApi({deviceId:row.deviceId});
                }).then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                }).catch(() => {});
            },
            /** 今日菜谱按钮操作-打开弹窗 */
            openMenuDialog(row){
                this.openMenu=true
                this.recipeId = row.firstRecipeId
                this.queryMenuData()
            },
            handleMenuQuery(){
                this.queryMenuData()
            },
            //今日菜谱弹窗-分页查询接口
            queryMenuData() {
                console.log(this.dialogMenuParams.applyDate)
                let param = {
                    "applyDate": this.dialogMenuParams.applyDate,
                    "recipeId": this.recipeId
                }
                getMenuRecipeDetailApi(param).then((response) => {
                    console.log(response)
                    this.menuData = response;
                    this.menuSubData=[]
                    console.log(this.dialogMenuParams.keyWord)
                    this.menuData.forEach(item => {
                        if(item.mealtimeName == this.dialogMenuParams.keyWord){
                            this.menuSubData = this.menuSubData.concat(item.dishesList)
                        }
                    });
                });
            },
            formatDate(date) {
                // 格式化为 YYYY-MM-DD
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
                const day = String(date.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            },
            handleApp(){
                 this.appForm = {
                    version:null,
                    versionName:null,
                    apkName:null,
                    apkPath:null,
                    updateContent:null,
                    deviceType:null,//20食堂APP   2超市APP
                };
                this.resetForm("appForm");
                this.openApp = true;
            },
            // 文件上传中处理
            handleFileUploadProgress(event, file, fileList) {
                this.upload.isUploading = true
            },
            // 文件上传成功处理
            handleFileSuccess(response, file, fileList) {
                console.log(response)
                this.upload.isUploading = false
                this.$refs.upload.clearFiles()
                if(response.code==200){
                    this.appForm.apkPath=response.data.url
                }else{
                    this.$modal.msgError("上传失败，请重新选择文件！");
                }
            },
            confirmApp(){
                console.log(this.appForm)
                this.$refs["appForm"].validate(valid => {
                    if (valid) {
                        uploadApkApi(this.appForm).then(response => {
                            this.$modal.msgSuccess("操作成功");
                            this.openApp = false;
                        });
                    }
                });
            },

        }
    };
  </script>
  <style scoped lang="scss">
    .form-title{
        display: flex;
        align-items: flex-end;
        // width: 100%;
        // height: 40px;
        background: #e7f0fa;
        border-left: 3px solid #46a6ff;
        margin: 10px 0;
        padding: 5px;
    }
    .form-item{
        width: 100%;
        font-size: 14px !important;
    }





  </style>
