<template>
  <cacp-search-layout>
    <template #search>
      <cacp-search-panel-layout
          :model="state.queryData"
          ref="formRef"
          :rules="rules"
          label-position="left"
          label-width="auto"
          :gutter="30"
          :colSpan="6"
      >
        <el-form-item label="报关单号" prop="entryId">
          <el-input v-model="state.queryData.entryId" clearable />
        </el-form-item>
        <el-form-item label="通关模式" prop="passMode">
          <el-select v-model="state.queryData.passMode" clearable>
            <el-option
                v-for="item in dict.pass_mode"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="运输方式" prop="trafMode">
          <el-select v-model="state.queryData.trafMode" filterable clearable>
            <el-option
                v-for="item in trafMode"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              <span style="float: left">{{ item.label }}</span>
              <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px;">
                {{ item.value }}
                  </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="进出口标识" prop="ieFlag">
          <el-select v-model="state.queryData.ieFlag" clearable>
            <el-option
                v-for="item in dict.ie_flag"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="进出境口岸" prop="iePort">
          <el-select v-model="state.queryData.iePort" filterable
                     clearable>
            <el-option
                v-for="item in iePort"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            >
              <span style="float: left">{{ item.label }}</span>
              <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px;">
                {{ item.value }}
                  </span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="隶属海关" prop="customsCode" v-if="state.isSelect">
          <el-select v-model="state.queryData.customsCode"
                     clearable>
            <el-option
                v-for="item in dict.affiliation_customs_info"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="监管方式" prop="tradeMode">
          <el-select v-model="state.queryData.tradeMode" clearable>
            <el-option
                v-for="item in tradeMode"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              <span style="float: left">{{ item.label }}</span>
              <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px;">
                {{ item.value }}
                  </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报关模式" prop="declMode">
          <el-select v-model="state.queryData.declMode"
                     clearable>
            <el-option
                v-for="item in dict.decl_mode"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否查验" prop="checkFlag">
          <el-select v-model="state.queryData.checkFlag"
                     clearable>
            <el-option
                v-for="item in dict.yes_no"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="结关开始时间" prop="beginReleaseDate">
          <el-date-picker v-model="state.queryData.beginReleaseDate" clearable />
        </el-form-item>
        <el-form-item label="结关结束时间" prop="endReleaseDate">
          <el-date-picker v-model="state.queryData.endReleaseDate" clearable />
        </el-form-item>
        <template #buttonGroup>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button type="info" @click="onReset">重置</el-button>
        </template>
      </cacp-search-panel-layout>
    </template>
    <cacp-complex-table
        :actions="actions"
        :data="tableData"
        :pagination="tablePagination"
        :actionsWidth="50"
        @on-page-change="onPageChange"
        @on-size-change="onSizeChange"
        :loading="loading"
    >
      <el-table-column property="entryId" label="报关单号" sortable  width="160" />
      <el-table-column property="passMode" label="通关模式" width="80">
        <template #default="scope">
          <dict-tag :options="dict.pass_mode" :dictValue="scope.row.passMode"/>
        </template>
      </el-table-column>
      <el-table-column property="trafMode" label="运输方式" width="80">
        <template #default="scope">{{ formatTrafMode(scope.row.trafMode) }}</template>
      </el-table-column>
      <el-table-column property="ieFlag" label="出入境标志" width="90" >
        <template #default="scope">
          <dict-tag :options="dict.ie_flag" :dictValue="scope.row.ieFlag"/>
        </template>
      </el-table-column>
      <el-table-column property="iePort" label="进出境口岸" width="100" >
        <template #default="scope">{{ formatIePort(scope.row.iePort) }}</template>
      </el-table-column>
      <el-table-column property="customsCode" label="主管海关" width="100">
        <template #default="scope">
          <dict-tag :options="dict.affiliation_customs_info" :dictValue="scope.row.customsCode"/>
        </template>
      </el-table-column>
      <el-table-column property="tradeMode" label="监管方式" width="80" >
        <template #default="scope">{{ formatTradeMode(scope.row.tradeMode) }}</template>
      </el-table-column>
      <el-table-column property="declMode" label="报关模式" width="80" >
        <template #default="scope">
          <dict-tag :options="dict.decl_mode" :dictValue="scope.row.declMode"/>
        </template>
      </el-table-column>
      <el-table-column property="tradeCountry" label="贸易国别" width="80" >
        <template #default="scope">{{ formatCountryIso(scope.row.tradeCountry) }}</template>
      </el-table-column>
      <el-table-column property="ieDate" label="进出口时间" sortable width="150">
        <template #default="scope">{{ scope.row.ieDate ? dayjs(scope.row.ieDate).format('YYYY-MM-DD HH:mm:ss'):'' }}</template>
      </el-table-column>
      <el-table-column property="declDate" label="申报时间" sortable width="150">
        <template #default="scope">{{ scope.row.declDate ? dayjs(scope.row.declDate).format('YYYY-MM-DD HH:mm:ss'):'' }}</template>
      </el-table-column>
      <el-table-column property="declAdvanceFlag" label="是否提前申报" width="80" >
        <template #default="scope">
          <dict-tag :options="dict.yes_no" :dictValue="scope.row.declAdvanceFlag"/>
        </template>
      </el-table-column>
      <el-table-column property="acceptDate" label="自动受理时间" sortable width="150">
        <template #default="scope">{{ scope.row.acceptDate ? dayjs(scope.row.acceptDate).format('YYYY-MM-DD HH:mm:ss'):'' }}</template>
      </el-table-column>
      <el-table-column property="exInPortDate" label="货物进港时间" sortable width="150">
        <template #default="scope">{{ scope.row.exInPortDate ? dayjs(scope.row.exInPortDate).format('YYYY-MM-DD HH:mm:ss'):'' }}</template>
      </el-table-column>
      <el-table-column property="consignCode" label="境内收发货人代码" width="130"/>
      <el-table-column property="consignName" label="境内收发货人名称" :show-overflow-tooltip="true" min-width="200">
      </el-table-column>
      <el-table-column property="frnConsignCode" label="境外收发货人代码" width="130"/>
      <el-table-column property="frnConsignName" label="境外收发货人名称(中文)" :show-overflow-tooltip="true" min-width="200">
      </el-table-column>
      <el-table-column property="grossWt" label="货运量毛重" width="100"/>
      <el-table-column property="netWt" label="货运量净重" width="100"/>
      <el-table-column property="rmbPrice" label="货运值人民币(总)" width="130"/>
      <el-table-column property="usdPrice" label="货运值美元(总)" width="130"/>
      <el-table-column property="orderReceiveDate" label="现场接单时间" sortable width="150">
        <template #default="scope">{{ scope.row.orderReceiveDate ? dayjs(scope.row.orderReceiveDate).format('YYYY-MM-DD HH:mm:ss'):'' }}</template>
      </el-table-column>
      <el-table-column property="orderReceiveCost" label="接单耗时(小时)" width="130"/>
      <el-table-column property="certRlsDate" label="单证放行时间" sortable width="150">
        <template #default="scope">{{ scope.row.certRlsDate ? dayjs(scope.row.certRlsDate).format('YYYY-MM-DD HH:mm:ss'):'' }}</template>
      </el-table-column>
      <el-table-column property="preReleaseDate" label="担保放行时间" sortable width="150">
        <template #default="scope">{{ scope.row.preReleaseDate ? dayjs(scope.row.preReleaseDate).format('YYYY-MM-DD HH:mm:ss'):'' }}</template>
      </el-table-column>
      <el-table-column property="agentCode" label="申报单位代码" width="130"/>
      <el-table-column property="agentName" label="申报单位名称" :show-overflow-tooltip="true" min-width="200">
      </el-table-column>
      <el-table-column property="noteS" label="备注" :show-overflow-tooltip="true" min-width="200"/>
      <el-table-column property="ownerCode" label="生产销售单位代码" width="130"/>
      <el-table-column property="ownerName" label="生产销售单位名称" :show-overflow-tooltip="true" min-width="200">
      </el-table-column>
      <el-table-column property="examDate" label="转关数据发送时间" sortable width="150">
        <template #default="scope">{{ scope.row.examDate ? dayjs(scope.row.examDate).format('YYYY-MM-DD HH:mm:ss'):'' }}</template>
      </el-table-column>
      <el-table-column property="checkDate" label="转关数据核销时间" sortable width="150">
        <template #default="scope">{{ scope.row.checkDate ? dayjs(scope.row.checkDate).format('YYYY-MM-DD HH:mm:ss'):'' }}</template>
      </el-table-column>
      <el-table-column property="releaseDate" label="结关时间" sortable width="150">
        <template #default="scope">{{ scope.row.releaseDate ? dayjs(scope.row.releaseDate).format('YYYY-MM-DD HH:mm:ss'):'' }}</template>
      </el-table-column>
      <el-table-column property="cuCost" label="海关通关时间(小时)" width="130"/>
      <el-table-column property="totalCost" label="整体通关时间(小时)" width="130"/>
      <el-table-column property="beforeDeclCost" label="申报前准备时间(小时)" width="130"/>
      <el-table-column property="profVerifyFlag" label="是否专业审单" width="80" >
        <template #default="scope">
          <dict-tag :options="dict.yes_no" :dictValue="scope.row.profVerifyFlag"/>
        </template>
      </el-table-column>
      <el-table-column property="newTwoStepFlag" label="是否新两步申报" width="80" >
        <template #default="scope">
          <dict-tag :options="dict.yes_no" :dictValue="scope.row.newTwoStepFlag"/>
        </template>
      </el-table-column>
      <el-table-column property="assessStartDate" label="现场验估时间" sortable width="150">
        <template #default="scope">{{ scope.row.assessStartDate ? dayjs(scope.row.assessStartDate).format('YYYY-MM-DD HH:mm:ss'):'' }}</template>
      </el-table-column>
      <el-table-column property="assessEndDate" label="验估处置完毕时间" sortable width="150">
        <template #default="scope">{{ scope.row.assessEndDate ? dayjs(scope.row.assessEndDate).format('YYYY-MM-DD HH:mm:ss'):'' }}</template>
      </el-table-column>
      <el-table-column property="checkFlag" label="是否查验" width="80" >
        <template #default="scope">
          <dict-tag :options="dict.yes_no" :dictValue="scope.row.checkFlag"/>
        </template>
      </el-table-column>
      <el-table-column property="checkCustomsCode" label="查验海关" width="100">
        <template #default="scope">
          <dict-tag :options="dict.affiliation_customs_info" :dictValue="scope.row.checkCustomsCode"/>
        </template>
      </el-table-column>
      <el-table-column property="manCreateTime" label="查验指令下达时间" sortable width="150">
        <template #default="scope">{{ scope.row.manCreateTime ? dayjs(scope.row.manCreateTime).format('YYYY-MM-DD HH:mm:ss'):'' }}</template>
      </el-table-column>
      <el-table-column property="manChkTimeStart" label="查验开始时间" sortable width="150">
        <template #default="scope">{{ scope.row.manChkTimeStart ? dayjs(scope.row.manChkTimeStart).format('YYYY-MM-DD HH:mm:ss'):'' }}</template>
      </el-table-column>
      <el-table-column property="manChkTimeEnd" label="查验结束时间" sortable width="150">
        <template #default="scope">{{ scope.row.manChkTimeEnd ? dayjs(scope.row.manChkTimeEnd).format('YYYY-MM-DD HH:mm:ss'):'' }}</template>
      </el-table-column>
      <el-table-column property="manProcResult" label="处理结果" width="100">
        <template #default="scope">
          <dict-tag :options="dict.affiliation_customs_info" :dictValue="scope.row.manProcResult"/>
        </template>
      </el-table-column>
      <el-table-column property="manProcIdea" label="处理意见" width="100">
        <template #default="scope">
          <dict-tag :options="dict.affiliation_customs_info" :dictValue="scope.row.manProcIdea"/>
        </template>
      </el-table-column>
      <el-table-column property="gno" label="商品项号"  width="60" />
      <el-table-column property="iqCode" label="检验检疫编码" width="80" />
      <el-table-column property="codeTs" label="商品编码" width="80" />
      <el-table-column property="gname" label="商品名称" :show-overflow-tooltip="true" min-width="120" />
      <el-table-column property="gmodel" label="规格型号" :show-overflow-tooltip="true" min-width="120" />
      <el-table-column property="qty1" label="第一（法定）数量" width="80" />
      <el-table-column property="rmbPriceList" label="商品货运值人民币" width="130"/>
      <el-table-column property="usdPriceList" label="商品货运值美元" width="130"/>
      <el-table-column property="gCertFlag" label="每项商品需要监管证件" width="130"/>
      <el-table-column property="ungid" label="UN编码" width="130"/>
      <el-table-column property="ungClassify" label="危包类别" width="130"/>
      <el-table-column property="ungGName" label="危险货物名称" :show-overflow-tooltip="true" min-width="120"/>
      <el-table-column property="productCharCode" label="货物属性代码" width="130"/>
      <el-table-column property="goodsType" label="危险品类型" width="130">
        <template #default="scope">
          <dict-tag :options="dict.goods_type" :dictValue="scope.row.goodsType"/>
        </template>
      </el-table-column>
    </cacp-complex-table>
  </cacp-search-layout>
</template>
<script setup lang="ts">
import { useLoading } from '@cacp/ui'
import { exportList, getList} from '@/apis/analyze/goodsEntry'
import type {EntryQuery, Entry} from '@/types/analyze/goodsEntry'
import config from '@/config'
import { getBaseCodeList } from '@/apis/base/baseCode'

import dayjs from 'dayjs'

import {
  SuccessResultCode,
  useComplexTable,
  type SearchPanelLayoutInstance,
  type TableAction
} from '@cacp/ui'
import type { FormRules } from 'element-plus'
import { ref, reactive, onBeforeMount } from 'vue'
import { useRouter } from 'vue-router'
import { permissionStatus } from '@/utils/globalPermission'
import { useDictType } from '@/components/useDict'
import { useCoreStore } from '@/stores'
const coreStore = useCoreStore()

interface State {
  queryData: EntryQuery
  isSelect: boolean
}
const { loading, setLoading } = useLoading()
const { dict } = useDictType('affiliation_customs_info', 'proc_idea', 'proc_result', 'yes_no', 'decl_mode', 'pass_mode', 'ie_flag','goods_type')
const tableHooks = useComplexTable<Entry>(config)
const { tableData, tablePagination, setPagination, setPageIndex, setPageSizes } = tableHooks
const router = useRouter()

const formRef = ref<SearchPanelLayoutInstance>()
//基础数据返回jsonObject
const iePort = ref([]);
const trafMode = ref([]);
const tradeMode = ref([]);
const tradeCountry = ref([]);
const countryIso = ref([]);

const now = dayjs()

const state = reactive<State>({
  queryData: {
    entryId: '',
    beginReleaseDate: now.subtract(1, 'month').format('YYYY-MM-DD'),
    endReleaseDate: now.format('YYYY-MM-DD'),
    ieFlag: '',
    iePort: '',
    customsCode: '',
    passMode: '',
    trafMode: '',
    tradeMode: '',
    declMode: '',
    checkFlag: '',
    goodsType: '1'
  },
  isSelect: false,
})
const rules = reactive<FormRules<EntryQuery>>({
  beginReleaseDate: [{ required: true, message: '请输入结关开始时间', trigger: 'change' }],
  endReleaseDate: [{ required: true, message: '请输入结关结束时间', trigger: 'change' }]
})

const actions = <Array<TableAction>>[
  {
    key: '1',
    text: '查看',
    onclick: onView,
    limit: permissionStatus('one', 'GOODS_ENTRY_VIEW_BT'),
    type: 'primary'
  },
  {
    key: '2',
    text: '导出',
    confirm: true,
    onclick: onExportData,
    limit: permissionStatus('none', 'GOODS_ENTRY_EXPORT_BT'),
    type: 'primary'
  }
]

function onSearch() {
  onPageChange(1)
}

function onReset() {
  formRef.value.resetFields()
  onPageChange(1)
}

function onView(row: Entry) {
  router.push({
    path: '/get-goods',
    query: {
      entryId: row.entryId
    }
  })
}

function onPageChange(page: number) {
  setPageIndex(page)
  onLoadData()
}
function onSizeChange(size: number) {
  setPageSizes(size)
  onLoadData()
}

// 运输方式
function formatTrafMode(code: string): string {
  const result = trafMode.value.find((item) => item.value == code)
  if (result) {
    return result.label
  }
  return ''
}

// 监管方式
function formatTradeMode(code: string): string {
  const result = tradeMode.value.find((item) => item.value == code)
  if (result) {
    return result.label
  }
  return ''
}

// 监管方式
function formatCountryIso(code: string): string {
  const result = countryIso.value.find((item) => item.value == code)
  if (result) {
    return result.label
  }
  return ''
}

// 进出境口岸
function formatIePort(code: string): string {
  const result = iePort.value.find((item) => item.value == code)
  if (result) {
    return result.label
  }
  return ''
}
// 加载数据
async function onLoadData() {
  const loginCustomsCode = coreStore.currentUser.customsCode;
  if("4700" === loginCustomsCode){
    state.isSelect = true;
  }else{
    state.queryData.customsCode = loginCustomsCode;
    state.isSelect = false;
  }
  console.log(state.isSelect);
  const query = { ...state.queryData, pageIndex: tablePagination.currentPage, pageSize: tablePagination.pageSize }
  setLoading(true)
  const res = await getList(query)
  if (res.code == SuccessResultCode) {
    setPagination(res.data)
  }
  // const port = await getBaseCodeList("customsCode")
  // if (port.code == SuccessResultCode) {
  //   iePort.value = port.data
  // }
  setLoading(false)
}

// 加载数据
async function onExportData() : Promise<void>{
  const query = { ...state.queryData}
  await exportList(query);
}

async function getTrafMode() {
  const traf = await getBaseCodeList("TransitMode")
  if (traf.code == SuccessResultCode) {
    trafMode.value = traf.data
  }
}

async function getCustoms() {
  const traf = await getBaseCodeList("customsCode")
  if (traf.code == SuccessResultCode) {
    iePort.value = traf.data
  }
}

async function getTradeMode() {
  const traf = await getBaseCodeList("tradeCode")
  if (traf.code == SuccessResultCode) {
    tradeMode.value = traf.data
  }
}

async function getTradeCountry() {
  const traf = await getBaseCodeList("countryCode")
  if (traf.code == SuccessResultCode) {
    tradeCountry.value = traf.data
  }
}

async function getCountryIso() {
  const traf = await getBaseCodeList("countryIsoE")
  if (traf.code == SuccessResultCode) {
    countryIso.value = traf.data
  }
}

onBeforeMount(async () => {
  await Promise.all([ getCustoms(),getTrafMode(),getTradeMode(),getTradeCountry(),getCountryIso()])
  onLoadData()
//  console.log(dict);
})
</script>
