<!-- eslint-disable camelcase -->
<template>
  <div style="margin-top: 42px">
    <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="['bound_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="'新增'" icon="add" @click="add()"></q-btn>
            <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-btn-group push class="q-ml-md"> </q-btn-group>
            <q-input
              outlined
              rounded
              dense
              debounce="300"
              color="primary"
              v-model="filter"
              :placeholder="$t('search')"
              @input="getSearchList()"
              @keyup.enter="getSearchList()"
            >
              <template v-slot:append>
                <q-icon name="search" @click="getSearchList()" />
              </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" style="max-width: 10px">
                <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-btn
                  icon="print"
                  flat
                  v-print="getPrintConfig()"
                  @click="setCurrentBatch(props.row.container_code)"
                >
                  <q-tooltip>打印条码</q-tooltip>
                </q-btn>
              </q-td>
            </template>

            <template v-if="props.row.id === editid">
              <q-td key="container_code" :props="props">
                <q-input
                  dense
                  outlined
                  square
                  v-model="editFormData.container_code"
                  :label="'托盘编码'"
                  autofocus
                  :rules="[(val) => (val && val.length > 0) || error1]"
                />
              </q-td>
            </template>
            <template v-else-if="props.row.id !== editid">
              <q-td key="container_code" :props="props">{{
                props.row.container_code
              }}</q-td>
            </template>

            <template v-if="props.row.id === editid">
              <q-td key="current_location" :props="props">
                <q-input
                  dense
                  outlined
                  square
                  v-model="editFormData.current_location"
                  :label="'当前位置'"
                  :rules="[(val) => (val && val.length > 0) || error2]"
                />
              </q-td>
            </template>
            <template v-else-if="props.row.id !== editid">
              <q-td key="current_location" :props="props">{{
                props.row.current_location
              }}</q-td>
            </template>

                        <template v-if="props.row.id === editid">
              <q-td key="target_location" :props="props">
                <q-input
                  dense
                  outlined
                  square
                  v-model="editFormData.target_location"
                  :label="'目标位置'"
                  :rules="[(val) => (val && val.length > 0) || error2]"
                />
              </q-td>
            </template>
            <template v-else-if="props.row.id !== editid">
              <q-td key="target_location" :props="props">{{
                props.row.target_location
              }}</q-td>
            </template>

            <template v-if="props.row.id === editid">
              <q-td key="status" :props="props">
                <q-input
                  dense
                  outlined
                  square
                  v-model="editFormData.status"
                  :label="'状态'"
                  :rules="[(val) => (val && val.length > 0) || error2]"
                />
              </q-td>
            </template>
            <template v-else-if="props.row.id !== editid">
              <q-td key="status" :props="props">{{ props.row.status }}</q-td>
            </template>

            <template v-if="props.row.id === editid">
              <q-td key="last_operation" :props="props">
                <q-input
                  dense
                  outlined
                  square
                  v-model="editFormData.last_operation"
                  :label="'最后操作时间'"
                  :rules="[(val) => (val && val.length > 0) || error4]"
                />
              </q-td>
            </template>
            <template v-else-if="props.row.id !== editid">
              <q-td key="last_operation" :props="props">{{
                props.row.last_operation
              }}</q-td>
            </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>

    <div id="printBarcode" class="print-area">
      <div class="q-pa-md text-center" style="flex: none">
        <svg ref="barcodeElement" style="width: 100%; height: auto"></svg>
      </div>
    </div>
    <containercard
      v-if="showInventoryDetails"
      ref="containercard"
      :container-number="select_container_number"
      :container-code="select_container_code"
      :key="select_container_number"

    />
  </div>

</template>

<script>
import { getauth, postauth } from 'boot/axios_request'
import containercard from 'components/containercard.vue'
import JsBarcode from 'jsbarcode'
import { LocalStorage } from 'quasar'

export default {
  name: 'PageContainerlist',
  components: {
    containercard
  },
  data () {
    return {
      goods_code: '',
      goods_desc: '',
      openid: '',
      login_name: '',
      authin: '0',
      searchUrl: '',
      pathname: 'container/list/',
      detailpathname: 'container/detail/',
      pathname_previous: '',
      pathname_next: '',
      separator: 'cell',
      loading: false,
      height: '',
      table_list: [],
      columns: [
        { name: 'detail', label: '详情', field: 'detail', align: 'center' },
        {
          name: 'container_code',
          required: true,
          label: '托盘编码',
          align: 'center',
          field: 'container_code'
        },
        {
          name: 'current_location',
          label: '当前位置',
          field: 'current_location',
          align: 'center'
        },
        {
          name: 'target_location',
          label: '目标位置',
          field: 'target_location',
          align: 'center'
        },
        { name: 'status', label: '托盘状态', field: 'status', align: 'center' },
        {
          name: 'last_operation',
          label: '上次操作时间',
          field: 'last_operation',
          align: 'center'
        }
      ],
      filter: '',
      pagination: {
        page: 1,
        rowsPerPage: 11
      },
      editid: 0,
      editFormData: {},
      detailForm: false,
      activeTab: 'tab1',
      table_detail: [
        {
          container: {
            container_code: '',
            current_location: ''
          },
          batch: {
            bound_number: '',
            goods_desc: '',
            goods_weight: '',
            goods_qty: '',
            creater: ''
          }
        }
      ],
      operate_detail: [],

      newValue: '',

      error1: this.$t('goods.view_goodslist.error1'),
      current: 1,
      max: 0,
      total: 0,
      paginationIpt: 1,
      onlyread: true,
      currentBarcode: '',
      select_container_number: 0,
      select_container_code: 0,
      showInventoryDetails: false,
      filterModels: {
        bound_department: null
      },
      filterdata: {},
      activeSearchField: '',
      activeSearchLabel: ''
    }
  },

  methods: {
     // 处理过滤变化
    handleFilterChange () {
      this.pagination.page = 1
      this.getSearchList(1)
    },
    getFilterOptions (columnName) {
      switch (columnName) {
        case 'type':
          return [
            { label: '生产入库', value: 1 },
            { label: '采购入库', value: 2 },
            { label: '其他入库', value: 3 },
            { label: '调拨入库', value: 4 }
          ]
        case 'bound_status':
          return [
            { label: '待审核', value: 0 },
            { label: '确认无误', value: 1 }
          ]
        case 'bound_department':
          return this.bound_department_list
        default:
          return []
      }
    },
    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.filterdata = searchParams
        this.$q.notify({
          message: `已搜索 ${this.activeSearchLabel} 含有 "${value}" 的结果`,
          icon: 'search',
          color: 'positive'
        })

        // // 重置激活的搜索字段
        this.activeSearchField = ''
        this.activeSearchLabel = ''
      }
    },
    setCurrentBatch (item) {
      this.currentBarcode = item || ''
    },
    getPrintConfig () {
      this.generateBarcode()
      return {
        id: 'printBarcode'
      }
    },
    generateBarcode () {
      this.$refs.barcodeElement.innerHTML = ''

      try {
        JsBarcode(this.$refs.barcodeElement, this.currentBarcode, {
          format: 'CODE128',
          displayValue: true,
          fontSize: 16,
          height: 60,
          margin: 10
        })
      } catch (error) {
        console.error('条码生成失败:', error)
      }
    },
    add () {
      postauth('/container/list/', {})
        .then((res) => {
          this.$q.notify({
            message: '添加成功',
            icon: 'done',
            color: 'positive'
          })
          this.reFresh()
        })
        .catch((err) => {
          this.$q.notify({
            message: err.detail,
            icon: 'close',
            color: 'negative'
          })
        })
    },

    getList (params = {}) {
      var _this = this
      _this.loading = true
      // 合并基础参数
      const baseParams = {
        page: _this.current,
        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 ,// 添加过滤条件
        ...this.filterdata, // 添加其他过滤条件
      })
    },
    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.filterdata = {}
      this.filterModels = {
        bound_department: null
      }
      _this.getSearchList()
    },
    detailData (e) {
      var _this = this
      _this.detailid = e.id
      console.log('detail查询的id是:', _this.detailid)
      getauth(
        _this.detailpathname + '?status__lte=2&container=' + _this.detailid
      )
        .then((res) => {
          if (res.results.length === 0) {
            _this.table_detail = [
              {
                container: {
                  container_code: '',
                  current_location: ''
                },
                batch: {
                  bound_number: '',
                  goods_desc: '',
                  goods_weight: '',
                  goods_qty: '',
                  creater: ''
                }
              }
            ]
            _this.$q.notify({
              message: '该托盘暂无物料信息',
              icon: 'info',
              color: 'positive'
            })
            return
          }
          _this.showInventoryDetails = true
          _this.select_container_number = e.id
          _this.select_container_code = e.container_code
          _this.$refs.containercard.handleclick()
        })
        .catch((err) => {
          _this.$q.notify({
            message: err.detail,
            icon: 'close',
            color: 'negative'
          })
        })
    }
  },
  created () {
    var _this = this
    if (LocalStorage.has('openid')) {
      _this.openid = LocalStorage.getItem('openid')
    } else {
      _this.openid = ''
      LocalStorage.set('openid', '')
    }
    if (LocalStorage.has('login_name')) {
      _this.login_name = LocalStorage.getItem('login_name')
    } else {
      _this.login_name = ''
      LocalStorage.set('login_name', '')
    }
    if (LocalStorage.has('auth')) {
      _this.authin = '1'
      _this.getList()
    } else {
      _this.authin = '0'
    }
  },
  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'
    }
  },
  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);
}
</style>
