<template>
  <a-card :bordered="false" v-if="indexShow">
    <a-tabs v-model:activeKey="searchFormState.baType" @change="onSearch()">
      <a-tab-pane key="basq" tab="备案申请"/>
      <a-tab-pane key="bgsq" tab="变更申请"/>
      <a-tab-pane key="zxsq" tab="注销申请"/>
    </a-tabs>
    <a-form ref="searchFormRef" name="advanced_search" :model="searchFormState" class="ant-advanced-search-form">
      <a-row :gutter="24">
        <a-col :span="6">
          <a-form-item label="主管海关" name="companyMainHgType">
            <a-select v-model:value="searchFormState.companyMainHgType" placeholder="请选择主管海关"
                      :options="companyMainHgTypeOptions" show-search allow-clear option-filter-prop="label"/>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="申报时间" name="applyTime">
            <a-range-picker v-model:value="searchFormState.applyTime" value-format="YYYY-MM-DD HH:mm:ss" show-time
                            allow-clear/>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="录入时间" name="createTime">
            <a-range-picker v-model:value="searchFormState.createTime" value-format="YYYY-MM-DD HH:mm:ss" show-time
                            allow-clear/>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="单据状态" name="status">
            <a-select v-model:value="searchFormState.status	" placeholder="请选择单据状态"
                      :options="statusOptions" show-search allow-clear option-filter-prop="label"/>
          </a-form-item>
        </a-col>
        <a-col :span="6" :offset="18">
          <div style="width: 100%;display: flex;justify-content: flex-end">
            <a-button type="primary" @click="onSearch()">查询</a-button>
            <a-button style="margin: 0 0 0 8px" @click="reset">重置</a-button>
          </div>
        </a-col>
      </a-row>
    </a-form>
    <s-table
      ref="tableRef"
      :columns="columns"
      :data="loadData"
      :alert="options.alert.show"
      bordered
      :row-key="(record) => record.id"
      :tool-config="toolConfig"
      :row-selection="options.rowSelection"
      v-model:filterParam="filterParam"
      :scroll="{ x: 2000 }"
    >
      <template #operator class="table-operator">
        <a-space>
          <a-button type="primary" @click="onDetail()" v-if="hasPerm('qyRecordAdd') && searchFormState.baType === 'basq'">
            <template #icon>
              <plus-outlined/>
            </template>
            新增
          </a-button>
          <xn-batch-delete
            v-if="hasPerm('qyRecordDelete')"
            :selectedRowKeys="selectedRowKeys"
            @batchDelete="deleteBatchQyRecord"
          />
          <a-button @click="onExport" v-if="hasPerm('qyRecordBatchExport')">
            <template #icon>
              <export-outlined/>
            </template>
            批量导出
          </a-button>
        </a-space>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'companyMainHgType'">
          {{ $TOOL.dictTypeData('zhhg', record.companyMainHgType) }}
        </template>
        <template v-if="column.dataIndex === 'baType'">
          {{ $TOOL.dictTypeData('qybalx', record.baType) }}
        </template>
        <template v-if="column.dataIndex === 'status'">
          {{ $TOOL.dictTypeData('djzt', record.status) }}
        </template>
        <template v-if="column.dataIndex === 'action'">
          <a-space>
            <a @click="onDetail(record, true)" v-if="hasPerm('qyRecordView')">查看</a>
            <a @click="onDetail(record)" v-if="hasPerm('qyRecordEdit') && record.status == 1">编辑</a>
            <a-popconfirm title="确定要删除吗？" @confirm="deleteQyRecord(record)">
              <a-button type="link" danger size="small" v-if="hasPerm('qyRecordDelete') && record.status == 1">删除</a-button>
            </a-popconfirm>
		    <a @click="resultDetailRef.onOpen(record)" v-if="record.status == 3 || record.status == 4">查看回执</a>
		  	<template v-if="(record.baType === 'basq' || record.baType === 'bgsq') && record.status == 3">
				<a @click="onChange(record)">变更</a>
		  	</template>
		  	<template v-else-if="(record.baType === 'basq' || record.baType === 'bgsq') && record.status == 3">
				<a @click="onKill(record)">注销</a>
		  	</template>
          </a-space>
        </template>
      </template>
    </s-table>
  </a-card>
  <Detail v-else ref="detailRef" @onClose="indexShow = true" @successful="onSearch()"/>
  <ResultDetail ref="resultDetailRef"/>
</template>

<script setup name="qyrecord">
import tool from '@/utils/tool'
import {cloneDeep} from 'lodash-es'
import Detail from './detail.vue'
import ResultDetail from './result.vue'
import qyRecordApi from '@/api/yqyc/qyRecordApi'
import downloadUtil from "@/utils/downloadUtil";
import {message, Modal} from "ant-design-vue";
import {ExclamationCircleOutlined} from "@ant-design/icons-vue";
import {createVNode} from "vue";

const {proxy} = getCurrentInstance()
const searchFormState = ref({
  baType: 'basq'
})
const searchFormStateReal = ref(searchFormState.value) // 点击搜索后备份的查询参数
const searchFormRef = ref()
const tableRef = ref()
const filterParam = ref({})
const detailRef = ref()
const resultDetailRef = ref()
const indexShow = ref(true)
const toolConfig = {refresh: true, height: true, columnSetting: true, striped: false}
const columns = ref([
	{
		title: '统一社会信用代码',
		dataIndex: 'companyCode',
	},
	{
		title: '企业注册名称',
		dataIndex: 'companyName',
	},
	{
		title: '申报企业编号',
		dataIndex: 'companyApplyCode',
	},
	{
		title: '主管海关',
		dataIndex: 'companyMainHgType',
	},
	{
		title: '申报类型',
		dataIndex: 'baType',
	},
	{
		title: '申报时间',
		dataIndex: 'applyTime',
	},
	{
		title: '单据状态',
		dataIndex: 'status',
	},
	{
		title: '录入时间',
		dataIndex: 'createTime',
	},
	{
		title: '操作',
		dataIndex: 'action',
		align: 'center',
		width: 200,
		fixed: 'right',
	}
])
// 操作栏通过权限判断是否显示
if (hasPerm(['qyRecordView', 'qyRecordEdit', 'qyRecordDelete'])) {
	columns.value.forEach(v => {
		if (v.dataIndex === 'action') {
			v.width = 200
		}
	})
}
const selectedRowKeys = ref([])
// 列表选择配置
const options = {
  // columns数字类型字段加入 needTotal: true 可以勾选自动算账
  alert: {
    show: true,
    clear: () => {
      selectedRowKeys.value = ref([])
    }
  },
  rowSelection: {
    onChange: (selectedRowKey, selectedRows) => {
      selectedRowKeys.value = selectedRowKey
    }
  }
}
const loadData = (parameter) => {
  tableRef.value.clearSelected()
  // applyTime范围查询条件重载
  if (searchFormStateReal.value.applyTime) {
    searchFormStateReal.value.startApplyTime = searchFormStateReal.value.applyTime[0]
    searchFormStateReal.value.endApplyTime = searchFormStateReal.value.applyTime[1]
    delete searchFormStateReal.value.applyTime
  }
  // createTime范围查询条件重载
  if (searchFormStateReal.value.createTime) {
    searchFormStateReal.value.startCreateTime = searchFormStateReal.value.createTime[0]
    searchFormStateReal.value.endCreateTime = searchFormStateReal.value.createTime[1]
    delete searchFormStateReal.value.createTime
  }
  return qyRecordApi.qyRecordPage(Object.assign(parameter, searchFormStateReal.value)).then((data) => {
    return data
  })
}
// 搜索同时备份参数
const onSearch = (parameter) => {
  searchFormStateReal.value = cloneDeep(Object.assign(searchFormState.value, filterParam.value))
  nextTick(() => {
    tableRef.value.refresh(parameter)
  })
}
// 重置
const reset = () => {
  searchFormRef.value?.resetFields()
  onSearch(true)
}
// 删除
const deleteQyRecord = (record) => {
  let params = [
    {
      id: record.id
    }
  ]
  qyRecordApi.qyRecordDelete(params).then(() => {
    tableRef.value.refresh(true)
  })
}
// 批量删除
const deleteBatchQyRecord = (params) => {
  qyRecordApi.qyRecordDelete(params).then(() => {
    tableRef.value.clearRefreshSelected()
  })
}
// 批量导出
const onExport = () => {
  const params = {
    ...filterParam.value
  }
  if (selectedRowKeys.value.length > 0) {
    params.ids = selectedRowKeys.value
  } else {
    Object.entries(searchFormStateReal.value).forEach(([key, value]) => {
      console.log(key)
      if (proxy.$util.isValue(value)) {
        params[key] = value
      }
    })
  }
  qyRecordApi.qyRecordExport(params).then((res) => {
    downloadUtil.resultDownload(res)
    tableRef.value.clearSelected()
  })
}
// 切换至表单
const onDetail = (record = null, view) => {
  indexShow.value = false
  nextTick(() => {
    detailRef.value.onOpen(record, view)
  })
}
// 变更
const onChange = (record = null) => {
	Modal.confirm({
		title: '请确定是否变更?',
		icon: createVNode(ExclamationCircleOutlined),
		content: createVNode('div', { style: 'color:red;' }, '变更后将重新进行申报'),
		centered: true,
		onOk() {
			const form = cloneDeep(record)
			form.baType = 'bgsq'
			onDetail(form)
		},
		onCancel() {
		},
	});
}
// 注销
const onKill = (record = null) => {
	Modal.confirm({
		title: '确定要对该企业进行注销操作?',
		icon: createVNode(ExclamationCircleOutlined),
		content: createVNode('div', { style: 'color:red;' }, '注销后将该公司将无法进行报关申请等操作'),
		centered: true,
		onOk() {
			let recordData = cloneDeep(record)
			recordData.applyTime = proxy.$util.YMDHms(new Date())
			recordData.status = '3'
			recordData.baType = 'zxsq'
			qyRecordApi.qyRecordSubmitForm(recordData, recordData.id).then(() => {
				onSearch()
			})
		},
		onCancel() {
		},
	});
}
const companyMainHgTypeOptions = tool.dictList('zhhg')
const statusOptions = tool.dictList('djzt')
</script>

<style lang="less" scoped>
</style>
