<template>
  <div>
    <transition appear enter-active-class="animated fadeIn">
      <q-table
        class="my-sticky-header-column-table shadow-24"
        :data="table_list"
        row-key="id"
        :separator="separator"
        :loading="loading"
        :columns="columns"
        hide-bottom
        :pagination.sync="pagination"
        no-data-label="No data"
        no-results-label="No data you want"
        :table-style="{ height: height }"
        flat
        bordered
      >
        <template v-slot:header-cell="props">
          <q-th :props="props" @dblclick="handleHeaderDblClick(props.col)">
            <!-- 为特定列添加下拉选择器 -->
            <template
              v-if="
                [
                  'type',
                  'audit_status',
                  'save_status',
                  'bound_status',
                  'department',
                ].includes(props.col.name)
              "
            >
              <q-select
                dense
                outlined
                v-model="filterModels[props.col.name]"
                :options="getFilterOptions(props.col.name)"
                option-label="label"
                option-value="value"
                emit-value
                map-options
                clearable
                @input="handleFilterChange"
                style="min-width: 120px"
              >
                <template v-slot:prepend>
                  <span class="text-caption">{{ props.col.label }}</span>
                </template>
              </q-select>
            </template>
            <template v-else>
              {{ props.col.label }}
            </template>
          </q-th>
        </template>
        <template v-slot:top>
          <q-btn-group push>
            <q-btn :label="$t('refresh')" icon="refresh" @click="reFresh()">
              <q-tooltip
                content-class="bg-amber text-black shadow-4"
                :offset="[10, 10]"
                content-style="font-size: 12px"
                >{{ $t("refreshtip") }}</q-tooltip
              >
            </q-btn>
          </q-btn-group>
          <q-space />
          <div class="flex items-center">
            <q-input
              outlined
              rounded
              dense
              debounce="200"
              color="primary"
              v-model="filter"
              :placeholder="'输入单据编号搜索'"
              @input="getSearchList()"
              @keyup.enter="getSearchList()"
            >
              <template v-slot:append>
                <q-icon name="search" />
              </template>
            </q-input>
          </div>
        </template>
        <template v-slot:body="props">
          <q-tr :props="props">
            <template v-if="props.row.id === editid">
              <q-td key="detail" :props="props">
                <q-btn
                  round
                  flat
                  push
                  color="black"
                  icon="description"
                  @click="detailData(props.row)"
                >
                  <q-tooltip
                    content-class="bg-amber text-black shadow-4"
                    :offset="[10, 10]"
                    content-style="font-size: 12px"
                    >{{ "查看单据详情" }}</q-tooltip
                  >
                </q-btn>
              </q-td>
            </template>
            <template v-else-if="props.row.id !== editid">
              <q-td key="detail" :props="props">
                <q-btn
                  round
                  flat
                  push
                  color="black"
                  icon="description"
                  @click="detailData(props.row)"
                >
                  <q-tooltip
                    content-class="bg-amber text-black shadow-4"
                    :offset="[10, 10]"
                    content-style="font-size: 12px"
                    >{{ "查看批次详情" }}</q-tooltip
                  >
                </q-btn>
              </q-td>
            </template>

            <template v-if="props.row.id === editid">
              <q-td key="billId" :props="props">{{ props.row.billId }}</q-td>
            </template>
            <template v-else-if="props.row.id !== editid">
              <q-td key="billId" :props="props">{{ props.row.billId }}</q-td>
            </template>

            <template v-if="props.row.id === editid">
              <q-td key="number" :props="props">{{ props.row.number }}</q-td>
            </template>
            <template v-else-if="props.row.id !== editid">
              <q-td key="number" :props="props">{{ props.row.number }}</q-td>
            </template>

            <template v-if="props.row.id === editid">
              <q-td key="type" :props="props">
                <q-select
                  dense
                  outlined
                  square
                  v-model="editFormData.type"
                  :label="'单据类型'"
                  autofocus
                  :options="bound_code_type_list"
                  option-label="label"
                  option-value="value"
                  emit-value
                  map-options
                  transition-show="scale"
                  transition-hide="scale"
                  :rules="[(val) => (val && val.length > 0) || error1]"
                />
              </q-td>
            </template>
            <template v-else-if="props.row.id !== editid">
              <q-td key="type" :props="props">
                {{ formatBSType(props.row.type) || props.row.type }}</q-td
              >
            </template>

            <template v-if="props.row.id === editid">
              <q-td key="department" :props="props">
                <q-select
                  dense
                  outlined
                  square
                  v-model="editFormData.department"
                  :label="'部门'"
                  :options="bound_department_list"
                  option-label="label"
                  option-value="value"
                  emit-value
                  map-options
                  transition-show="scale"
                  transition-hide="scale"
                  :rules="[(val) => (val && val.length > 0) || error1]"
                />
              </q-td>
            </template>
            <template v-else-if="props.row.id !== editid">
              <q-td key="department" :props="props">
                {{
                  bound_department_map[props.row.department] ||
                  props.row.department
                }}</q-td
              >
            </template>

            <template v-if="props.row.id === editid">
              <q-td key="audit_status" :props="props">{{
                audit_status_name_map[props.row.audit_status] ||
                props.row.audit_status
              }}</q-td>
            </template>
            <template v-else-if="props.row.id !== editid">
              <q-td key="audit_status" :props="props">{{
                audit_status_name_map[props.row.audit_status] ||
                props.row.audit_status
              }}</q-td>
            </template>
            <template v-if="props.row.id === editid">
              <q-td key="save_status" :props="props">{{
                save_status_name_map[props.row.save_status] ||
                props.row.save_status
              }}</q-td>
            </template>
            <template v-else-if="props.row.id !== editid">
              <q-td key="save_status" :props="props">{{
                save_status_name_map[props.row.save_status] ||
                props.row.save_status
              }}</q-td>
            </template>

            <template v-if="props.row.id === editid">
              <q-td key="date" :props="props">{{ props.row.date }}</q-td>
            </template>
            <template v-else-if="props.row.id !== editid">
              <q-td key="date" :props="props">{{ props.row.date }}</q-td>
            </template>

            <template v-if="props.row.id === editid">
              <q-td key="creater" :props="props">
                <q-input
                  dense
                  outlined
                  square
                  v-model.number="editFormData.creater"
                  :label="'经办人'"
                  :rules="[(val) => (val && val > 0) || error1]"
                />
              </q-td>
            </template>
            <template v-else-if="props.row.id !== editid">
              <q-td key="creater" :props="props">{{ props.row.creater }}</q-td>
            </template>

<template v-if="props.row.id === editid">
              <q-td key="bound_status" :props="props">
                {{
                  formatStatusType(props.row.bound_status) ||
                  props.row.bound_status
                }}
              </q-td>
            </template>
            <template v-else-if="props.row.id !== editid">
              <q-td key="bound_status" :props="props">
                <div class="row justify-center items-center">
                  <span>{{
                    formatStatusType(props.row.bound_status) ||
                    props.row.bound_status
                  }}</span>
                  <q-btn
                    v-if="props.row.bound_status === 0"
                    round
                    flat
                    push
                    color="primary"
                    icon="check"
                    size="sm"
                    @click="auditRow(props.row)"
                    class="q-ml-sm"
                  >
                    <q-tooltip
                      content-class="bg-amber text-black shadow-4"
                      :offset="[10, 10]"
                    >
                      审核通过
                    </q-tooltip>
                  </q-btn>
                </div>
              </q-td>
            </template>

            <template v-if="!editMode">
              <q-td key="action" :props="props" style="width: 100px">
                <q-btn
                  round
                  flat
                  push
                  color="dark"
                  icon="trolley"
                  @click="change_status(props.row)"
                >
                  <q-tooltip
                    content-class="bg-amber text-black shadow-4"
                    :offset="[10, 10]"
                    content-style="font-size: 12px"
                    >单据无误</q-tooltip
                  >
                </q-btn>
                <q-btn
                  round
                  flat
                  push
                  color="deep-purple"
                  icon="delete"
                  @click="delete_data(props.row)"
                >
                  <q-tooltip
                    content-class="bg-amber text-black shadow-4"
                    :offset="[10, 10]"
                    >{{ $t("delete") }}</q-tooltip
                  >
                </q-btn>
              </q-td>
            </template>
            <template v-else-if="editMode">
              <template v-if="props.row.id === editid">
                <q-td key="action" :props="props" style="width: 100px">
                  <q-btn
                    round
                    flat
                    push
                    color="secondary"
                    icon="check"
                    @click="editDataSubmit()"
                  >
                    <q-tooltip
                      content-class="bg-amber text-black shadow-4"
                      :offset="[10, 10]"
                      content-style="font-size: 12px"
                      >{{ $t("confirmedit") }}</q-tooltip
                    >
                  </q-btn>
                  <q-btn
                    round
                    flat
                    push
                    color="red"
                    icon="close"
                    @click="editDataCancel()"
                  >
                    <q-tooltip
                      content-class="bg-amber text-black shadow-4"
                      :offset="[10, 10]"
                      content-style="font-size: 12px"
                      >{{ $t("canceledit") }}</q-tooltip
                    >
                  </q-btn>
                </q-td>
              </template>
              <template v-else-if="props.row.id !== editid"></template>
            </template>
          </q-tr>
        </template>
      </q-table>
    </transition>
    <template>
      <div v-show="max !== 0" class="q-pa-lg flex flex-center">
        <div>{{ total }}</div>
        <q-pagination
          v-model="current"
          color="black"
          :max="max"
          :max-pages="6"
          boundary-links
          @click="
            getSearchList(current);
            paginationIpt = current;
          "
        />
        <div>
          <input
            v-model="paginationIpt"
            @blur="changePageEnter"
            @keyup.enter="changePageEnter"
            style="width: 60px; text-align: center"
          />
        </div>
      </div>
      <div v-show="max === 0" class="q-pa-lg flex flex-center">
        <q-btn flat push color="dark" :label="$t('no_data')"></q-btn>
      </div>
    </template>

    <q-dialog
      v-model="detailForm"
      transition-show="jump-down"
      transition-hide="jump-up"
    >
      <q-card style="min-width: 950px; position: relative">
        <q-bar
          class="bg-light-blue-10 text-white rounded-borders"
          style="height: 50px"
        >
          <div>
            {{ "单据信息" }}
          </div>
          <q-space></q-space>
          <q-btn dense flat icon="close" v-close-popup>
            <q-tooltip
              content-class="bg-amber text-black shadow-4"
              :offset="[20, 20]"
              content-style="font-size: 12px"
            >
              {{ $t("index.close") }}</q-tooltip
            >
          </q-btn>
        </q-bar>
        <q-card-section class="q-pt-md">
          <q-tabs v-model="activeTab">
            <q-tab name="tab1" label="单据信息" />
            <q-tab name="tab2" label="对接信息" />
          </q-tabs>
        </q-card-section>
        <!-- 选项卡内容 -->
        <q-tab-panels v-model="activeTab" animated>
          <q-tab-panel name="tab1" style="min-height: 609px">
            <div class="row q-gutter-x-md">
              <div class="col column q-gutter-y-md">
                <q-input
                  dense
                  outlined
                  square
                  v-model="table_detail.date"
                  :label="'单据时间'"
                  :readonly="true"
                />
              </div>
              <div class="col column q-gutter-y-md">
                <q-input
                  dense
                  outlined
                  square
                  v-model="table_detail.number"
                  :label="'单据编码'"
                  :readonly="true"
                />
              </div>
            </div>
            <div
              style="
                float: right;
                padding: 15px 15px 50px 15px;
                min-width: 100%;
              "
              flow="row wrap"
            >
              <q-card class="q-mb-md" bordered>
                <q-card-section>
                  <template>
                    <div class="text-h6 q-mb-md" style="max-width: 800px">
                      {{ "批次信息" }}
                    </div>
                    <template v-if="batch_detail.length > 0">
                      <q-table
                        v-if="batch_detail.length > 0"
                        :data="batch_detail"
                        :columns="columns_batch"
                        row-key="id"
                        flat
                        bordered
                        hide-pagination
                        class="my-sticky-table scrollable-table"
                        :container-style="{ height: 'auto' }"
                        :pagination="{ rowsPerPage: 0 }"
                      >
                      </q-table>
                    </template>
                  </template>
                </q-card-section>
              </q-card>
            </div>
          </q-tab-panel>
          <q-tab-panel name="tab2" style="min-height: 300px">
            <div class="row q-gutter-x-md">
              <div class="col column q-gutter-y-md">
                <q-input
                  dense
                  outlined
                  square
                  v-model="table_detail.date"
                  :label="'单据时间'"
                  :readonly="true"
                />
              </div>
              <div class="col column q-gutter-y-md">
                <q-input
                  dense
                  outlined
                  square
                  v-model="table_detail.number"
                  :label="'单据编码'"
                  :readonly="true"
                />
              </div>
            </div>
            <div
              style="
                float: right;
                padding: 15px 15px 50px 15px;
                min-width: 100%;
              "
              flow="row wrap"
            >
              <q-card class="q-mb-md" bordered>
                <q-card-section>
                  <template>
                    <div class="text-h6 q-mb">
                      {{ formatBSType(detail_type) }}对接信息
                      <q-btn dense flat icon="cached" @click="get_log_list()">
                        <q-tooltip
                          content-class="bg-amber text-black shadow-4"
                          :offset="[20, 20]"
                          content-style="font-size: 12px"
                        >
                          刷新对接日志
                        </q-tooltip>
                      </q-btn>
                      <q-space></q-space>
                    </div>
                    <div class="row q-gutter-x-md">
                      <div class="q-pa-md col">
                        <q-timeline color="primary">
                          <q-timeline-entry
                            v-for="(item, index) in logline"
                            :key="index"
                            :subtitle="
                              item.create_time + '：' + item.log_content
                            "
                            side="left"
                          >
                          </q-timeline-entry>
                        </q-timeline>
                      </div>
                      <div class="q-pa-md col">
                        <q-timeline color="primary">
                          <q-timeline-entry
                            v-for="(stage, stageIndex) in getTimelineStages(
                              table_detail.type
                            )"
                            :key="stageIndex"
                            :subtitle="stage.timestamp"
                            side="left"
                          >
                            <div class="row items-center">
                              <q-btn
                                round
                                dense
                                flat
                                :icon="stage.icon"
                                :color="stage.color"
                                class="q-mr-sm"
                                @click="checkStage(stage)"
                              />
                              <q-expansion-item
                                class="col"
                                v-model="stage.expanded"
                                expand-icon-class="text-primary"
                                :label="stage.title"
                                header-class="text-primary"
                              >
                                <div class="q-pl-md">
                                  <div class="text-body2">
                                    {{ stage.content }}
                                  </div>
                                </div>
                              </q-expansion-item>
                            </div>
                          </q-timeline-entry>
                          <!-- <q-timeline-entry
                            v-for="(item, index) in timeline"
                            :key="index"
                            :subtitle="item.timestamp"
                            side="left"
                          >
                            <div class="row items-center">
                              <q-btn
                                round
                                dense
                                flat
                                :icon="getButtonIcon(item)"
                                :color="getButtonColor(item)"
                                class="q-mr-sm"
                                @click="check_erp(item)"
                              />
                              <q-expansion-item
                                class="col"
                                v-model="item.expanded"
                                expand-icon-class="text-primary"
                                :label="item.title"
                                header-class="text-primary"
                              >
                                <div class="q-pl-md">
                                  <div class="text-body2">
                                    {{ item.content }}
                                  </div>

                                  <div
                                    v-if="item.details"
                                    class="text-caption text-grey q-pt-sm"
                                  >
                                    {{ item.details }}
                                  </div>
                                </div>
                              </q-expansion-item>
                            </div>
                          </q-timeline-entry> -->
                        </q-timeline>
                      </div>
                    </div>
                  </template>
                </q-card-section>
              </q-card>
            </div>
          </q-tab-panel>
        </q-tab-panels>
      </q-card>
    </q-dialog>
    <q-dialog
      v-model="confirmForm"
      position="top"
      transition-show="scale"
      transition-hide="scale"
    >
      <q-card class="shadow-24">
        <q-card-section style="max-height: 325px; width: 500px" class="scroll">
          <div class="text-h6 q-mb-md">{{ "确认入库单" }}</div>
          确定现场数目与入库汇报{{ choose_bill_code }}单计划数目一致吗？
        </q-card-section>
        <div style="float: right; padding: 15px 15px 15px 0">
          <q-btn
            color="white"
            text-color="black"
            style="margin-right: 25px"
            @click="confirmForm = false"
            >{{ $t("cancel") }}</q-btn
          >
          <q-btn color="primary" @click="confirm_status">{{
            $t("submit")
          }}</q-btn>
        </div>
      </q-card>
    </q-dialog>
  </div>
</template>
<router-view />

<script>
import { getauth, putauth, postauth, deleteauth } from 'boot/axios_request'
import moment from 'moment'
import { date, exportFile, LocalStorage } from 'quasar'

export default {
  name: 'Pageasnlist',
  data () {
    return {
      // 新增：过滤模型
      filterModels: {
        type: null,
        audit_status: null,
        save_status: null,
        bound_status: null,
        department: null
      },
      activeSearchField: '', // 当前激活的搜索字段
      activeSearchLabel: '', // 当前激活的搜索字段的标签
      createDate2: '',
      date_range: '',
      proxyDate: '',
      date: '',
      goods_code: '',
      goods_desc: '',
      openid: '',
      login_name: '',
      authin: '0',
      warehouse_code: '',
      warehouse_name: '',
      searchUrl: '',
      pathname: 'wms/outboundBills/',
      pathfilename: 'bound/file/',
      pathname_previous: '',
      pathname_next: '',
      separator: 'cell',
      loading: false,
      height: '',
      printObj: {
        id: 'printMe',
        popTitle: this.$t('inbound.asn')
      },
      table_list: [],
      table_detail: {},
      batch_detail: [],
      bound_code_type_list: [],
      bound_code_type_map: [],
      bound_bs_type_list: [],
      bound_bs_type_map: [],
      bound_desc_list: [],
      bound_desc_map: [],
      bound_department_list: [],
      bound_department_map: [],
      audit_status_name_map: {
        0: '待审核',
        1: '已审核',
        9: '无需审核'
      },

      save_status_name_map: {
        0: '待保存',
        1: '已保存',
        9: '无需保存'
      },

      bound_status_list: [],
      product_list: [],
      product_map: [],
      columns: [
        { name: 'detail', label: '详情', field: 'detail', align: 'center' },
        // { name: 'billId', label: '表单序号', field: 'billId', align: 'center' },
        { name: 'number', label: '单据编号', field: 'number', align: 'center' },
        { name: 'type', label: '业务类型', field: 'type', align: 'center' },
        {
          name: 'department',
          label: '部门',
          field: 'department',
          align: 'center'
        },
        {
          name: 'audit_status',
          label: '审核状态',
          field: 'audit_status',
          align: 'center'
        },
        {
          name: 'save_status',
          label: '保存状态',
          field: 'save_status',
          align: 'center'
        },
        { name: 'date', label: '单据日期', field: 'date', align: 'center' },
        { name: 'creater', label: '经办人', field: 'creater', align: 'center' },
        {
          name: 'bound_status',
          label: '状态',
          field: 'bound_status',
          align: 'center'
        },
        { name: 'action', label: '操作', align: 'center' }
      ],
      // 列定义
      columns_batch: [
        // {
        //   name: "id",
        //   label: "主单ID",
        //   field: (row) => row.bound_billId,
        //   align: "center",
        // },
        // {
        //   name: "entryid",
        //   label: "详单ID",
        //   field: (row) => row.entryIds,
        //   align: "center",
        // },
        {
          name: 'production_batch',
          label: 'ERP批次号',
          field: (row) => row.production_batch,
          align: 'center'
        },
        {
          name: 'goods_code',
          label: '货物编码',
          field: (row) => row.goods_code,
          align: 'center'
        },
        {
          name: 'goods_name',
          label: '货物名称',
          field: (row) => row.goods_name,
          align: 'center'
        },
        {
          name: 'plan_qty',
          label: '计划数量',
          field: (row) => row.goods_out_qty,
          align: 'center'
        },
        {
          name: 'goods_unit',
          label: '单位',
          field: (row) => row.goods_unit,
          align: 'center'
        },
        {
          name: 'create_time',
          label: '创建时间',
          field: (row) => moment(row.create_time).format('YYYY-MM-DD'),
          align: 'center'
        }
      ],

      filter: '',
      product_filter: '',
      pagination: {
        page: 1,
        rowsPerPage: 11
      },
      newForm: false,
      newBatchForm: false,
      newFormData: {},
      newBatchFormData: {},
      newDetailFormData: {},
      editid: 0,
      editFormData: {},
      editMode: false,
      deleteForm: false,
      detailForm: false,
      deleteid: 0,
      detailid: 0,
      bar_code: '',
      error1: this.$t('goods.view_goodslist.error1'),
      max: 0,
      total: 0,
      paginationIpt: 1,
      current: 1,
      onlyread: false,
      bound_batch_list: [],
      activeTab: 'tab1',
      confirmForm: false,
      choose_bill_id: '',
      choose_bill_code: '',
      logline: [],
      timeline: [
        {
          timestamp: '出库汇报',
          title: '单据编码',
          content: '暂无',
          expanded: true,
          type: 1
        },
        {
          timestamp: '出库审核',
          title: '单据编码',
          content: '暂无',
          expanded: true,
          type: 2
        },
        {
          timestamp: '出库保存',
          title: '单据编码',
          content: '暂无',
          expanded: true,
          type: 3
        }
      ],
      detail_type: 0
    }
  },
  computed: {
    interval () {
      return (
        this.$t('download_center.start') +
        ' - ' +
        this.$t('download_center.end')
      )
    }
  },
  methods: {
     // 新增审核行方法
    auditRow (row) {
      const _this = this
      // 调用API更新审核状态
      putauth(`wms/outboundBills/${row.billId}/`, {
        bound_status: 1 // 设置为已审核状态
      })
        .then(res => {
          _this.$q.notify({
            message: '审核状态已更新',
            color: 'positive'
          })
          // 刷新数据
          _this.getSearchList()
        })
        .catch(err => {
          _this.$q.notify({
            message: err.detail || '更新审核状态失败',
            color: 'negative'
          })
        })
    },
    // 检查阶段处理
    // 获取过滤选项
    getFilterOptions (columnName) {
      switch (columnName) {
        case 'type':
          return [
            { label: '销售出库', value: 1 },
            { label: '生产领料', value: 2 },
            { label: '其他出库', value: 3 },
            { label: '调拨出库', value: 4 }
          ]
        case 'audit_status':
          return [
            { label: '待审核', value: 0 },
            { label: '已审核', value: 1 },
            { label: '无需审核', value: 9 }
          ]
        case 'save_status':
          return [
            { label: '待保存', value: 0 },
            { label: '已保存', value: 1 },
            { label: '无需保存', value: 9 }
          ]
        case 'bound_status':
          return [
            { label: '待审核', value: 0 },
            { label: '确认无误', value: 1 }
          ]
        case 'department':
          return this.bound_department_list
        default:
          return []
      }
    },
    // 处理过滤变化
    handleFilterChange () {
      this.pagination.page = 1
      this.getSearchList(1)
    },

    handleHeaderDblClick (column) {
      // 排除不需要搜索的列
      if (['detail', 'action'].includes(column.name)) return

      this.activeSearchField = column.field
      this.activeSearchLabel = column.label

      // 弹出搜索对话框
      this.$q
        .dialog({
          title: `搜索${column.label}`,
          message: `请输入${column.label}的搜索条件`,
          prompt: {
            model: '',
            type: 'text'
          },
          cancel: true,
          persistent: true
        })
        .onOk((data) => {
          // 执行搜索
          this.executeColumnSearch(column.field, data)
        })
        .onCancel(() => {
          this.activeSearchField = ''
          this.activeSearchLabel = ''
        })
    },

    // 执行列搜索
    executeColumnSearch (field, value) {
      // 构建搜索参数
      if (
        field === 'type' ||
        field === 'audit_status' ||
        field === 'save_status' ||
        field === 'bound_status'
      ) {
        const searchParams = {
          [field]: value
        }
        // 清除其他搜索条件
        this.filter = ''
        this.date_range = ''

        // 执行搜索
        this.getList({
          ...searchParams,
          page: 1
        })

        // 重置激活的搜索字段
        this.activeSearchField = ''
        this.activeSearchLabel = ''
      } else {
        const searchParams = {
          [field + '__icontains']: value
        }
        // 清除其他搜索条件
        this.filter = ''
        this.date_range = ''

        // 执行搜索
        this.getList({
          ...searchParams,
          page: 1
        })

        // 重置激活的搜索字段
        this.activeSearchField = ''
        this.activeSearchLabel = ''
      }
    },
    checkStage (stage) {
      const _this = this

      if (stage.type === 1) {
        // 业务汇报阶段处理
        _this.get_log_list()
      } else if (stage.type === 2) {
        // 业务审核阶段处理
        postauth('wms/boundBills/audit/', {
          billid: _this.detailid,
          billtype: _this.detail_type,
          billbase: 1
        }).catch((err) => {
          _this.$q.notify({
            message: err.detail || '审核失败',
            icon: 'close',
            color: 'negative'
          })
        })
      } else if (stage.type === 3) {
        // 业务保存阶段处理
        postauth('wms/boundBills/save/', {
          billid: _this.detailid,
          billtype: _this.detail_type,
          billbase: 1
        })
      }
    },
    // 根据业务类型获取时间线阶段
    getTimelineStages (billType) {
      const stageDefinitions = {
        1: [
          // 销售出库申请 (类型1)
          {
            type: 1,
            icon: '1',
            color: 'primary',
            timestamp: '出库汇报',
            title: '销售出库'
          },
          // {
          //   type: 2,
          //   icon: 'verified',
          //   color: 'orange',
          //   timestamp: '生产审核',
          //   title: '生产审核'
          // }
          {
            type: 3,
            icon: 'save',
            color: 'green',
            timestamp: '出库保存',
            title: '销售出库'
          }
        ],
        2: [
          // 生产领料申请 (类型2)
          {
            type: 1,
            icon: '1',
            color: 'primary',
            timestamp: '领料申请',
            title: '领料申请'
          },
          {
            type: 2,
            icon: 'verified',
            color: 'orange',
            timestamp: '领料审核',
            title: '领料审核'
          }
          // {
          //   type: 3,
          //   icon: 'save',
          //   color: 'green',
          //   timestamp: '采购保存',
          //   title: '采购入库'
          // }
        ],
        3: [
          // 其他出库申请 (类型3)
          {
            type: 1,
            icon: '1',
            color: 'primary',
            timestamp: '出库申请',
            title: '出库申请'
          },
          {
            type: 2,
            icon: 'verified',
            color: 'orange',
            timestamp: '出库审核',
            title: '出库审核'
          }
          // {
          //   type: 3,
          //   icon: "save",
          //   color: "green",
          //   timestamp: "入库完成",
          //   title: "入库完成",
          // },
        ],
        4: [
          // 调拨入库 (类型4)
          {
            type: 1,
            icon: '1',
            color: 'primary',
            timestamp: '调拨发起',
            title: '调拨单据'
          },
          {
            type: 2,
            icon: 'verified',
            color: 'orange',
            timestamp: '调拨审核',
            title: '调拨审核'
          }
          // {
          //   type: 3,
          //   icon: "save",
          //   color: "green",
          //   timestamp: "调拨入库",
          //   title: "调拨完成",
          // },
        ],
        // 默认类型
        default: [
          {
            type: 1,
            icon: '1',
            color: 'primary',
            timestamp: '业务开始',
            title: '业务开始'
          },
          {
            type: 2,
            icon: 'verified',
            color: 'orange',
            timestamp: '业务处理',
            title: '业务处理'
          },
          {
            type: 3,
            icon: 'save',
            color: 'green',
            timestamp: '业务完成',
            title: '业务完成'
          }
        ]
      }

      // 获取对应业务类型的阶段定义
      const stages = stageDefinitions[billType] || stageDefinitions.default

      // 返回带有默认值的副本
      return stages.map((stage) => ({
        expanded: true,
        content: '暂无',
        ...stage
      }))
    },
    getButtonIcon (item) {
      // 根据业务类型决定图标
      if (item.type === 1) return '1' // 入库汇报
      if (item.type === 2) return 'verified' // 入库审核
      if (item.type === 3) return 'save' // 入库保存
      return 'help' // 默认图标
    },

    getButtonColor (item) {
      // 根据业务类型决定颜色
      if (item.type === 1) return 'primary' // 蓝色
      if (item.type === 2) return 'orange' // 橙色
      if (item.type === 3) return 'green' // 绿色
      return 'grey' // 默认颜色
    },
    check_erp (item) {
      var _this = this
      if (item.type === 1) {
        _this.get_log_list()
      } else if (item.type === 2) {
        postauth('wms/boundBills/audit/', {
          billid: _this.detailid,
          billtype: _this.detail_type,
          billbase: 1
        }).catch((err) => {
          _this.$q.notify({
            message: err.detail || '审核失败',
            icon: 'close',
            color: 'negative'
          })
        })
      } else if (item.type === 3) {
        postauth('wms/boundBills/save/', {
          billid: _this.detailid,
          billtype: _this.detail_type,
          billbase: 1
        })
      }
    },
    get_log_list () {
      var _this = this

      getauth('wms/outboundBills/log/?billid=' + _this.detailid)
        .then((res) => {
          if (res && res.results) {
            _this.logline = res.results
          } else {
            console.error('响应中没有 results 属性', res)
          }
        })
        .catch((err) => {
          _this.$q.notify({
            message: err.detail || '获取日志列表时出错',
            icon: 'close',
            color: 'negative'
          })
        })

      postauth('wms/outboundBills/number/', { billid: _this.detailid })
        .then((res) => {
          _this.timeline[0].title = res.bill_number
          _this.timeline[1].title = res.bill_audit
          _this.timeline[2].title = res.bill_save
          _this.detail_type = res.bill_type
          if (res.bill_status === 0) {
            _this.timeline[0].content = 'ERP已发起出库申请，请审核'
            _this.timeline[1].content = '待审核'
            _this.timeline[2].content = '待保存'
          } else if (res.bill_status === 1) {
            _this.timeline[0].content = 'ERP已发起出库申请，已审核'
            _this.timeline[1].content = '已质检或无需质检'
            _this.timeline[2].content = '待入库'
          } else if (res.bill_status === 2) {
            _this.timeline[0].content = 'ERP已发起出库申请，已审核'
            _this.timeline[1].content = '已质检或无需质检'
            _this.timeline[2].content = '已入库'
          }
        })
        .catch((err) => {
          _this.$q.notify({
            message: err.detail || '获取单据编号时出错',
            icon: 'close',
            color: 'negative'
          })
        })
    },
    formatBSType (type) {
      switch (type) {
        case 1:
          return '销售出库申请'
        case 2:
          return '生产领料申请'
        case 3:
          return '其他出库申请'
        case 4:
          return '调拨入库申请'
        default:
          return '未知'
      }
    },
    formatStatusType (type) {
      switch (type) {
        case 0:
          return '待审核'
        case 1:
          return '确认无误'
        case 3:
          return '其他入库'
        case 4:
          return '调拨入库'

        default:
          return '未知'
      }
    },

    getList (params = {}) {
      var _this = this
      _this.loading = true
      // 合并基础参数
      const baseParams = {
        page: _this.current,
        base_type: '1',
        page_size: _this.pagination.rowsPerPage
      }
      // 创建URLSearchParams处理参数
      const queryParams = new URLSearchParams({
        ...baseParams,
        ...params
      })
      console.log(queryParams)
      // 过滤空值参数
      Array.from(queryParams.entries()).forEach(([key, value]) => {
        if (value === '' || value === null || value === undefined) {
          queryParams.delete(key)
        }
      })
      getauth(`${_this.pathname}?${queryParams}`)
        .then((res) => {
          _this.table_list = res.results
          _this.total = res.count
          _this.max = Math.ceil(res.count / _this.pagination.rowsPerPage) || 0
          _this.pathname_previous = res.previous
          _this.pathname_next = res.next
        })
        .catch((err) => {
          _this.$q.notify({
            message: err.detail,
            icon: 'close',
            color: 'negative'
          })
        })
        .finally(() => {
          _this.loading = false
        })
    },
    changePageEnter () {
      if (Number(this.paginationIpt) < 1) {
        this.current = 1
        this.paginationIpt = 1
      } else if (Number(this.paginationIpt) > this.max) {
        this.current = this.max
        this.paginationIpt = this.max
      } else {
        this.current = Number(this.paginationIpt)
      }
      this.getSearchList(this.current)
    },

    // 修改搜索方法以包含过滤条件
    getSearchList (page = 1) {
      this.current = page
      this.paginationIpt = page

      // 构建过滤参数
      const filterParams = {}
      for (const [key, value] of Object.entries(this.filterModels)) {
        if (value !== null && value !== '') {
          filterParams[key] = value
        }
      }

      this.getList({
        number__icontains: this.filter,
        document_date__range: this.date_range,
        ...filterParams // 添加过滤条件
      })
    },
    getfileList () {
      var _this = this
      _this.loading = true
      const params = {
        goods_desc__icontains: _this.filter,
        document_date__range: _this.date_range
      }
      const queryParams = new URLSearchParams({
        ...params
      })
      console.log(queryParams)
      // 过滤空值参数
      Array.from(queryParams.entries()).forEach(([key, value]) => {
        if (value === '' || value === null || value === undefined) {
          queryParams.delete(key)
        }
      })
      console.log(`${_this.pathfilename}?${queryParams}`)
      getauth(`${_this.pathfilename}?${queryParams}`)
        .then((res) => {
          var timeStamp = Date.now()
          var formattedString = date.formatDate(timeStamp, 'YYYYMMDDHHmmss')
          const status = exportFile(
            _this.pathfilename + 'list' + formattedString + '.csv',
            '\uFEFF' + res,
            'text/csv'
          )
          if (status !== true) {
            _this.$q.notify({
              message: 'Browser denied file download...',
              color: 'negative',
              icon: 'warning'
            })
          }
        })
        .catch((err) => {
          _this.$q.notify({
            message: err.detail,
            icon: 'close',
            color: 'negative'
          })
        })
        .finally(() => {
          _this.loading = false
        })
    },

    getListPrevious () {
      var _this = this
      if (LocalStorage.has('auth')) {
        getauth(_this.pathname_previous, {})
          .then((res) => {
            _this.table_list = res.results
            _this.pathname_previous = res.previous
            _this.pathname_next = res.next
          })
          .catch((err) => {
            _this.$q.notify({
              message: err.detail,
              icon: 'close',
              color: 'negative'
            })
          })
      } else {
      }
    },
    getListNext () {
      var _this = this
      if (LocalStorage.has('auth')) {
        getauth(_this.pathname_next, {})
          .then((res) => {
            _this.table_list = res.results

            _this.pathname_previous = res.previous
            _this.pathname_next = res.next
          })
          .catch((err) => {
            _this.$q.notify({
              message: err.detail,
              icon: 'close',
              color: 'negative'
            })
          })
      }
    },
    reFresh () {
      var _this = this
      _this.getSearchList()
    },

    change_status (e) {
      var _this = this
      // _this.loading = true
      _this.detailData(e)
      _this.confirmForm = true
      _this.choose_bill_id = e.billId
      _this.choose_bill_code = e.number
    },
    confirm_status () {
      var _this = this
      _this.loading = true
      const params = {
        billId: _this.choose_bill_id
      }
      postauth('wms/generateoutbound', params)
        .then((res) => {
          if (res.code === 200) {
            _this.$q.notify({
              message: '出库库单生成成功,请到出库管理中查看',
              icon: 'check',
              color: 'green'
            })
          }
          if (res.code === 400) {
            _this.$q.notify({
              message: res.error,
              icon: 'info',
              color: 'info'
            })
          }
        })
        .finally(() => {
          _this.loading = false
          _this.confirmForm = false
          _this.getSearchList()
        })
    },
    delete_data (e) {
      var _this = this

      // 设置要删除的数据ID（根据你的数据结构调整）
      _this.deleteid = e.billId // 如果e是行数据对象，可能需要使用e.id或e.billId
      _this.choose_bill_code = e.number // 保存单据编号用于显示

      // 创建确认对话框
      _this.$q
        .dialog({
          title: '确认删除',
          message: `确定要删除单据编号为【${_this.choose_bill_code}】的记录吗？此操作不可撤销。`,
          cancel: true,
          persistent: true,
          ok: {
            push: true,
            label: '删除',
            color: 'negative'
          },
          cancel: {
            push: true,
            label: '取消',
            color: 'primary'
          }
        })
        .onOk(() => {
          // 用户确认删除
          _this.deleteDataSubmit()
        })
        .onCancel(() => {
          // 用户取消删除
          _this.deleteid = 0
          _this.choose_bill_code = ''
          _this.$q.notify({
            message: '已取消删除操作',
            icon: 'info',
            color: 'info'
          })
        })
    },

    detailData (e) {
      var _this = this
      _this.detailForm = true
      _this.detailid = e.billId
      console.log('detail查询的id是:', _this.detailid)
      getauth(_this.pathname + _this.detailid + '/')
        .then((res) => {
          _this.table_detail = res
        })
        .catch((err) => {
          _this.$q.notify({
            message: err.detail,
            icon: 'close',
            color: 'negative'
          })
        })
      console.log('detail查询的结果是:', _this.table_detail)

      getauth('wms/outmaterials/?bound_billId=' + _this.detailid)
        .then((res) => {
          _this.batch_detail = res.results
        })
        .catch((err) => {
          _this.$q.notify({
            message: err.detail,
            icon: 'close',
            color: 'negative'
          })
        })
      console.log('batch查询的结果是:', _this.batch_detail)
      console.log('batch长度查询的结果是:', _this.batch_detail.length)
      _this.get_log_list()
    },
    deleteDataSubmit () {
      var _this = this
      deleteauth(_this.pathname + _this.deleteid + '/')
        .then((res) => {
          _this.getSearchList()
          _this.$q.notify({
            message: '成功删除数据',
            icon: 'check',
            color: 'green'
          })
        })
        .catch((err) => {
          _this.$q.notify({
            message: err.detail,
            icon: 'close',
            color: 'negative'
          })
        })
    },
    deleteDataCancel () {
      var _this = this
      _this.deleteForm = false
      _this.deleteid = 0
    },

    updateProxy () {
      var _this = this
      _this.proxyDate = _this.date
    }
  },
  created () {
    var _this = this
    if (LocalStorage.has('openid')) {
      _this.openid = LocalStorage.getItem('openid')
    } else {
      _this.openid = ''
      LocalStorage.set('openid', '')
    }
    if (LocalStorage.has('warehouse_code')) {
      _this.warehouse_code = LocalStorage.getItem('warehouse_code')
    }
    if (LocalStorage.has('warehouse_name')) {
      _this.warehouse_name = LocalStorage.getItem('warehouse_name')
    }
    if (LocalStorage.has('login_name')) {
      _this.login_name = LocalStorage.getItem('login_name')
    } else {
      _this.login_name = ''
      LocalStorage.set('login_name', '')
    }
    if (LocalStorage.has('auth')) {
      const timeStamp = Date.now()
      const formattedString = date.formatDate(timeStamp, 'YYYY/MM/DD')
      _this.date = formattedString
      console.log(_this.date)
      _this.authin = '1'
      _this.getList()
    } else {
      _this.authin = '0'
    }
    getauth('warehouse/boundcodetype/', {})
      .then((res) => {
        _this.bound_code_type_list = res.results.map((item) => ({
          label: item.bound_code_type_name,
          value: item.bound_code_type_code
        }))
        // 编码 → 名称的映射（普通对象，确保响应式）
        _this.bound_code_type_map = res.results.reduce((acc, item) => {
          acc[item.bound_code_type_code] = item.bound_code_type_name
          return acc
        }, {})
      })
      .catch((err) => {
        _this.$q.notify({
          message: err.detail,
          icon: 'close',
          color: 'negative'
        })
      })

    getauth('warehouse/boundtype/', {})
      .then((res) => {
        _this.bound_desc_list = res.results.map((item) => ({
          label: item.bound_type_name,
          value: item.bound_type_code
        }))
        // 编码 → 名称的映射（普通对象，确保响应式）
        _this.bound_desc_map = res.results.reduce((acc, item) => {
          acc[item.bound_type_code] = item.bound_type_name
          return acc
        }, {})
      })
      .catch((err) => {
        _this.$q.notify({
          message: err.detail,
          icon: 'close',
          color: 'negative'
        })
      })

    getauth('warehouse/department/?max_page=1000', {})
      .then((res) => {
        _this.bound_department_list = res.results.map((item) => ({
          label: item.department_name,
          value: item.department_code
        }))
        _this.bound_department_map = res.results.reduce((acc, item) => {
          acc[item.department_code] = item.department_name
          return acc
        }, {})
      })
      .catch((err) => {
        _this.$q.notify({
          message: err.detail,
          icon: 'close',
          color: 'negative'
        })
      })

    getauth('warehouse/boundbusiness/', {})
      .then((res) => {
        _this.bound_bs_type_list = res.results.map((item) => ({
          label: item.bound_bs_name,
          value: item.bound_bs_code
        }))
        // 编码 → 名称的映射（普通对象，确保响应式）
        _this.bound_bs_type_map = res.results.reduce((acc, item) => {
          acc[item.bound_bs_code] = item.bound_bs_name
          return acc
        }, {})
      })
      .catch((err) => {
        _this.$q.notify({
          message: err.detail,
          icon: 'close',
          color: 'negative'
        })
      })
  },

  mounted () {
    var _this = this
    if (_this.$q.platform.is.electron) {
      _this.height = String(_this.$q.screen.height - 290) + 'px'
    } else {
      _this.height = _this.$q.screen.height - 290 + '' + 'px'
    }
    _this.newFormData.creater = _this.login_name
  },
  updated () {},
  destroyed () {}
}
</script>
<style scoped>
/* 添加在 <style> 中 */
.q-date__calendar-item--selected {
  transition: all 0.3s ease;
  background-color: #1976d2 !important;
}

.q-date__range {
  background-color: rgba(25, 118, 210, 0.1);
}

:deep(.q-field__label) {
  margin-top: 8px;
  align-self: center;
}

:deep(.q-field__control-container) {
  padding-left: 50px;
  margin-top: -5px;
}
.q-timeline__subtitle {
  font-size: 14px;
  margin-bottom: 8px;
}

/* 修改滚动样式 */
.scrollable-table {
  flex: 1; /* 允许表格填充剩余空间 */
  display: flex;
  flex-direction: column;
}

.scrollable-table .q-table__container {
  flex: 1;
  overflow: auto;
}

.scrollable-table .q-table__top {
  position: sticky;
  top: 0;
  background: white;
  z-index: 1;
}

.my-sticky-table .q-table__middle {
  overflow-y: auto !important;
}
</style>
