<template>
  <div>
    <el-row :gutter="10">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" style="height: 65px;"
        @keyup.enter.native="queryList">
        <div>
          <el-form-item label="单据编号:" style="margin-left:10px">
            <div style="width: 150px;">
              <el-input v-model="queryParams.billCode" placeholder="出库单编号" />
            </div>
          </el-form-item>
          <el-form-item label="出库人:">
            <div style="width: 120px;">
              <el-input v-model="queryParams.stkoutMan" placeholder="出库人" />
            </div>
          </el-form-item>
          <el-form-item label="销售商\客户:">
            <el-input v-model="queryParams.agentName" placeholder="销售商\客户" />
          </el-form-item>
          <!-- <el-form-item label="收货人">
            <div style="width: 120px;">
              <el-input v-model="queryParams.consigneeInfo" placeholder="收货人" />
            </div>
          </el-form-item> -->
          <el-form-item label="单据状态:">
            <div style="width:120px;">
              <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: 260px;" 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> -->
        </div>
      </el-form>
    </el-row>
    <el-row :gutter="10">
      <!-- 出库单 -->
      <el-col :span="18" :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 prop="stkoutMan" label="出库人" header-align="center" width="100" />
          <el-table-column prop="stkoutNum" label="出库数量" header-align="center" align="center" width="80" />
          <!-- <el-table-column prop="stkoutSignImg" label="电子签名" header-align="center" width="80" /> -->
          <el-table-column fit prop="agentName" label="销售商\客户名称" header-align="center" align="left" min-width="200" />
          <el-table-column prop="consigneeInfo" label="收货人" header-align="center" width="100" />
          <!-- <el-table-column prop="proofImgUrl" 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.finishedFlag" :type="StateColorMap[scope.row.invaildFlag]" effect="dark">{{
                  Dic.tstkInOrOutState[scope.row.finishedFlag]
              }}</el-tag>
              <el-tag v-else type="success" effect="dark">正常</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="100" />
          <el-table-column fit prop="invalidBecause" label="作废原因" header-align="center" min-width="200" />
          <el-table-column fit prop="stkoutMemo" label="备注信息" header-align="center" width="200" />

          <el-table-column fixed="right" label="单据操作" align="center" width="240">
            <template #default="scope" :disabled="adminFlag">
              <el-button type="text" @click="handleEditTstkout(scope.row)" :disabled="scope.row.finishedFlag !== '1'">
                编辑
              </el-button>
              <el-button type="text" @click="handleEditTstkoutDetail(scope.row)"
                :disabled="scope.row.finishedFlag !== '1'">新增设备</el-button>
              <el-button type="text" @click="handleInvaildTstkout(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="handleResumeTstkout(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="6" :xs="24">
        <el-table v-loading="loading_tstkout_detail" :data="state.tableData_tstkout_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="140px" />
          <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 label="" align="center" width="80">
            <template #default="scope" :disabled="adminFlag">
              <el-button type="text" @click="handleRemoveTstkoutDetail(scope.row)"
                :disabled="state.select_tcheck.finishedFlag !== '1'">移除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-config-provider :locale="locale">
          <el-pagination v-model:currentPage="queryParams_tstkout_detail.page"
            v-model:page-size="queryParams_tstkout_detail.rows" :page-sizes="[10, 15, 20, 25, 100]"
            :small="state.pagination_tstkout_detail.small" :disabled="state.pagination_tstkout_detail.disabled"
            :background="state.pagination_tstkout_detail.background" layout="total, prev, pager, next, jumper"
            :total="state.pagination_tstkout_detail.total" style="text-align: center; margin-top: 10px; height: 30px"
            @size-change="handleSizeChange_tstkout_detail" @current-change="handleCurrentChange_tstkout_detail" />
        </el-config-provider>
      </el-col>
    </el-row>
  </div>
  <div>
    <!--新增出库单子-->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="950px" 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.addDeviceDetail" border stripe style="width: 100%," highlight-current-row
              size="small" height="610px" :header-cell-style="{ background: '#FF000000', color: '#000000' }">
              <el-table-column type="index" width="45" align="center" />
              <el-table-column label="设备SN" align="center" width="255">
                <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="MCU版本" align="center" min-width="80">
                <template #default="scope">
                  <span>{{ scope.row.mcuVersion }}</span>
                </template>
              </el-table-column>

              <!-- <el-table-column label="版本" align="center" width="50">
                <template #default="scope">
                  <span style="color: green;font-weight: bold;font-size: 18px;" v-if="scope.row.verFlag === 1">√</span>
                  <span style="color:red;font-weight: bold;font-size: 18px;"  v-if="scope.row.verFlag === 0">×</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="经销商:" style="margin-top: 15px;">
                <div style="width:260px;">
                  <el-select v-model="formData.agentId" class="filter-item" placeholder="经销商" style="width:100%;"
                    @change="selectChange" :disabled="state.currentType == 2">
                    <el-option v-for="item in tAffiliatedunitData" :key="item.unitCode" :label="item.unitName"
                      :value="item.unitCode" />
                  </el-select>
                </div>
              </el-form-item>
              <el-form-item label="客户" prop="agentName">
                <el-input v-model="formData.agentName" placeholder="经销商/客户" style="width: 260px;"
                  :disabled="state.currentType == 2" />
              </el-form-item>
              <el-form-item label="收货人" prop="consigneeInfo">
                <el-input v-model="formData.consigneeInfo" placeholder="收货人" style="width: 260px;"
                  :disabled="state.currentType == 2" />
              </el-form-item>
              <el-form-item label="MCU版本">
                <el-input v-model="formData.mcuVersion" placeholder="需要校验时填写" style="width: 260px;" maxlength="25"
                  show-word-limit clearable :disabled="state.currentType == 2" />
              </el-form-item>
              <el-form-item label="备注信息:">
                <div style="width:260px;">
                  <el-input v-model="formData.stkoutMemo" type="textarea" placeholder="备注信息" style="width:100%;"
                    :disabled="state.currentType == 2" :autosize="{ minRows: 7, maxRows: 7 }" 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_tstkout.title" v-model="dialog_tstkout.visible" width="450px" draggable center>
      <el-form ref="dataFormRef" :model="formData" label-width="100px" :rules="rules">
        <div class="big_box">
          <div class="left_box_full">
            <el-form-item label="经销商:">
              <div style="width:260px;">
                <el-select v-model="formData.agentId" class="filter-item" placeholder="经销商" style="width:100%;"
                  @change="selectChange">
                  <el-option v-for="item in tAffiliatedunitData" :key="item.unitCode" :label="item.unitName"
                    :value="item.unitCode" />
                </el-select>
              </div>
            </el-form-item>
            <el-form-item label="客户" prop="agentName">
              <div style="width:260px;">
                <el-input v-model="formData.agentName" placeholder="经销商/客户" />
              </div>
            </el-form-item>
            <el-form-item label="收货人" prop="consigneeInfo">
              <div style="width:260px;">
                <el-input v-model="formData.consigneeInfo" placeholder="收货人" />
              </div>
            </el-form-item>
            <el-form-item label="备注信息:">
              <div style="width:260px;">
                <el-input v-model="formData.stkoutMemo" type="textarea" placeholder="备注信息" style="width:100%;"
                  :autosize="{ minRows: 15, maxRows: 15 }" 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_tstkout.disabled">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!--作废出库单子-->
    <el-dialog :title="dialog_tstkout_invaild.title" v-model="dialog_tstkout_invaild.visible" width="450px" draggable
      center>
      <el-form :model="formData_tstkout_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_tstkout_invaild.invalidBecause" type="textarea" placeholder="作废原因"
                  style="width:100%;" :autosize="{ minRows: 15, maxRows: 15 }" 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_tstkout_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
        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_tstkout_detail.title" v-model="dialog_tstkout_detail.visible" width="650px" height="600px"
      draggable center @opened="queryTStkoutDetailList">
      <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_tstkout_detail">关闭</el-button>
          <el-button @click="add_tstkout_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-out-object="state.select_tcheck" :isAdd="state.isAdd" :task-type="state.taskType"
      @change="childMethod" v-if="taskDialog.visible"></batchForm>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, toRefs, ref, onMounted } from "vue";
import { ElForm, ElMessage, ElMessageBox, ElTable } from 'element-plus';
import TAffiliatedunitAction from "@/api/customermanagement/taffiliatedunit";
import TStkoutAction from "@/api/tstkout";
import DeviceAction from "@/api/deviceacc";
import TStkoutDetailAction from "@/api/tstkoutdetail";
import { TStkoutModel, TStkoutModelQueryParam, Dialog, PageResult, DeviceAccModel, DeviceAccQueryParam, TStkoutDetailModel, TStkoutDetailModelQueryParam, TAffiliatedunitModel, TAffiliatedunitQueryParam, TAireadModel } 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 TAireadAction from "@/api/tairead";
import Dic from '@/dictionary';

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_tstkout_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"),],
  tAffiliatedunitData: [] as TAffiliatedunitModel[],
  queryParams_tAffiliatedunit: { page: 1, rows: 999, unitType: "3" } as TAffiliatedunitQueryParam,

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

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

  dialog_tstkout: {} as Dialog,
  formData_tstkout: {} as TStkoutModel,

  dialog_tstkout_invaild: {} as Dialog,
  formData_tstkout_invaild: {} as TStkoutModel,

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

  dialog_tstkout_detail: {} as Dialog,
  queryParams_tstkout_detail: { page: 1, rows: 100 } as TStkoutDetailModelQueryParam,
  tableData_tstkout_detail: [] as TStkoutDetailModel[],
  pagination_tstkout_detail: {
    total: 0,
    small: false,
    background: false,
    disabled: false,
  },

  dynamicTags: [] as string[],
  rules: {
    agentName: [{ required: true, message: "经销商/客户不能为空", trigger: "blur", },],
    consigneeInfo: [{ required: true, message: "收货人不能为空", trigger: "blur", },]
  },
  taskDialog: {} as Dialog,
  isAdd: true,
  taskType: 0,
  select_tcheck: {} as TStkoutModel,
  addDeviceDetail: [] as TStkoutDetailModel[]
});

const {
  search_disabled,
  queryParams,
  tAffiliatedunitData,

  dialog,
  dialog_device,
  queryParams_device,
  formData,
  tableData,
  dynamicTags,
  rules,

  dialog_tstkout,
  formData_tstkout,

  dialog_tstkout_invaild,
  formData_tstkout_invaild,

  dialog_tstkout_detail,
  tableData_tstkout_detail,
  queryParams_tstkout_detail,
  taskDialog,
  isAdd,
  taskType
} = toRefs(state);

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

const handleCurrentRowChange = (val: TStkoutModel) => {
  currentRow.value = val
  state.select_tcheck = val;
  state.tableData_tstkout_detail = [] as TStkoutDetailModel[];
  if (!tool.objectIsNullOrEmpty(val)) {
    state.queryParams_tstkout_detail.billCode = val.billCode;
    state.tableData_tstkout_detail = [] as TStkoutDetailModel[];
    queryTStkoutDetailList();
  }
}

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

const currentRow_device = ref()

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

async function handleAdd() {
  await queryTAffiliatedunitList();
  state.currentType = 0;
  state.formData = {} as TStkoutModel;
  state.addDeviceDetail = [] as TStkoutDetailModel[];
  for (let i = 0; i < 50; i++) {
    state.addDeviceDetail.push({} as TStkoutDetailModel);
  }
  state.dynamicTags.splice(0, state.dynamicTags.length)
  state.dialog = {
    title: '新增出库单',
    visible: true,
    disabled: false,
  };
}

async function handleEditTstkout(row: TStkoutModel) {
  await queryTAffiliatedunitList();
  state.currentType = 1;
  state.formData = JSON.parse(JSON.stringify(row));
  //state.formData_tstkout = JSON.parse(JSON.stringify(row));
  state.queryParams_tstkout_detail = { page: 1, rows: 100, billCode: row.billCode } as TStkoutDetailModelQueryParam,
    state.dialog_tstkout = {
      title: '编辑出库单',
      visible: true,
      disabled: false,
    };
}

async function handleEditTstkoutDetail(row: TStkoutModel) {
  await queryTAffiliatedunitList();
  state.currentType = 2;
  state.addDeviceDetail = [] as TStkoutDetailModel[];
  for (let i = 0; i < 50; i++) {
    state.addDeviceDetail.push({} as TStkoutDetailModel);
  }
  state.formData = JSON.parse(JSON.stringify(row));

  //state.dynamicTags.splice(0, state.dynamicTags.length)
  state.dialog = {
    title: '添加出库设备',
    visible: true,
    disabled: false,
  };
  // if (!tool.objectIsNullOrEmpty(row)) {
  //   state.currentType = 2;
  //   state.queryParams_tstkout_detail.billCode = row.billCode;
  //   state.tableData_tstkout_detail = [] as TStkoutDetailModel[];
  //   state.dynamicTags.splice(0, state.dynamicTags.length)
  //   state.dialog_tstkout_detail = {
  //     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_tstkout_detail = (val: number) => {
  queryParams_tstkout_detail.value.rows = val;
  queryTStkoutDetailList();
};

const handleCurrentChange_tstkout_detail = (val: number) => {
  queryParams_tstkout_detail.value.page = val;
  queryTStkoutDetailList();
};

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_tstkout_detail = [] as TStkoutDetailModel[];
  loading.value = true;
  state.search_disabled = true;
  TStkoutAction.QueryTStkoutModelList(queryParams.value).then(result => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;
      if (flag === "1") {
        const pageData = res as PageResult<TStkoutModel[]>;
        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;
        // if (state.dynamicTags.length === 0) {
        //   ElMessage.warning("请选择出库设备");
        //   state.dialog.disabled = false;
        //   return;
        // }

        //let deviceSns = state.dynamicTags.join(",")
        //state.formData.devsns = deviceSns;
        state.formData.dataType = 0;
        state.formData.detailModels = state.addDeviceDetail;
        state.formData.stkoutMan = localStorage.getItem("UserName") || "";
        TStkoutAction.AddTStkoutModel(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;
            }
          }
        }).catch(error => {
          //请求失败时的操作     
          ElMessage.error(error || "未知异常...");
          state.dialog.disabled = false;
        });
      }
      else if (state.currentType > 0) {
        state.dialog_tstkout.disabled = true;
        state.formData.detailModels = state.addDeviceDetail;
        state.formData.dataType = state.currentType;
        TStkoutAction.EditTStkoutModel(state.formData).then(result => {
          if (result.status === 200) {
            const { res, flag, error } = result.data;
            if (flag === "1") {
              ElMessage.success('保存成功');
              cancel();
              queryList();
              let data = res as TStkoutModel;
              if (!tool.objectIsNullOrEmpty(data)) {
                let index = state.tableData.findIndex(p => p.id === data.id);
                state.tableData[index] = data;
              }
            } else {
              ElMessage.error(error || "未知异常...");
              state.dialog_tstkout.disabled = false;
            }
          }
        }).catch(error => {
          //请求失败时的操作     
          ElMessage.error(error || "未知异常...");
          state.dialog_tstkout.disabled = false;
        });
      }
    }
  });
};

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

const submitDeleteForm = () => {
  state.dialog_tstkout_invaild.disabled = true;
  state.formData_tstkout_invaild.invalidMan = localStorage.getItem("UserName") || "";

  TStkoutAction.DeleteTStkoutModel(state.formData_tstkout_invaild).then(result => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;
      if (flag === "1") {
        ElMessage.success('作废成功');
        state.dialog_tstkout_invaild.visible = false;
        queryList();
      } else {
        ElMessage.error(error || "未知异常...");
        state.dialog_tstkout_invaild.disabled = false;
      }
    }
  }).catch(error => {
    //请求失败时的操作     
    ElMessage.error(error || "未知异常...");
    state.dialog_tstkout_invaild.disabled = false;
  });;
};

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

      TStkoutAction.EditTStkoutModel(state.formData_tstkout).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_tstkout.visible = false;
  state.dialog_tstkout_invaild.visible = false;
}

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

const queryTAffiliatedunitList = () => {
  TAffiliatedunitAction.QueryTAffiliatedunitList(state.queryParams_tAffiliatedunit).then(result => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;
      if (flag === "1") {
        const pageData = res as PageResult<TAffiliatedunitModel[]>;
        state.tAffiliatedunitData = pageData.list;
      } 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_tstkout_detail = () => {
  state.dialog_tstkout_detail.visible = false;
}
const add_tstkout_detail = () => {
  state.dialog_tstkout_detail.disabled = true;

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

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

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

        queryTStkoutDetailList();
      } 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 queryTStkoutDetailList = () => {
  loading_tstkout_detail.value = true;
  TStkoutDetailAction.QueryTStkoutDetailModelList(state.queryParams_tstkout_detail)
    .then((result) => {
      if (result.status === 200) {
        const { res, flag, error } = result.data;
        if (flag === "1") {
          const pageData = res as PageResult<TStkoutDetailModel[]>;
          state.tableData_tstkout_detail = pageData.list;
          state.pagination_tstkout_detail.total = pageData.total;
          // state.tableData_tstkout_detail = res as TStkoutDetailModel[];
          // state.pagination_tstkout_detail.total = state.tableData_tstkout_detail.length;
        } else {
          ElMessage.error(error || "查询设备明细异常...");
        }
        loading_tstkout_detail.value = false;
      }
      else {
        loading_tstkout_detail.value = false;
      }
    })
    .catch((error) => {
      ElMessage.error(error || "查询设备明细异常...");
      loading_tstkout_detail.value = false;
    });
};

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

    TStkoutDetailAction.DeleteTStkoutDetailModel(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].stkoutNum--;

          queryTStkoutDetailList();
        } 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) {
    addNewTstkoutDetail();
  }
  else {
    state.dialog_device.visible = false;
  }
};

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

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

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

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

  });
};

const selectChange = (val: any) => {
  let tAffiliatedunit = state.tAffiliatedunitData.filter((eleme) => {
    return val == eleme.unitCode;
  });

  if (state.currentType === 0) {
    state.formData.agentName = tAffiliatedunit.length > 0 ? tAffiliatedunit[0].unitName : "";
  }
  else if (state.currentType === 1) {
    state.formData_tstkout.agentName = tAffiliatedunit.length > 0 ? tAffiliatedunit[0].unitName : "";
  }
};

//添加批量配置任务 2022-10-15 guozhao
const addBatchCfgTask = (val: TStkoutModel) => {
  state.taskType = 4;
  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.addDeviceDetail.forEach(s => {
    if (s.deviceSn && event.target.value.includes(s.deviceSn)) {
      if (event.target.value.length === 11) {
        s.deviceSn = event.target.value;
        TAireadAction.QueryLatestTAireadByDeviceSn(event.target.value).then((result) => {
          const { res, flag, error } = result.data;
          if (flag != undefined && flag == 1) {
            let readModel = res as TAireadModel;
            if (readModel) {
              s.mcuVersion = readModel.softVer;
            }
          }
        });
      }
    }
  }
  )
}

/**确认出库 */
const updateFinishedFlag = (model: TStkoutModel) => {
  ElMessageBox.confirm(
    ' 是否确认当前批次设备均已出库[' + model.billCode + ']? ',
    '提示',
    {
      cancelButtonText: '取消',
      confirmButtonText: '确认',
      type: 'warning',
      center: true,
    }
  ).then(() => {
    model.finishedFlag = '2';
    TStkoutAction.EditTStkoutModel(model).then(result => {
      if (result.status === 200) {
        const { res, flag, error } = result.data;
        if (flag === "1") {
          ElMessage.success('确认出库成功');
          cancel();
          queryList();
          let data = res as TStkoutModel;
          if (!tool.objectIsNullOrEmpty(data)) {
            let index = state.tableData.findIndex(p => p.id === data.id);
            state.tableData[index] = data;
          }
          //queryTStkinDetailList();
        } else {
          ElMessage.error(error || "未知异常...");
        }
      }
    })
  })
}
</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: 53%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

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

.right_box {
  width: 45%;
  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; //垂直居中
  margin-left: 10px;
}

.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>