<template>
  <div>
    <el-row :gutter="10">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" style="height: 65px;"
        @keyup.enter.native="queryList">
        <el-form-item label="单据编号:" style="margin-left:10px">
          <div style="width:150px;">
            <el-input v-model="queryParams.billCode" placeholder="入库单编号" style="width: 100%;" />
          </div>
        </el-form-item>
        <el-form-item label="库房名称:">
          <div style="width:120px;">
            <el-input v-model="queryParams.stkroomName" placeholder="库房名称" />
          </div>
        </el-form-item>
        <el-form-item label="入库人:">
          <div style="width:120px;">
            <el-input v-model="queryParams.stkinMan" placeholder="入库人" style="width: 100%;" />
          </div>
        </el-form-item>
        <el-form-item label="单据状态:">
          <div style="width:100px;">
            <el-select v-model="queryParams.finishedFlag" placeholder="状态" width="100%" clearable>
              <el-option v-for="(key, value) in Dic.tstkInOrOutState" :key="key" :label="key" :value="value" />
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="时间范围:">
          <el-config-provider :locale="locale">
            <el-date-picker v-model="state.defaultTime" type="daterange" start-placeholder="开始时间" style="width: 270px;"
              end-placeholder="结束时间" :default-time="state.defaultTime" value-format="YYYY-MM-DDTHH:mm:ss" />
          </el-config-provider>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="button" @click="queryList" :disabled="search_disabled">查询入库单</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" :disabled="!currentRow" @click="addBatchCfgTask">新增批量任务</el-button>
        </el-form-item> -->
      </el-form>
    </el-row>
    <el-row :gutter="10">
      <!-- 入库单 -->
      <el-col :span="17" :xs="24">
        <el-table v-loading="loading" :data="state.tableData" border stripe ref="my_table" :height="tableHeight"
          highlight-current-row @current-change="handleCurrentRowChange" :cell-style="{ padding: '0px' }"
          :header-row-style="{ height: '50px' }" :row-style="{ height: '55px' }"
          :header-cell-style="{ background: '#606266', color: '#FFFFFF' }" :row-key="getSelectRowKeys">
          <el-table-column fixed type="index" width="50" align="center" />
          <el-table-column fixed prop="billCode" label="单据编号" header-align="center" width="150" />
          <el-table-column label="入库时间" header-align="center" width="120">
            <template #default="scope">
              {{ tool.dateFormat(scope.row.finishedTime) }}
            </template>
          </el-table-column>
          <el-table-column fit prop="stkroomName" label="库房名称" header-align="center" min-width="120" />
          <el-table-column prop="stkinMan" label="入库人" header-align="center" width="100" />
          <!-- <el-table-column prop="stkinNum" label="数量" header-align="center" align="center" width="60" /> -->
          <!-- <el-table-column prop="unitArea" label="电子签名" header-align="center" width="80" /> -->
          <el-table-column label="状态" header-align="center" align="center" width="80">
            <template #default="scope">
              <el-tag v-if="scope.row.invaildFlag" :type="StateColorMap[scope.row.invaildFlag]" effect="dark"
                size="small">
                {{
                  Dic.tstkInOrOutState[scope.row.finishedFlag]
                }}</el-tag>
              <el-tag v-else type="success" effect="dark" size="small">正常</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="批量任务" header-align="center" width="90">
            <template #default="scope">
              {{ global.getTaskBatchState(scope.row.taskBatchRemoteModel) }}
            </template>
          </el-table-column>

          <el-table-column label="作废时间" header-align="center" width="120">
            <template #default="scope">
              {{ tool.dateFormat(scope.row.invalidTime) }}
            </template>
          </el-table-column> -->
          <el-table-column prop="invalidMan" label="作废人" header-align="center" width="120" />
          <el-table-column prop="invalidBecause" label="作废原因" header-align="center" width="200" />

          <el-table-column prop="stkinMemo" label="备注信息" header-align="center" min-width="150" />

          <el-table-column fixed="right" label="单据操作" align="center" width="240">
            <template #default="scope" :disabled="adminFlag">
              <el-button type="text" @click="handleEditTstkin(scope.row)" :disabled="scope.row.finishedFlag !== '1'">
                编辑
              </el-button>
              <el-button type="text" @click="handleEditTstkinDetail(scope.row)"
                :disabled="scope.row.finishedFlag !== '1'">新增设备</el-button>
              <el-button type="text" @click="handleInvaildTstkin(scope.row)"
                :disabled="!adminFlag || scope.row.finishedFlag !== '1'">作废</el-button>
              <el-button type="text" @click="addBatchCfgTask(scope.row)">批量任务</el-button>
              <!-- <el-button v-else type="text" @click="handleResumeTstkin(scope.row)" :disabled="adminFlag">恢复
              </el-button> -->
            </template>
          </el-table-column>

          <el-table-column fixed="right" label="确认入库" align="center" width="80">
            <template #default="scope" :disabled="adminFlag">
              <el-button type="text" @click="updateFinishedFlag(scope.row)" :disabled="scope.row.finishedFlag !== '1'">
                确认入库
              </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.pagination.small" :disabled="state.pagination.disabled"
            :background="state.pagination.background" layout="total, sizes, prev, pager, next, jumper"
            :total="state.pagination.total" style="text-align: center;margin-top: 10px;" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </el-config-provider>
      </el-col>
      <!-- 设备信息 -->
      <el-col :span="7" :xs="24">
        <el-table v-loading="loading_tstkin_detail" :data="state.tableData_tstkin_detail" border stripe
          :height="tableHeight" highlight-current-row :header-row-style="{ height: '50px' }"
          :header-cell-style="{ background: '#606266', color: '#FFFFFF' }" :row-style="{ height: '55px' }"
          :cell-style="{ padding: '0px' }">
          <el-table-column fixed type="index" width="50" align="center" />
          <el-table-column prop="deviceSn" label="设备SN" header-align="center" width="120" />
          <el-table-column label="类型" header-align="center" align="center" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.deviceType" type="success">{{
                DeviceTypeMap[scope.row.deviceType]
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="batCode" label="电池编号" header-align="center" width="155" />
          <!-- <el-table-column fit prop="stkroomName" label="库房名称" header-align="center" min-width="120" /> -->
          <el-table-column label="" align="center" width="70">
            <template #default="scope" :disabled="adminFlag">
              <el-button type="text" @click="handleRemoveTstkinDetail(scope.row)"
                :disabled="state.select_model.finishedFlag !== '1'">移除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-config-provider :locale="locale">
          <el-pagination v-model:currentPage="queryParams_tstkin_detail.page"
            v-model:page-size="queryParams_tstkin_detail.rows" :page-sizes="[10, 15, 20, 25, 100]"
            :small="state.pagination_tstkin_detail.small" :disabled="state.pagination_tstkin_detail.disabled"
            :background="state.pagination_tstkin_detail.background" layout="total, prev, pager, next, jumper"
            :total="state.pagination_tstkin_detail.total" style="text-align: center; margin-top: 10px; height: 30px"
            @size-change="handleSizeChange_tstkin_detail" @current-change="handleCurrentChange_tstkin_detail" />
        </el-config-provider>
      </el-col>
    </el-row>
  </div>
  <div>
    <!--新增入库单子-->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="1200px" draggable center>
      <el-form ref="dataFormRef" :model="formData" label-width="100px" :rules="rules">
        <div class="big_box">
          <div class="left_box">
            <el-table :data="state.addDataDetail" border stripe style="width: 100%" height="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="170">
                <template #default="scope">
                  <el-input v-model="scope.row.deviceSn" maxlength="11" clearable @blur="inputLostFoucs($event)">
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column label="电池编号" align="center" width="230">
                <template #default="scope">
                  <el-input v-model="scope.row.batCode" maxlength="15" show-word-limit clearable>
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column label="采样间隔" align="center" width="75" >
                <template #default="scope">
                  <span style="font-size:large;">{{ scope.row.sampleInterval }}</span>
                </template>
              </el-table-column>
              <el-table-column label="天线类型" align="center" width="75" >
                <template #default="scope">
                  <span style="font-size:large;">{{ scope.row.tianxianType }}</span>
                </template>
              </el-table-column>
              <el-table-column label="MCU版本" align="center" width="120">
                <template #default="scope">
                  <span style="font-size:15px;">{{ scope.row.softVer }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="right_box">
            <div class="right_box_header">
              <!-- <el-button text @click="openDeviceForm(0)" type="primary">点击新增设备</el-button> -->
              <span style="font-size:18px;margin-left: 10px;">请使用扫码枪录入设备SN和电池编号</span>
            </div>
            <div class="right_box_content">
              <el-form-item label="入库库房:" prop="stkroomId" style="margin-top:10px">
                <div style="width:250px;">
                  <el-select v-model="formData.stkroomId" class="filter-item" placeholder="入库库房" style="width:100%;"
                    :disabled="state.currentType === 2" @change="selectChange">
                    <el-option v-for="item in stkroomData" :key="item.stkroomId" :label="item.stkroomName"
                      :value="item.stkroomId" />
                  </el-select>
                </div>
              </el-form-item>
              <el-form-item label="备注信息:">
                <div style="width:250px;">
                  <el-input v-model="formData.stkinMemo" type="textarea" placeholder="备注信息" style="width:100%;"
                    :disabled="state.currentType === 2" :autosize="{ minRows: 17, maxRows: 17 }" resize="none" />
                </div>
              </el-form-item>
              <!-- <el-space direction="horizontal" wrap="true">
                <el-tag v-for="tag in dynamicTags" :key="tag" closable :disable-transitions="false"
                  @close="handleRemoveTag(tag)" class="el_tag">
                  {{ tag }}
                </el-tag>
              </el-space> -->
            </div>
          </div>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm" :disabled="state.dialog.disabled">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!--编辑入库单子-->
    <el-dialog :title="dialog_tstkin.title" v-model="dialog_tstkin.visible" width="450px" draggable center>
      <el-form ref="dataFormRef" :model="formData_tstkin" label-width="100px" :rules="rules">
        <div class="big_box">
          <div class="left_box_full">
            <el-form-item label="入库库房:" prop="stkroomId">
              <div style="width:260px;">
                <el-select v-model="formData_tstkin.stkroomId" class="filter-item" placeholder="入库库房"
                  style="width:100%;" @change="selectChange">
                  <el-option v-for="item in stkroomData" :key="item.stkroomId" :label="item.stkroomName"
                    :value="item.stkroomId" />
                </el-select>
              </div>
            </el-form-item>
            <el-form-item label="备注信息:">
              <div style="width:260px;">
                <el-input v-model="formData_tstkin.stkinMemo" type="textarea" placeholder="备注信息" style="width:100%;"
                  :autosize="{ minRows: 21, maxRows: 21 }" resize="none" />
              </div>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm" :disabled="state.dialog_tstkin.disabled">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!--作废入库单子-->
    <el-dialog :title="dialog_tstkin_invaild.title" v-model="dialog_tstkin_invaild.visible" width="450px" draggable
      center>
      <el-form :model="formData_tstkin_invaild" label-width="100px" :rules="rules">
        <div class="big_box">
          <div class="left_box_full">
            <el-form-item label="作废原因:">
              <div style="width:260px;">
                <el-input v-model="formData_tstkin_invaild.invalidBecause" type="textarea" placeholder="作废原因"
                  style="width:100%;" :autosize="{ minRows: 24, maxRows: 24 }" resize="none" />
              </div>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitDeleteForm" :disabled="state.dialog_tstkin_invaild.disabled">确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!--设备选择列表-->
    <el-dialog :title="dialog_device.title" v-model="dialog_device.visible" width="450px" height="600px" draggable
      center @opened="queryDeviceList">
      <el-table ref="multipleTableRef" v-loading="loading_device" :data="state.tableData_device" border stripe
        style="width:100%;" height="400" highlight-current-row
        :header-cell-style="{ background: '#606266', color: '#FFFFFF' }" @selection-change="handleSelectionChange"
        :row-key="getRowKeys">
        <el-table-column fixed type="index" width="50" align="center" />
        <el-table-column type="selection" :reserve-selection="true" width="55" align="center" />
        <el-table-column prop="deviceSn" label="设备SN" header-align="center" width="120" />
        <el-table-column label="设备状态" header-align="center" align="center" fit min-width="110">
          <template #default="scope">
            <el-tag size="small">{{ scope.row.curStateTypeName }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <el-config-provider :locale="locale">
        <el-pagination v-model:currentPage="queryParams_device.page" v-model:page-size="queryParams_device.rows"
          :page-sizes="[10, 15, 20, 25, 100]" :small="state.pagination_device.small"
          :disabled="state.pagination_device.disabled" :background="state.pagination_device.background"
          layout="prev, pager, next" :total="state.pagination_device.total"
          style="text-align: center; margin-top: 10px; height: 30px" @size-change="handleSizeChange_device"
          @current-change="handleCurrentChange_device" />
      </el-config-provider>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel_device">取消</el-button>
          <el-button type="primary" @click="submitDevice" :disabled="state.dialog_device.disabled">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!--入库设备列表-->
    <el-dialog :title="dialog_tstkin_detail.title" v-model="dialog_tstkin_detail.visible" width="670px" height="600px"
      draggable center @opened="queryTStkinDetailList">
      <div class="right_box" style="width:100%;">
        <div class="right_box_header" style="justify-content: center;">
          <el-button text @click="openDeviceForm(0)" type="primary">点击新增设备</el-button>
        </div>
        <div class="right_box_content">
          <el-space direction="horizontal" wrap="true">
            <el-tag v-for="tag in dynamicTags" :key="tag" closable :disable-transitions="false"
              @close="handleRemoveTag(tag)" class="el_tag">
              {{ tag }}
            </el-tag>
          </el-space>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel_tstkin_detail">关闭</el-button>
          <el-button @click="add_tstkin_detail">确定新增</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  <el-dialog :title="taskDialog.title" v-model="taskDialog.visible" width="1300px" draggable center
    @close="dialogClose">
    <!-- 使用v-if强制重新渲染 v-if="adddialog.visible" -->
    <batchForm :st-in-object="state.select_model" :isAdd="state.isAdd" :task-type="state.taskType"
      v-if="taskDialog.visible" @change="childMethod"></batchForm>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, toRefs, ref, onMounted } from "vue";
import { ElForm, ElMessage, ElMessageBox, ElTable } from 'element-plus';
import DicStkroomAction from "@/api/systemdictionary/stkroom";
import TStkinAction from "@/api/tstkin";
import DeviceAction from "@/api/deviceacc";
import TStkinDetailAction from "@/api/tstkindetail";
import {
  DicStkroomModel, DicStkroomModelQueryParam, TStkinModel, TStkinModelQueryParam, Dialog, PageResult, DeviceAccModel, DeviceAccQueryParam,
  TStkinDetailModel, TStkinDetailModelQueryParam, TaskBatchRemoteDetailModel, TAicbqCfgQueryParam, TAicbqCfg
} from '@/types';
import tool from "@/until/tool";
import zhCn from 'element-plus/lib/locale/lang/zh-cn';
import Moment from "moment";
import batchForm from '@/components/batchcfg/index.vue';
import global from '@/until/global';
import { stat } from "fs";
import Dic from '@/dictionary';
import TAicbqCfgAction from "@/api/taicbqcfg";
import DicCfg from '@/dictionary/aicbqcfg'
import TAireadAction from "@/api/tairead";

let locale = ref(zhCn)

const dataFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致
const adminFlag = localStorage.getItem("AdminFlag")?.toString() === '1';
const userType = localStorage.getItem("UserType") || "";
const unitCode = localStorage.getItem("UnitCode") || "";

let pageSize = (localStorage.getItem("PageSize") == null ? 10 : localStorage.getItem("PageSize") as unknown as number) * 1;

type mapStatee = Record<string, string>;

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

const StateTypeMap: mapStatee = {
  0: '正常',
  1: '作废',
}

const DeviceTypeMap: mapStatee = {
  0: '正常',
  1: '水表',
}

const loading = ref(false);
const loading_device = ref(false);
const loading_tstkin_detail = ref(false);
const defaultDate = new Date();
const state = reactive({
  currentType: 0,  //0 新增入库单 1 编辑入库单 2 编辑设备清单
  search_disabled: false,
  defaultTime: [Moment(defaultDate.getTime() - 1000 * 3600 * 24 * 30).format("YYYY-MM-DD 00:00:00"), Moment(defaultDate).format("YYYY-MM-DD 23:59:59"),],

  queryParams: { page: 1, rows: pageSize } as TStkinModelQueryParam,
  tableData: [] as TStkinModel[],
  pagination: {
    total: 0,
    small: false,
    background: false,
    disabled: false,
  },

  dialog: {} as Dialog,
  formData: {} as TStkinModel,

  dialog_tstkin: {} as Dialog,
  formData_tstkin: {} as TStkinModel,

  dialog_tstkin_invaild: {} as Dialog,
  formData_tstkin_invaild: {} as TStkinModel,

  dialog_device: {} as Dialog,
  queryParams_device: { page: 1, rows: 30 } as DeviceAccQueryParam,
  tableData_device: [] as DeviceAccModel[],
  pagination_device: {
    total: 0,
    small: false,
    background: false,
    disabled: false,
  },

  dialog_tstkin_detail: {} as Dialog,
  queryParams_tstkin_detail: { page: 1, rows: 100 } as TStkinDetailModelQueryParam,
  tableData_tstkin_detail: [] as TStkinDetailModel[],
  pagination_tstkin_detail: {
    total: 0,
    small: false,
    background: false,
    disabled: false,
  },

  stkroomData: [] as DicStkroomModel[],
  dynamicTags: [] as string[],
  rules: {
    stkroomId: [
      {
        required: true,
        message: '请选择入库库房',
        trigger: 'change',
      },
    ]
  },
  taskDialog: {} as Dialog,
  isAdd: true,
  taskType: 0,
  select_model: {} as TStkinModel,
  addDataDetail: [] as TStkinDetailModel[],
});

const {
  search_disabled,
  queryParams,
  dialog,
  dialog_device,
  queryParams_device,
  formData,
  tableData,
  stkroomData,
  dynamicTags,
  rules,

  dialog_tstkin,
  formData_tstkin,

  dialog_tstkin_invaild,
  formData_tstkin_invaild,

  dialog_tstkin_detail,
  tableData_tstkin_detail,
  queryParams_tstkin_detail,
  taskDialog,
  isAdd,
  taskType
} = toRefs(state);

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

const handleCurrentRowChange = (val: TStkinModel) => {
  currentRow.value = val;
  state.select_model = val;
  state.tableData_tstkin_detail = [] as TStkinDetailModel[];
  if (!tool.objectIsNullOrEmpty(val)) {
    state.queryParams_tstkin_detail.billCode = val.billCode;
    state.tableData_tstkin_detail = [] as TStkinDetailModel[];
    queryTStkinDetailList();
  }
}

const getSelectRowKeys = (row: TStkinModel) => {
  return row.id.toString();
};

const currentRow_device = ref()

const handleCurrentRowChange_device = (val: TStkinModel) => {
  currentRow_device.value = val
}

const handleAdd = () => {
  state.currentType = 0;
  state.formData = {} as TStkinModel;
  state.addDataDetail = [] as TStkinDetailModel[];
  for (let i = 0; i < 25; i++) {
    state.addDataDetail.push({} as TStkinDetailModel)
  }
  state.dynamicTags.splice(0, state.dynamicTags.length)
  state.dialog = {
    title: '新增入库单',
    visible: true,
    disabled: false,
  };
}

const handleEditTstkin = (row: TStkinModel) => {
  state.currentType = 1;
  state.formData_tstkin = JSON.parse(JSON.stringify(row));
  state.queryParams_tstkin_detail = { page: 1, rows: 100, billCode: row.billCode } as TStkinDetailModelQueryParam,
    state.dialog_tstkin = {
      title: '编辑入库单',
      visible: true,
      disabled: false,
    };
}

const handleEditTstkinDetail = (row: TStkinModel) => {
  if (!tool.objectIsNullOrEmpty(row)) {
    state.currentType = 2;
    state.formData_tstkin = JSON.parse(JSON.stringify(row));
    state.queryParams_tstkin_detail.billCode = row.billCode;
    //state.tableData_tstkin_detail = [] as TStkinDetailModel[];
    state.dynamicTags.splice(0, state.dynamicTags.length)
    // state.dialog_tstkin_detail = {
    //   title: '新增设备',
    //   visible: true,
    //   disabled: false,
    // };
    state.formData = JSON.parse(JSON.stringify(row));
    state.addDataDetail = [] as TStkinDetailModel[];
    for (let i = 0; i < 25; i++) {
      state.addDataDetail.push({} as TStkinDetailModel)
    }

    state.dialog = {
      title: '新增设备',
      visible: true,
      disabled: false,
    }
  }
}

const handleSizeChange = (val: number) => {
  queryParams.value.rows = val;
  queryList();
  localStorage.setItem("PageSize", val.toString());
};

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 handleSizeChange_device = (val: number) => {
  queryParams_device.value.rows = val;
  queryDeviceList();
};

const handleCurrentChange_device = (val: number) => {
  queryParams_device.value.page = val;
  queryDeviceList();
};

const handleSizeChange_tstkin_detail = (val: number) => {
  queryParams_tstkin_detail.value.rows = val;
  queryTStkinDetailList();
};

const handleCurrentChange_tstkin_detail = (val: number) => {
  queryParams_tstkin_detail.value.page = val;
  queryTStkinDetailList();
};

const queryList = () => {

  if (!state.defaultTime) {
    ElMessage.warning("请输入要查询的时间范围！！！");
    state.search_disabled = false;
    return;
  }

  state.queryParams.startTime = tool.dateFormat(state.defaultTime[0].toString(), "YYYY-MM-DD HH:mm:ss", "YYYYMMDDHHmmss");
  state.queryParams.endTime = tool.dateFormat(state.defaultTime[1].toString(), "YYYY-MM-DD HH:mm:ss", "YYYYMMDDHHmmss");

  state.tableData_tstkin_detail = [] as TStkinDetailModel[];
  loading.value = true;
  state.search_disabled = true;
  TStkinAction.QueryTStkinModelList(queryParams.value).then(result => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;
      if (flag === "1") {
        const pageData = res as PageResult<TStkinModel[]>;
        state.tableData = pageData.list;
        state.pagination.total = pageData.total;
        loading.value = false;
        state.search_disabled = false;

        if (state.tableData && state.tableData.length > 0) {
          handleCurrentRowChange(pageData.list[0])
        }
      } else {
        ElMessage.error(error || "查询异常...");
        loading.value = false;
        state.search_disabled = false;
      }
    }
  }).catch(error => {
    //请求失败时的操作     
    ElMessage.error(error || "未知异常...");
    loading.value = false;
    state.search_disabled = false;
  })
};

const submitForm = () => {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      if (state.currentType == 0) {
        state.dialog.disabled = true;
        // let deviceSns = state.dynamicTags.join(",")
        // state.formData.devsns = deviceSns;
        state.formData.detailModels = state.addDataDetail;
        state.formData.dataType = 0;
        state.formData.stkinMan = localStorage.getItem("UserName") || "";
        TStkinAction.AddTStkinModel(state.formData).then(result => {
          if (result.status === 200) {
            const { res, flag, error } = result.data;
            if (flag === "1") {
              ElMessage.success('新增成功');
              cancel();
              queryList();
            } else {
              ElMessage.error(error || "未知异常...");
              state.dialog.disabled = false;
            }
          } else {

          }
        }).catch(error => {
          //请求失败时的操作     
          ElMessage.error(error || "未知异常...");
          state.dialog.disabled = false;
        });
      }
      else if (state.currentType > 0) {
        state.dialog_tstkin.disabled = true;
        //state.formData.detailModels = state.addDataDetail;
        state.formData_tstkin.dataType = state.currentType;
        state.formData_tstkin.detailModels = state.addDataDetail;

        TStkinAction.EditTStkinModel(state.formData_tstkin).then(result => {
          if (result.status === 200) {
            const { res, flag, error } = result.data;
            if (flag === "1") {
              ElMessage.success('编辑成功');
              cancel();
              queryList();
              let data = res as TStkinModel;
              if (!tool.objectIsNullOrEmpty(data)) {
                let index = state.tableData.findIndex(p => p.id === data.id);
                state.tableData[index] = data;
              }
              //queryTStkinDetailList();
            } else {
              ElMessage.error(error || "未知异常...");
              state.dialog_tstkin.disabled = false;
            }
          }
        }).catch(error => {
          //请求失败时的操作     
          ElMessage.error(error || "未知异常...");
          state.dialog_tstkin.disabled = false;
        });
      }
    }
  });
};

const handleInvaildTstkin = (row: TStkinModel) => {
  ElMessageBox.confirm(
    ' 是否作废入库单[' + row.billCode + ']? ',
    '提示',
    {
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'warning',
      center: true,
    }
  )
    .then(() => {
      state.formData_tstkin_invaild = JSON.parse(JSON.stringify(row));
      state.dialog_tstkin_invaild = {
        title: '单据作废',
        visible: true,
        disabled: false,
      };
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消作废成功!',
      })
    })
};

const submitDeleteForm = () => {
  state.dialog_tstkin_invaild.disabled = true;
  state.formData_tstkin_invaild.invalidMan = localStorage.getItem("UserName") || "";
  TStkinAction.DeleteTStkinModel(state.formData_tstkin_invaild).then(result => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;
      if (flag === "1") {
        ElMessage.success('作废成功');
        state.dialog_tstkin_invaild.visible = false;
        queryList();
      } else {
        ElMessage.error(error || "未知异常...");
        state.dialog_tstkin_invaild.disabled = false;
      }
    }
  }).catch(error => {
    //请求失败时的操作     
    ElMessage.error(error || "未知异常...");
    state.dialog_tstkin_invaild.disabled = false;
  });;
};

const handleResumeTstkin = (row: TStkinModel) => {
  ElMessageBox.confirm(
    ' 是否恢复入库单[' + row.billCode + ']? ',
    '提示',
    {
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'warning',
      center: true,
    }
  )
    .then(() => {
      state.formData_tstkin = JSON.parse(JSON.stringify(row));
      state.formData_tstkin.invalidBecause = "";
      state.formData_tstkin.invalidMan = "";
      state.formData_tstkin.invaildFlag = "";

      TStkinAction.EditTStkinModel(state.formData_tstkin).then(result => {
        if (result.status === 200) {
          const { res, flag, error } = result.data;
          if (flag === "1") {
            ElMessage.success('恢复成功');
            queryList();
          } else {
            ElMessage.error(error || "未知异常...");
          }
        }
      }).catch(error => {
        //请求失败时的操作     
        ElMessage.error(error || "未知异常...");
      });

    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消作废成功!',
      })
    })
};

const cancel = () => {
  dataFormRef.value.resetFields();
  state.dialog.visible = false;
  state.dialog_tstkin.visible = false;
  state.dialog_tstkin_invaild.visible = false;
}

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


const querySktroomList = () => {
  let data = {} as DicStkroomModelQueryParam;
  DicStkroomAction.QueryDicStkroomList(data).then(result => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;
      if (flag === "1") {
        state.stkroomData = res as DicStkroomModel[];
      } else {
        ElMessage.error(error || "数据异常...");
      }
    }
  }).catch(error => {
    //请求失败时的操作     
    ElMessage.error(error || "未知异常...");
  })
};

//打开设备列表弹窗
const openDeviceForm = (val: number) => {
  state.currentType = val;
  state.dialog_device = {
    title: '设备信息',
    visible: true,
    disabled: false,
  };
}

//移除所选设备
const handleRemoveTag = (tag: string) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}

const cancel_device = () => {
  state.dialog_device.visible = false;
};

const cancel_tstkin_detail = () => {
  state.dialog_tstkin_detail.visible = false;
};

const add_tstkin_detail = () => {
  state.dialog_tstkin_detail.disabled = true;

  if (state.dynamicTags.length === 0) {
    ElMessage.warning("请选择入库设备");
    state.dialog_tstkin_detail.disabled = false;
    return;
  }
  let billCode = state.queryParams_tstkin_detail.billCode;
  if (!billCode) {
    ElMessage.warning("获取入库单信息异常...");
    state.dialog_tstkin_detail.disabled = false;
    return;
  }

  billCode = billCode + "";
  let deviceSns = state.dynamicTags.join(",");
  TStkinDetailAction.AddTStkinDetailModel(billCode, deviceSns).then(result => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;
      if (flag === "1") {
        ElMessage.success('新增成功');
        state.dialog_tstkin_detail.visible = false;

        let index = state.tableData.findIndex(p => p.billCode === billCode);
        state.tableData[index].stkinNum += state.dynamicTags.length;

        queryTStkinDetailList();
      } else {
        ElMessage.error(error || "未知异常...");
      }
    }
  }).catch(error => {
    //请求失败时的操作     
    ElMessage.error(error || "未知异常...");

  });
};

//查询设备信息
const queryDeviceList = () => {
  loading_device.value = true;
  DeviceAction.QueryDeviceAccList(state.queryParams_device)
    .then((result) => {
      if (result.status === 200) {
        const { res, flag, error } = result.data;
        if (flag === "1") {
          const pageData = res as PageResult<DeviceAccModel[]>;
          state.tableData_device = pageData.list;
          state.pagination_device.total = pageData.total;
        } else {
          ElMessage.error(error || "查询设备异常...");
        }
        loading_device.value = false;
      }
      else {
        loading_device.value = false;
      }
    })
    .catch((error) => {
      ElMessage.error(error || "查询设备异常...");
      loading_device.value = false;
    });
};

//查询入库设备明细信息
const queryTStkinDetailList = () => {
  loading_tstkin_detail.value = true;
  TStkinDetailAction.QueryTStkinDetailModelList(state.queryParams_tstkin_detail)
    .then((result) => {
      if (result.status === 200) {
        const { res, flag, error } = result.data;
        if (flag === "1") {
          const pageData = res as PageResult<TStkinDetailModel[]>;
          state.tableData_tstkin_detail = pageData.list;
          state.pagination_tstkin_detail.total = pageData.total;

          // state.tableData_tstkin_detail = res as TStkinDetailModel[];
          // state.pagination_tstkin_detail.total = state.tableData_tstkin_detail.length;
        } else {
          ElMessage.error(error || "查询设备明细异常...");
        }
        loading_tstkin_detail.value = false;
      }
      else {
        loading_tstkin_detail.value = false;
      }
    })
    .catch((error) => {
      ElMessage.error(error || "查询设备明细异常...");
      loading_tstkin_detail.value = false;
    });
};

const handleRemoveTstkinDetail = (row: TStkinDetailModel) => {
  ElMessageBox.confirm(
    ' 是否移除入库设备[' + row.deviceSn + ']? ',
    '提示',
    {
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'warning',
      center: true,
    }
  )
    .then(() => {
      if (Object.keys(row).length === 0) {
        ElMessage.error("未获取到设备信息...");
        return;
      }

      TStkinDetailAction.DeleteTTStkinDetailModel(row.id.toString()).then(result => {
        if (result.status === 200) {
          const { res, flag, error } = result.data;
          if (flag === "1") {
            ElMessage.success('删除成功');
            let index = state.tableData.findIndex(p => p.billCode === row.billCode);
            //state.tableData[index].stkinNum--;

            queryTStkinDetailList();
          } else {
            ElMessage.error(error || "未知异常...");
          }
        }
      }).catch(error => {
        //请求失败时的操作     
        ElMessage.error(error || "未知异常...");
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消移除设备成功!',
      })
    })
};

const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<DeviceAccModel[]>([]);

const getRowKeys = (row: DeviceAccModel) => {
  return row.accId;
};

const handleSelectionChange = (val: DeviceAccModel[]) => {
  multipleSelection.value = val;
};

const submitDevice = () => {

  multipleSelection.value.forEach((eleme) => {
    if (!state.dynamicTags.includes(eleme.deviceSn)) {
      state.dynamicTags.push(eleme.deviceSn);
    }
  });
  multipleTableRef.value?.clearSelection();

  if (state.currentType === 2) {
    addNewTstkinDetail();
  }
  else {
    state.dialog_device.visible = false;
  }
};

const addNewTstkinDetail = () => {
  state.dialog_device.disabled = true;

  if (state.dynamicTags.length === 0) {
    ElMessage.warning("请选择入库设备");
    state.dialog_device.disabled = false;
    return;
  }
  let billCode = state.queryParams_tstkin_detail.billCode;
  if (!billCode) {
    ElMessage.warning("获取入库单信息异常...");
    state.dialog_device.disabled = false;
    return;
  }

  billCode = billCode + "";
  let deviceSns = state.dynamicTags.join(",");
  TStkinDetailAction.AddTStkinDetailModel(billCode, deviceSns).then(result => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;
      if (flag === "1") {
        ElMessage.success('新增成功');
        state.dialog_device.visible = false;
        queryTStkinDetailList();
      } else {
        ElMessage.error(error || "未知异常...");

      }
    }
  }).catch(error => {
    //请求失败时的操作     
    ElMessage.error(error || "未知异常...");

  });
};

const selectChange = (val: any) => {
  let stkroom = state.stkroomData.filter((eleme) => {
    return val == eleme.stkroomId;
  });

  if (state.currentType === 0) {
    state.formData.stkroomName = stkroom.length > 0 ? stkroom[0].stkroomName : "";
  }
  else if (state.currentType === 1) {
    state.formData_tstkin.stkroomName = stkroom.length > 0 ? stkroom[0].stkroomName : "";
  }
};

//添加批量配置任务 2022-10-15 guozhao
const addBatchCfgTask = (val: TStkinModel) => {
  state.taskType = 3;
  state.isAdd = true;
  state.taskDialog = {
    title: "新增批量任务",
    visible: true,
    disabled: false,
  };
}

const dialogClose = () => {
  state.taskDialog = {
    title: "",
    visible: false,
    disabled: true,
  };
}

//子组件保存或取消的返回值
const childMethod = (val: Boolean) => {
  dialogClose();
  if (val) {
    queryList();
  }
}

//SN录入框失去焦点后,10位的补0
const inputLostFoucs = (event: any) => {
  if (event.target.value.length === 10) {
    event.target.value = '0' + event.target.value;
  }
  else if (event.target.value.length < 10) {
    return;
  }

  state.addDataDetail.forEach(s => {
    if (s.deviceSn && event.target.value.includes(s.deviceSn)) {
      s.deviceSn = event.target.value;
      queryDeviceCfg(s);
      bindBatInfoByDeviceAcc(s);
      queryLatestData(s);
    }
  }
  )
}

/**确认入库 */
const updateFinishedFlag = (model: TStkinModel) => {
  ElMessageBox.confirm(
    ' 是否确认当前批次设备均已入库[' + model.billCode + ']? ',
    '提示',
    {
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'warning',
      center: true,
    }
  ).then(() => {
    model.finishedFlag = '2';
    TStkinAction.EditTStkinModel(model).then(result => {
      if (result.status === 200) {
        const { res, flag, error } = result.data;
        if (flag === "1") {
          ElMessage.success('确认入库成功');
          cancel();
          queryList();
          let data = res as TStkinModel;
          if (!tool.objectIsNullOrEmpty(data)) {
            let index = state.tableData.findIndex(p => p.id === data.id);
            state.tableData[index] = data;
          }
          //queryTStkinDetailList();
        } else {
          ElMessage.error(error || "未知异常...");
        }
      }
    }).catch(error => {
      //请求失败时的操作     
      //ElMessage.error(error || "未知异常...");
    });
  })
}

//查询设备配置
const queryDeviceCfg = (row: TStkinDetailModel) => {
  let queryParams = { page: 1, rows: 1, useFlag: '1', deviceSn: row.deviceSn } as TAicbqCfgQueryParam;
  TAicbqCfgAction.QueryTAicbqCfgList(queryParams)
    .then((result) => {
      if (result.status === 200) {
        const { res, flag, errot } = result.data;
        if (flag != undefined && flag == 1) {
          const pageData = res as PageResult<TAicbqCfg[]>;
          if (pageData.list.length > 0) {
            row.sampleInterval = pageData.list[0].sampleInterval;
            row.tianxianType = DicCfg.tianxianType[pageData.list[0].tianxianType];
          } else {
            ElMessage.info("当前设备没有有效的配置记录");
          }
        }
      }
    })
    .catch((error) => {
      //请求失败时的操作
      ElMessage.error(error);
    });
}

//获取最新读数,展示MCU版本,供用户核对
const queryLatestData = (row: TStkinDetailModel) => {
  TAireadAction.QueryLatestTAireadByDeviceSn(row.deviceSn).then((result) => {
    const { res, flag, error } = result.data;
    if (flag != undefined && flag == 1 && res != null) {
      row.softVer = res.softVer;
    }
  });
}

//根据设备台账信息将关联的电池信息显示到窗体
const bindBatInfoByDeviceAcc = (row: TStkinDetailModel) => {
  DeviceAction.FindDeviceAccBysn(row.deviceSn).then((result) => {
    const { res, flag, error } = result.data;
    if (flag != undefined && flag == 1) {
      let deviceAcc = res as DeviceAccModel;
      row.batCode = deviceAcc.batCode;
    }
  });
}

</script>

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

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

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

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

.right_box {
  width: 33%;
  height: 100%;
  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: 452px;
  border-top: 1px solid rgb(204, 204, 204);
  //overflow-y: auto;
}

.el_tag {
  margin-left: 5px;
  margin-top: 5px;
  width: 110px;
}
</style>