<template>
  <div>
    <el-form ref="queryFormRef" :model="queryParams" :inline="true" style="height: 65px;"
      @keyup.enter.native="queryList">
      <el-form-item label="电池编号" style="width: 320px;">
        <el-input v-model="queryParams.batCode" placeholder="电池编号" maxlength="15" show-word-limit clearable />
      </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="handleAddBatch">批量新增</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="batCode" label="电池编号" header-align="center" width="160" />

      <el-table-column label="生产日期" header-align="center" width="110" align="center">
        <template #default="scope">
          {{ tool.dateFormatYMDHm(scope.row.deliveryTime, 'YYYY-MM-DD HH:mm:ss', 'YYYY-MM-DD') }}
        </template>
      </el-table-column>

      <el-table-column prop="batModel" label="电池型号" header-align="center" width="100" />
      <el-table-column prop="manufacturer" label="生产厂商" header-align="center" width="100" />
      <el-table-column prop="batCapacity" label="电池容量" header-align="center" width="100" />
      <el-table-column prop="lastWorkingVoltage" label="当前电压" header-align="center" width="100" />
      <el-table-column prop="batRumTime" label="运行时长" header-align="center" width="100" />
      <el-table-column prop="batRunNum" label="运行次数" header-align="center" width="100" />
      <el-table-column label="电池状态" header-align="center" align="center" width="80">
        <template #default="scope">
          <el-tag>
            {{ deviceStateMap[scope.row.batStatus] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="statusUpdateTime" label="状态更新时间" header-align="center" width="155" />
      <el-table-column prop="createMan" label="登记人" header-align="center" width="80" />
      <el-table-column prop="createTime" label="登记时间" header-align="center" width="155" />

      <el-table-column label="操作" align="center" width="70">
        <template #default="scope">
          <!-- <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="750px" draggable center>
      <el-form ref="dataFormRef" :model="state.formAddDetail" label-width="100px">
        <div class="big_box">
          <div class="left_box">
            <el-table :data="state.formAddDetail" 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="电池编号" align="center" width="300">
                <template #default="scope">
                  <el-input v-model="scope.row.batCode" maxlength="15" 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;">请使用扫码枪录入电池编号</span>
            </div>
            <div class="right_box_content">
              <el-form-item label="生产日期:" style="margin-top: 20px;">
                <el-date-picker v-model="formAddData.deliveryTime" type="date" placeholder="生产日期"
                  value-format="YYYY-MM-DD HH:mm:ss" style="width: 200px;" />
              </el-form-item>

              <el-form-item label="电池型号:">
                <el-input v-model="formAddData.batModel" placeholder="电池型号" style="width:200px;" maxlength="20" />
              </el-form-item>

              <el-form-item label="生产厂商:">
                <el-input v-model="formAddData.manufacturer" placeholder="生产厂商" style="width:200px;" maxlength="30" />
              </el-form-item>

              <el-form-item label="电池容量:">
                <el-input v-model="formAddData.batCapacity" placeholder="电池容量" style="width:200px;" maxlength="10" />
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
      <div style="text-align: center;">
        <el-button @click="cancel()">取消</el-button>
        <el-button type="primary" @click="submitAddForm" :disabled="state.saveDisabled">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="adddialogBatch.title" v-model="adddialogBatch.visible" width="450px" center>
      <el-form ref="addFormRef" :model="formAddData" :rules="state.rules" label-width="100px">
        <el-form-item label="电池编号:" prop="batCode">
          <el-input v-model="formAddData.batCode" placeholder="电池编号" width="150px" maxlength="15" 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>
      </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>
  </div>
</template>

<script lang="ts" setup>
import { reactive, toRefs, toRef, ref, onMounted } from "vue";
import { ElForm, ElMessage, ElMessageBox } from "element-plus";
import BatteryAction from "@/api/batteryacc";
import { BatteryAccQueryParam, BatteryAccModel, Dialog, PageResult } from "@/types";
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import tool from "@/until/tool";

let locale = ref(zhCn);
const my_table = ref();
const adminFlag = localStorage.getItem("AdminFlag")?.toString() === '1';
const addFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致

type mapStatee = Record<string, string>;

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


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

const loading = ref(false);

const state = reactive({
  queryParams: { page: 1, rows: 10 } as BatteryAccQueryParam,
  currentType: 0,//val=0 新增; =1 批量新增一; =2 批量新增二; =3 编辑;
  total: 0,
  small: false,
  background: true,
  disabled: false,
  search_disabled: false,
  adddialog: {} as Dialog,
  adddialogBatch: {} as Dialog,
  editdialog: {} as Dialog,
  formAddData: {} as BatteryAccModel,
  formAddDetail: {} as BatteryAccModel[],
  tableData: [] as BatteryAccModel[],
  cfgdialog: {} as Dialog,
  cfgData: {} as BatteryAccModel,
  rules: {
    deviceSn: [
      { required: true, message: "电池编号不能为空", trigger: "blur" }
    ],
  },
  saveDisabled:false
});

const {
  queryParams,
  total,
  adddialog,
  adddialogBatch,
  editdialog,
  formAddData,
  formAddDetail,
  tableData,
} = toRefs(state);

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

const currentRow = ref();

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

const handleAdd = () => {
  state.currentType = 0;
  state.formAddDetail = [] as BatteryAccModel[];
  for (let i = 0; i < 10; i++) {
    state.formAddDetail.push({} as BatteryAccModel);
  }

  state.adddialog = {
    title: "新增电池台账",
    visible: true,
    disabled: false,
  };
};

const handleAddBatch = () => {
  state.currentType = 1;
  state.adddialogBatch = {
    title: "批量新增电池台账",
    visible: true,
    disabled: false,
  };
};

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

const queryList = () => {
  loading.value = true;
  state.search_disabled = true;
  BatteryAction.QueryBatteryAccList(state.queryParams)
    .then((result) => {
      if (result.status === 200) {
        const { res, flag, error } = result.data;
        if (flag === "1") {
          const pageData = res as PageResult<BatteryAccModel[]>;
          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 = () => {
  //console.log(state.formAddData);
  state.saveDisabled=true;
  state.formAddData.createMan = localStorage.getItem("UserName") || "";
  if (state.currentType == 0) {
    let arrAdd = [] as String[];
    state.formAddDetail.forEach(s => {
      if (s.batCode)
        arrAdd.push(s.batCode);
    })

    if (arrAdd.length == 0) {
      ElMessage.warning("未录入任何数据");
      return;
    }
    state.formAddData.batCode = arrAdd.join(',');
  }

  BatteryAction.AddBatteryAcc(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 submitDeleteForm = (row: any) => {
  ElMessageBox.confirm(" 是否删除电池台账[" + row.batCode + "]? ", "提示", {
    cancelButtonText: "取消",
    confirmButtonText: "确认",
    type: "warning",
    center: true,
  })
    .then(() => {
      BatteryAction.DeleteBatteryAcc(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 cancel = () => {
  if (state.currentType == 0) {
    state.formAddData = {} as BatteryAccModel;
    state.adddialog.visible = false;
  }
  else if (state.currentType == 1) {
    state.formAddData = {} as BatteryAccModel;
    state.adddialogBatch.visible = false;
  }
  state.saveDisabled=false;
};

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

  queryList();
});
</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>