<template>
  <div>
    <el-form ref="queryFormRef" :model="queryParams" :inline="true" style="height: 65px;"
      @keyup.enter.native="queryList">
      <el-form-item label="设备SN">
        <el-input v-model="queryParams.deviceSn" placeholder="设备SN" width="120px" maxlength="11" show-word-limit clearable />
      </el-form-item>
      <!-- <el-form-item label="遥测站">
        <el-input v-model="queryParams.stationName" placeholder="遥测站" width="120px" />
      </el-form-item> -->
      <el-form-item label="设备类型">
        <el-select v-model="queryParams.deviceType" class="filter-item" placeholder="设备类型" width="150px" clearable>
          <el-option v-for="(key, value) in Dic.deviceTypeMap" :key="key" :label="key" :value="value" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备状态">
        <el-select v-model="queryParams.curStateType" class="filter-item" placeholder="设备状态" width="150px" clearable>
          <el-option v-for="(key, value) in deviceStateMap" :key="key" :label="key" :value="value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="button" :disabled="state.search_disabled" @click="queryList">
          查询设备
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="button" @click="handleAdd">新增设备</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="button" @click="handleBarCode">扫码新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="button" @click="handleAddOne">批量新增一</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="button" @click="handleAddTwo">批量新增二</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="state.tableData" border stripe style="width: 100%" :height="tableHeight"
      highlight-current-row @current-change="handleCurrentRowChange" ref="my_table"
      :header-cell-style="{ background: '#606266', color: '#FFFFFF' }">
      <el-table-column fixed type="index" width="50" align="center" />
      <el-table-column fixed prop="deviceSn" label="设备SN" header-align="center" width="120" />
      <el-table-column prop="deviceName" label="设备名称" header-align="center" width="100" />
      <el-table-column fit prop="stationCode" label="遥测站" header-align="center" min-width="250" />
      <el-table-column label="设备类型" header-align="center" align="center" width="80">
        <template #default="scope">
          <el-tag :type="deviceTypeColorMap[scope.row.deviceType]">{{ Dic.deviceTypeMap[scope.row.deviceType] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="设备状态" header-align="center" align="center" width="110">
        <template #default="scope">
          <el-tag>{{ scope.row.curStateTypeName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="batCode" label="电池编号" header-align="center" width="140" />
      <el-table-column prop="certifDate" label="质检日期" header-align="center" width="140" />
      <el-table-column prop="certifFlag" label="质检状态" header-align="center" width="90" />
      <el-table-column prop="certifMan" label="质检人" header-align="center" width="100" />

      <el-table-column fit prop="unusedBecause" label="停用原因" header-align="center" min-width="100" />
      <el-table-column fixed="right" label="" align="left" width="300">
        <template #default="scope">
          <el-button type="text">合格证</el-button>
          <el-button type="text" @click="showDevCfg(scope.row)">设备参数</el-button>
          <el-button type="text">设备履历</el-button>
          <el-button type="text" @click="handleEdit(scope.row)" :disabled="!adminFlag">编辑</el-button>
          <el-button type="text" @click="submitDeleteForm(scope.row)" :disabled="!adminFlag">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-config-provider :locale="locale">
      <el-pagination v-model:currentPage="queryParams.page" v-model:page-size="queryParams.rows"
        :page-sizes="[10, 15, 20, 25, 100]" :small="state.small" :disabled="state.disabled"
        :background="state.background" layout="total, sizes, prev, pager, next, jumper" :total="state.total"
        style="text-align: center; margin-top: 10px; height: 30px" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </el-config-provider>

    <el-dialog :title="adddialog.title" v-model="adddialog.visible" width="400px" draggable center>
      <el-form ref="addFormRef" :model="formAddData" :rules="state.rules" label-width="100px">
        <el-form-item label="设备SN:" prop="deviceSn" style="width: 320px;">
          <el-input v-model="formAddData.deviceSn" placeholder="设备SN" width="120px" maxlength="11" show-word-limit
            clearable />
        </el-form-item>
        <el-form-item label="设备名称:" style="width: 320px;">
          <el-input v-model="formAddData.deviceName" placeholder="设备名称" width="120px" clearable />
        </el-form-item>
        <el-form-item label="设备类型:">
          <el-select v-model="formAddData.deviceType" class="filter-item" placeholder="设备类型">
            <el-option v-for="(key, value) in Dic.deviceTypeMap" :key="key" :label="key" :value="value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel()">取消</el-button>
          <el-button type="primary" @click="submitAddForm" :disabled="state.saveDisabled">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog :title="adddialogOne.title" v-model="adddialogOne.visible" width="450px" center>
      <el-form ref="addFormRef" :model="formAddData" :rules="state.rules" label-width="100px">
        <el-form-item label="设备类型:">
          <el-select v-model="formAddData.deviceType" class="filter-item" placeholder="设备类型" style="width: 300px;">
            <el-option v-for="(key, value) in Dic.deviceTypeMap" :key="key" :label="key" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备SN:">
          <el-input v-model="formAddData.deviceSn" :rows="2" type="textarea" placeholder="设备SN" clearable />
        </el-form-item>
        <span style="font-size: 9px;color:red;float:right;">*已经存在的编号会自动跳过</span>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel()">取消</el-button>
          <el-button type="primary" @click="submitAddForm" :disabled="state.saveDisabled">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog :title="adddialogTwo.title" v-model="adddialogTwo.visible" width="450px" center>
      <el-form ref="addFormRef" :model="formAddData" :rules="state.rules" label-width="100px">
        <el-form-item label="设备类型:">
          <el-select v-model="formAddData.deviceType" class="filter-item" placeholder="设备类型" style="width: 300px;">
            <el-option v-for="(key, value) in Dic.deviceTypeMap" :key="key" :label="key" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备SN:" prop="deviceSn">
          <el-input v-model="formAddData.deviceSn" placeholder="设备SN" maxlength="11" show-word-limit
            clearable />
        </el-form-item>
        <el-form-item label="设备数量:">
          <el-input-number v-model="formAddData.addnum" min="1" placeholder="设备数量" width="150px" maxlength="4"/>
        </el-form-item>
        <span style="font-size: 9px;color:red;float:right;">*已经存在的编号会自动跳过</span>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitAddForm" :disabled="state.saveDisabled">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog :title="editdialog.title" v-model="editdialog.visible" width="450px" center>
      <el-form ref="editFormRef" :model="formEditData" label-width="100px">
        <el-form-item label="设备SN:">
          <el-input v-model="formEditData.deviceSn" placeholder="设备SN" width="120px" />
        </el-form-item>
        <el-form-item label="设备名称:">
          <el-input v-model="formEditData.deviceName" placeholder="设备名称" width="120px" />
        </el-form-item>
        <el-form-item label="设备类型:">
          <el-select v-model="formEditData.deviceType" class="filter-item" placeholder="设备类型" style="width: 300px;">
            <el-option v-for="(key, value) in Dic.deviceTypeMap" :key="key" :label="key" :value="value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="设备状态:">
        <el-select v-model="formEditData.curStateType" class="filter-item" placeholder="设备状态" width="150px">
          <el-option v-for="(key, value) in deviceStateMap" :key="key" :label="key" :value="value" />
        </el-select>
      </el-form-item> -->
        <el-form-item label="使用状态:">
          <el-select v-model="formEditData.useFlag" class="filter-item" placeholder="使用状态" style="width: 300px;">
            <el-option v-for="(key, value) in deviceUseFlagMap" :key="key" :label="key" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="停用原因:">
          <el-input v-model="formEditData.unusedBecause" type="textarea" :disabled="formEditData.useFlag=='1'"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel()">取消</el-button>
          <el-button type="primary" @click="submitEditForm" :disabled="state.saveDisabled">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog :title="cfgdialog.title" v-model="cfgdialog.visible" width="1100px" center>
      <DevCfgDialog :stationCode="state.cfgData.stationCode" :deviceSn="state.cfgData.deviceSn"></DevCfgDialog>
    </el-dialog>

    <el-dialog :title="barcodedialog.title" v-model="barcodedialog.visible" width="750px" draggable center>
      <el-form ref="addFormRef" :model="formAddData" :rules="state.rules" label-width="100px">
        <div class="big_box">
          <div class="left_box">
            <el-table :data="state.barcodeDetail" border stripe style="width: 100%," highlight-current-row size="small"
              :header-cell-style="{ background: '#FF000000', color: '#000000' }">
              <el-table-column type="index" width="50" align="center" />
              <el-table-column label="设备SN" align="center" width="300">
                <template #default="scope">
                  <el-input v-model="scope.row.deviceSn" maxlength="11" show-word-limit clearable>
                  </el-input>
                </template>
              </el-table-column>
            </el-table>

          </div>
          <div class="right_box">
            <div class="right_box_header">
              <span style="font-size:18px;margin-left: 10px;">请使用扫码枪录入设备SN</span>
            </div>
            <div class="right_box_content">
              <el-form-item label="设备类型:" style="margin-top: 20px;">
                <el-select v-model="formAddData.deviceType" class="filter-item" placeholder="设备类型" style="width:180px;">
                  <el-option v-for="(key, value) in Dic.deviceTypeMap" :key="key" :label="key" :value="value" />
                </el-select>
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
      <div style="text-align: center;">
        <el-button @click="cancel()">取消</el-button>
          <el-button type="primary" @click="submitBarCodeAddForm" :disabled="state.saveDisabled">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, toRefs, toRef, ref, onMounted } from "vue";
import { ElForm, ElMessage, ElMessageBox } from "element-plus";
import DeviceAction from "@/api/deviceacc";
import { DeviceAccQueryParam, DeviceAccModel, Dialog, PageResult } from "@/types";
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import DevCfgDialog from "@/components/devcfg/index.vue";
import Dic from "@/dictionary/aicbqcfg";

let locale = ref(zhCn);
const adminFlag = localStorage.getItem("AdminFlag")?.toString() === '1';
// const queryFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致
const addFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致
// const editFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致
const my_table = ref();
type mapStatee = Record<string, string>;

const deviceTypeColorMap: mapStatee = {
  0: '',
  1: 'success',
};


const deviceStateMap = {
  1: "登记台账",
  2: "拷机",
  3: "入库",
  4: "出库",
  5: "故障",
  6: "修复",
  7: "借出",
  8: "归还",
  9: "报废/丢失",
};

const deviceUseFlagMap = {
  0: "停用",
  1: "在用",
};

const loading = ref(false);

const state = reactive({
  queryParams: { page: 1, rows: 10 } as DeviceAccQueryParam,
  currentType: 0,//val=0 新增; =1 批量新增一; =2 批量新增二; =3 编辑;
  total: 0,
  small: false,
  background: true,
  disabled: false,
  search_disabled: false,
  adddialog: {} as Dialog,
  adddialogOne: {} as Dialog,
  adddialogTwo: {} as Dialog,
  editdialog: {} as Dialog,
  formAddData: {} as DeviceAccModel,
  formEditData: {} as DeviceAccModel,
  tableData: [] as DeviceAccModel[],
  cfgdialog: {} as Dialog,
  cfgData: {} as DeviceAccModel,
  rules: {
    deviceSn: [
      { required: true, message: "设备SN不能为空", trigger: "blur" },
      { min: 11, max: 11, message: "设备SN长度不合法", trigger: "blur" },
    ],
  },
  barcodeDialog: {} as Dialog,
  barcodeDetail:[] as DeviceAccModel[],
  saveDisabled:false
});

const {
  queryParams,
  total,
  adddialog,
  adddialogOne,
  adddialogTwo,
  editdialog,
  formAddData,
  formEditData,
  tableData,
  cfgdialog,
  barcodeDialog: barcodedialog
} = toRefs(state);

const tableHeight = ref(document.documentElement.clientHeight - 190);

const currentRow = ref();

const handleCurrentRowChange = (val: DeviceAccModel | undefined) => {
  currentRow.value = val;
};

const handleAdd = () => {
  state.currentType = 0;
  state.formAddData.deviceType = "1";
  state.adddialog = {
    title: "新增设备台账",
    visible: true,
    disabled: false,
  };
};
const handleAddOne = () => {
  state.currentType = 1;
  state.formAddData.deviceType = "1";
  state.adddialogOne = {
    title: "批量新增设备台账",
    visible: true,
    disabled: false,
  };
};
const handleAddTwo = () => {
  state.currentType = 2;
  state.formAddData.deviceType = "1";
  state.formAddData.addnum = 1;
  state.adddialogTwo = {
    title: "批量新增设备台账",
    visible: true,
    disabled: false,
  };
};

//条码新增
const handleBarCode = () => {
  state.currentType = 3;
  state.formAddData.addnum = 1;
  state.formAddData.deviceType = "1";
  state.barcodeDetail=[] as DeviceAccModel[];
  for(let i=0;i<10;i++){
    state.barcodeDetail.push({} as DeviceAccModel);
  }
  state.barcodeDialog = {
    title: "新增设备台账",
    visible: true,
    disabled: false,
  };
};

const handleEdit = (row: any) => {
  state.currentType = 3;
  state.formEditData = JSON.parse(JSON.stringify(row));;
  state.editdialog = {
    title: "编辑设备台账",
    visible: true,
    disabled: false,
  };
};

const queryList = () => {
  loading.value = true;
  state.search_disabled = true;
  DeviceAction.QueryDeviceAccList(state.queryParams)
    .then((result) => {
      if (result.status === 200) {
        const { res, flag, error } = result.data;
        if (flag === "1") {
          const pageData = res as PageResult<DeviceAccModel[]>;
          state.tableData = pageData.list;
          state.total = pageData.total;
        } else {
          ElMessage.error(error);
        }
        loading.value = false;
        state.search_disabled = false;
      }
      else {
        state.search_disabled = false;
        loading.value = false;
      }
    })
    .catch((error) => {
      loading.value = false;
      state.search_disabled = false;
    });
  loading.value = false;
  state.search_disabled = false;
};

const handleSizeChange = (val: number) => {
  queryParams.value.rows = val;
  queryList();
};

const handleCurrentChange = (val: number) => {
  queryParams.value.page = val;
  queryList();
  if (Object.keys(my_table).length > 0) { if (my_table.value != null) { (my_table.value as any).$refs.bodyWrapper.scrollTop = 0; } }
};

const submitAddForm = () => {
  state.saveDisabled=true;
  if (state.currentType == 0) {
    addFormRef.value.validate((valid: any) => {
      if (valid) {
        state.formAddData.createMan = localStorage.getItem("UserName") || "";
        state.formAddData.curStateType = "1";
        state.formAddData.addflag = 1;
        DeviceAction.AddDeviceAcc(state.formAddData).then((result) => {
          state.saveDisabled=false;
          const { res, flag, error } = result.data;
          if (flag === "1") {
            ElMessage.success("新增成功");
            cancel();
            queryList();
          }
          else {
            ElMessage.error(error || "未知异常...");
          }
        });
      }
    });
  }
  else if (state.currentType == 1) {
    state.formAddData.createMan = localStorage.getItem("UserName") || "";
    state.formAddData.curStateType = "1";
    state.formAddData.addflag = 2;
    DeviceAction.AddDeviceAcc(state.formAddData).then((result) => {
      state.saveDisabled=false;
      const { res, flag, error } = result.data;
      if (flag === "1") {
        ElMessage.success("新增成功");
        cancel();
        queryList();
      }
      else {
        ElMessage.error(error || "未知异常...");
      }
    });
  }
  else if (state.currentType == 2) {
    state.formAddData.createMan = localStorage.getItem("UserName") || "";
    state.formAddData.curStateType = "1";
    state.formAddData.addflag = 3;
    DeviceAction.AddDeviceAcc(state.formAddData).then((result) => {
      state.saveDisabled=false;
      const { res, flag, error } = result.data;
      if (flag === "1") {
        ElMessage.success("新增成功");
        cancel();
        queryList();
      }
      else {
        ElMessage.error(error || "未知异常...");
      }
    });
  }
};

const submitEditForm = () => {
  DeviceAction.EditDeviceAcc(state.formEditData).then((result) => {
    ElMessage.success("编辑成功");
    cancel();
    queryList();
  });
};

const submitDeleteForm = (row: any) => {
  ElMessageBox.confirm(" 是否删除设备[" + row.deviceSn + "]? ", "提示", {
    cancelButtonText: "取消",
    confirmButtonText: "确认",
    type: "warning",
    center: true,
  })
    .then(() => {
      DeviceAction.DeleteDeviceAcc(row.id).then((result) => {
        const { res, flag, error } = result.data;
        if (flag === "1") {
          ElMessage.success("删除成功");
          queryList();
        }
        else {
          ElMessage.error(error || "未知异常...");
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除成功!",
      });
    });
};

//扫码添加保存
const submitBarCodeAddForm=()=>{
  state.saveDisabled=true;
  state.formAddData.createMan = localStorage.getItem("UserName") || "";
    state.formAddData.curStateType = "1";
    state.formAddData.addflag = 2;
    let arr=[] as string[];
    state.barcodeDetail.forEach(s=>arr.push(s.deviceSn));
    state.formAddData.deviceSn=arr.join(',');
    DeviceAction.AddDeviceAcc(state.formAddData).then((result) => {
      state.saveDisabled=false;
      const { res, flag, error } = result.data;
      if (flag === "1") {
        ElMessage.success("新增成功");
        cancel();
        queryList();
      }
      else {
        ElMessage.error(error || "未知异常...");
      }
    });
}

const cancel = () => {
  if (state.currentType == 0) {
    state.formAddData = {} as DeviceAccModel;
    state.adddialog.visible = false;
  }
  else if (state.currentType == 1) {
    state.formAddData = {} as DeviceAccModel;
    state.adddialogOne.visible = false;
  }
  else if (state.currentType == 2) {
    state.formAddData = {} as DeviceAccModel;
    state.adddialogTwo.visible = false;
  }  else if (state.currentType == 3) {
    state.formAddData = {} as DeviceAccModel;
    state.barcodeDetail=[];
    state.barcodeDialog.visible=false;
  }else {
    state.formEditData = {} as DeviceAccModel;
    state.editdialog.visible = false;
  }
  state.saveDisabled=false;
};

onMounted(() => {
  window.onresize = function () {
    tableHeight.value = document.documentElement.clientHeight - 190;
  };

  queryList();
});

//显示参数配置
const showDevCfg = (row: any) => {
  state.cfgData = row as DeviceAccModel;

  state.cfgdialog = {
    title: "设备参数预览[" + state.cfgData.deviceSn + "]",
    visible: true,
    disabled: false,
  };
}
</script>

<style lang="scss" scoped>
.button {
  margin: 10px 0;
}

.big_box {
  width: 100%;
  height: 640px;
  display: flex;
  justify-content: space-between;
}

/* 设置大盒子的布局为flex布局 */
.left_box {
  width: 55%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.left_box_full {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.right_box {
  width: 45%;
  height: 95%;
  border-radius: 5px 5px 0 0;
  border: 1px solid rgb(204, 204, 204);
  margin-left: 5px;
}

.right_box_header {
  width: 100%;
  height: 60px;
  display: flex;
  justify-content: left; //水平居中
  align-items: center; //垂直居中
}

.right_box_content {
  width: 100%;
  height: 40px;
  border-top: 1px solid rgb(204, 204, 204);
  //overflow-y: auto;
}
</style>