<script setup lang="ts">
import { useRouter } from 'vue-router'
import { GlobalStore } from '@/stores/index'
import { View,Edit,Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import InStorageForm from './InStorageForm.vue'
import InStorageEdit from './InStorageEdit.vue'
import InStorageWarehouse from './InStorageWarehouse.vue'


import {ref, reactive, nextTick} from 'vue'
import TableBase from '@/components/TableBase/index.vue'
import type { ColumnProps } from '@/components/TableBase/interface/index'
import {Storehouse_StockIn_Apply_Warehouse_List, Storehouse_StockIn_Apply_del, stockInExcelBatch} from '@/api/storehouse/index'
import { depotHooks } from '@/hooks/useDepot'

const router = useRouter()
const globalStore = GlobalStore()
const TableRef = ref<InstanceType<typeof TableBase> | null>(null)
const multipleSelection = ref<any[]>([])

const columns: ColumnProps[] = [
  { type: 'selection', width: '44px', fixed: 'left'},
  { type: 'index', label: '序号', width: 80 },
  { prop: 'T_number', label: '退库单号' },
  { prop: 'T_application_date', label: '申请日期' },
  { prop: 'T_submit_name', label: '经办人' },
  { prop: 'T_return_user_name', label: '退库人' },
  { prop: 'T_depot_name', label: '退库仓库' },
  { prop: 'T_date', label: '退库日期' },
  { prop: 'T_state', label: '状态' ,name: 'T_state'},
  { prop: 'operation', label: '操作', width: 260, fixed: 'right' }
]

const InStorageFormRef = ref<InstanceType<typeof InStorageForm> | null>(null)
const InStorageRef = ref()
const InStorageWarehouseRef = ref()

/**
 * 查看详情
 */
const preview = (id: string) => {
  router.push({ name: 'InStorageDetail', params: { id } })
}
/**
 * 编辑
 */
const previewEdit = (row: any) => {
    // console.log('编辑',row,InStorageRef.value)
  InStorageRef.value?.openDrawer(true) // 传递true表示从仓库页面打开
  InStorageRef.value?.getStorehouseContractGet(row.T_number)
  for (let key in InStorageRef.value?.form) {
    if (row.hasOwnProperty(key)) InStorageRef.value.form[key] = row[key];
  }
}

/**
 * 入库
 */
 const previewWarehouse = (row: any) => {
    // console.log('编辑',row,InStorageRef.value)
	InStorageWarehouseRef.value?.openDrawer()
	InStorageWarehouseRef.value?.getStorehouseContractGet(row.T_number)
  for (let key in InStorageWarehouseRef.value?.form) {
    if (row.hasOwnProperty(key)) InStorageWarehouseRef.value.form[key] = row[key];
  }

}

// 搜索
const T_date = ref<string[]>([])

// 状态选项
const stateOptions = [
  { label: '待入库', value: 1 },
  { label: '已入库', value: 2 }
]

const initParam = reactive({
  User_tokey: globalStore.GET_User_tokey,
  T_end_date: '',
  T_start_date: '',
  T_depot_id: '',
  T_name: '',
  T_batch_number: '',
  T_state: ''
})

const searchHandle = () => {
  initParam.T_end_date = T_date.value ? T_date.value[1] : ''
  initParam.T_start_date = T_date.value ? T_date.value[0] : ''
  TableRef.value?.searchTable()
}
/**
 * 添加退库
 */
const openInStorageFormDrawer = () => InStorageFormRef.value?.openDrawer(true) // 传递true表示从仓库页面打开

/**
 * 删除
 */
const deleteFun = (row:any)=>{
    ElMessageBox.confirm(
    '删除操作，是否立即删除?',
    '删除',
    {
      confirmButtonText: '立即删除',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
    }
  ).then(async () => {
    const result:any = await Storehouse_StockIn_Apply_del({T_number:row})
    if(result.Code==200){
        ElMessage.success('删除成功')
        TableRef.value?.searchTable()
    }
    }).catch(() => {})
}


// 拿到仓库列表
const { options } = depotHooks()

// 保存选中的数据id,row-key就是要指定一个key标识这一行的数据
const getRowKey = (row: any) => {
	return row.T_number
}
const stockInexcelFun = async ()=>{
	if (multipleSelection.value.length === 0) {
		ElMessage.warning('请选择退库单!!!')
		return
	}
	let T_number_list = ''
	for (let item of multipleSelection.value) {
		T_number_list += item.T_number + '|'
	}

	const result:any = await stockInExcelBatch({T_number_list:T_number_list})
	if (result.Code === 200) {
		window.open(result.Data)
	}
	nextTick(() => {
		multipleSelection.value = []
		TableRef.value?.clearSelection()
	})
}
const handleSelectionChange = (val: any[]) => {
	multipleSelection.value = val
	console.log(multipleSelection.value)
}
</script>

<template>
  <div class="InStorage">
    <TableBase ref="TableRef" :columns="columns" :requestApi="Storehouse_StockIn_Apply_Warehouse_List" :initParam="initParam"
			   :getRowKey="getRowKey"
			   :selection-change="handleSelectionChange"
	>
      <template #table-header>
        <div class="input-suffix">
          <el-row :gutter="20" style="margin-bottom: 0">
		    <el-col :xl="5" :lg="5" :md="5" style="display: flex">
			  <span class="inline-flex items-center">退库编号：</span>
			  <el-input
				  v-model="initParam.T_name"
				  class="w-50 m-2"
				  type="text"
				  placeholder="退库编号搜索"
				  clearable
				  @change="searchHandle"
			  />
		  </el-col>
            <el-col :xl="6" :lg="6" :md="6" style="display: flex">
              <span class="inline-flex items-center">退库日期：</span>
              <el-date-picker
                v-model="T_date"
                type="daterange"
                range-separator="~"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-col>
            <el-col :xl="4" :lg="4" :md="4" style="display: flex">
              <span class="inline-flex items-center">状态：</span>
              <el-select v-model="initParam.T_state" clearable placeholder="请选择状态">
                <el-option v-for="item in stateOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <el-button type="primary" @click="searchHandle">搜索</el-button>
            </el-col>
            <el-col :xl="5" :lg="5" :md="5" class="btn">
				<el-button type="primary" @click="openInStorageFormDrawer">退库</el-button>
				<el-button type="success" icon="Download" @click="stockInexcelFun">导出excel</el-button>
			</el-col>
          </el-row>
        </div>
      </template>
		<template #T_type="{ row }">
			<el-tag v-if="row.T_type === 1" type="success"> 退库 </el-tag>
			<el-tag v-else> 退库 </el-tag>
		</template>
		<template #T_state="{ row }">
			<el-tag v-if="row.T_state === 1" type="warning">待入库</el-tag>
			<el-tag v-else-if="row.T_state === 2" type="success">已入库</el-tag>
			<el-tag v-else>未知状态</el-tag>
		</template>
      <template #right="{ row }">
        <el-button link type="primary" size="small" :icon="View" @click="preview(row.T_number)">详情</el-button>
		    <el-button link type="success" size="small" :icon="Edit" @click="previewWarehouse(row)" :disabled="row.T_state === 2">入库</el-button>
        <el-button link type="primary" size="small" :icon="Edit" @click="previewEdit(row)" :disabled="row.T_state === 2">编辑</el-button>
        <el-button link type="danger" size="small" :icon="Delete" @click="deleteFun(row.T_number)" :disabled="row.T_state === 2">删除</el-button>

      </template>
    </TableBase>
    <InStorageForm ref="InStorageFormRef" :options="options" @onUpdateList="searchHandle" />
    <InStorageEdit ref="InStorageRef" :options="options" @onUpdateList="searchHandle" />
	<InStorageWarehouse ref="InStorageWarehouseRef" :options="options" @onUpdateList="searchHandle" />

  </div>
</template>

<style scoped lang="scss">
@import '@/styles/var.scss';

.InStorage {
  @include f-direction;

  .input-suffix {
    width: 100%;
    .inline-flex {
      white-space: nowrap;
    }
    .w-50 {
      width: 12.5rem;
    }
    .btn {
      display: flex;
      justify-content: end;
      .el-button {
        padding: 0 20px;
      }
    }
  }
}
</style>
