<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { GlobalStore } from '@/stores/index'
import { View, Van,Edit,Delete } from '@element-plus/icons-vue'
import Drawer from '@/components/Drawer/index.vue'
import type { FormInstance, FormRules } from 'element-plus'
import { validate_T_phone } from '@/views/account/users/components/relus'
import { ref, reactive, nextTick } from 'vue'
import TableBase from '@/components/TableBase/index.vue'
import type { ColumnProps } from '@/components/TableBase/interface/index'
import {
	Storehouse_StockOut_List,
	Storehouse_StockOut_Edit,
	Storehouse_StockOut_Del,
	stockOutExcelBatch
} from '@/api/storehouse/index'
import { depotHooks, delivery_type } from '@/hooks/useDepot'
import InStorageEdit from './modules/InStorageEdit.vue'
const router = useRouter()
const formLabelWidth = ref('120px')
const globalStore = GlobalStore()
const ruleFormRef = ref<FormInstance>()
const TableRef = ref<InstanceType<typeof TableBase> | null>(null)
const DrawerRef = ref<InstanceType<typeof Drawer> | 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_receive_name', label: '领取人' },
  { prop: 'T_depot_name', label: '出库仓库' },
  { prop: 'T_date', label: '出库日期' },
  { prop: 'T_project', label: '关联项目' },
  { prop: 'T_type', label: '出库类型', name: 'T_type' },
  { prop: 'T_contract_number', label: '合同编号' },
  { prop: 'operation', label: '操作', width: 250, fixed: 'right', align: 'left ' }
]

const form = reactive({
  T_number: '',
  T_remark: '',
  T_delivery_type: '',
  T_signer_unit: '',
  T_signer: '',
  T_signer_phone: '',
  T_signer_date: '',
  T_courier_number: ''
})

const rules = reactive<FormRules>({
  T_delivery_type: [{ required: true, message: '请选择送货方式', trigger: 'blur' }],
  T_signer_unit: [{ required: true, message: '请输入签收单位', trigger: 'blur' }],
  T_signer_phone: [{ validator: validate_T_phone, trigger: 'blur' }]
})

/**
 * 查看详情
 */
const preview = (number: string) => {
  router.push({ name: 'OutStockDetail', params: { number } })
}
const InStorageRef = ref()
/**
 * 编辑
 */
 const previewEdit = (row: any) => {
  InStorageRef.value?.openDrawer()
  InStorageRef.value?.getStorehouseContractGet(row.T_number)
  for (let key in InStorageRef.value?.form) {  
    if (row.hasOwnProperty(key)) InStorageRef.value.form[key] = row[key]; 
  }

}
// 搜索
const T_date = ref<string[]>([])
const initParam = reactive({
  User_tokey: globalStore.GET_User_tokey,
  T_end_date: '',
  T_start_date: '',
  T_depot_id: '',
  T_name: ''
})
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 deliveryEdit = (number: string) => {
  form.T_number = number
  DrawerRef.value?.openDrawer()
}
const callbackDrawer = (done: () => void) => done()
const closeDrawer = () => {
  resetForm(ruleFormRef.value)
  DrawerRef.value?.closeDrawer()
}
const addOutStock = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async valid => {
    if (valid) {
      const res: any = await Storehouse_StockOut_Edit({ User_tokey: globalStore.GET_User_tokey, ...form })
      if (res.Code === 200) {
        ElMessage.success('发货成功！')
        nextTick(() => {
          closeDrawer()
        })
      }
    }
  })
}
/**
 * 重置表单
 */
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

/**
 * 删除
 */
 const deleteFun = (row:any)=>{
    ElMessageBox.confirm(
    '删除操作，是否立即删除?',
    '删除',
    {
      confirmButtonText: '立即删除',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
    }
  ).then(async () => {
    const result:any = await Storehouse_StockOut_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 stockOutExcelFun = 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 stockOutExcelBatch({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="out-stock">
    <TableBase ref="TableRef" :columns="columns" :requestApi="Storehouse_StockOut_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="7" :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="5" :lg="6" :md="5" style="display: flex">
              <span class="inline-flex items-center">仓库：</span>
              <el-select v-model="initParam.T_depot_id" clearable placeholder="请选择仓库~">
                <el-option v-for="item in options" :key="item.Id" :label="item.T_name" :value="item.Id" />
              </el-select>
              <el-button type="primary" @click="searchHandle">搜索</el-button>
            </el-col>
            <el-col :xl="8" :lg="6" :md="8" class="btn"
              ><el-button type="primary" @click="router.push('/receiveOutStock')">领料出库</el-button>
              <el-button type="primary" @click="router.push('/saleOutStock')">销售出库</el-button>
              <el-button type="success" icon="Download" @click="stockOutExcelFun">导出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 #right="{ row }">
        <el-button link type="success" size="small" :icon="View" @click="preview(row.T_number)">详情</el-button>
        <el-button link type="success" size="small" :icon="Edit" @click="previewEdit(row)">编辑</el-button>
        <el-button link type="danger" size="small" :icon="Delete" @click="deleteFun(row.T_number)">删除</el-button>
        <el-button
          v-if="row.T_type !== 1"
          link
          type="primary"
          size="small"
          :icon="Van"
          @click="deliveryEdit(row.T_number)"
          >发货管理</el-button
        >
      </template>
    </TableBase>
    <Drawer ref="DrawerRef" :handleClose="callbackDrawer">
      <template #header="{ params }">
        <h4 :id="params.titleId" :class="params.titleClass">发货管理</h4>
      </template>
      <el-form ref="ruleFormRef" :model="form" :rules="rules">
        <el-form-item label="送货方式：" :label-width="formLabelWidth" prop="T_delivery_type">
          <el-select v-model="form.T_delivery_type" clearable placeholder="请选择送货方式~">
            <el-option v-for="item in delivery_type" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="签收单位：" :label-width="formLabelWidth" prop="T_signer_unit">
          <el-input v-model="form.T_signer_unit" type="text" placeholder="请输入签收单位" />
        </el-form-item>
        <el-form-item label="签收人：" :label-width="formLabelWidth" prop="T_signer">
          <el-input v-model="form.T_signer" type="text" placeholder="请输入签收人" />
        </el-form-item>
        <el-form-item label="签收人电话：" :label-width="formLabelWidth" prop="T_signer_phone">
          <el-input v-model="form.T_signer_phone" type="text" placeholder="请输入签收人电话" />
        </el-form-item>
        <el-form-item label="签收日期：" :label-width="formLabelWidth" prop="T_signer_date">
          <el-date-picker
            class="my-date-picker"
            v-model="form.T_signer_date"
            type="date"
            style="width: 100%"
            placeholder="选择签收日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="物流单号：" :label-width="formLabelWidth" prop="T_courier_number">
          <el-input v-model="form.T_courier_number" type="text" placeholder="请输入物流单号" />
        </el-form-item>
        <el-form-item label="备注：" :label-width="formLabelWidth" prop="T_remark">
          <el-input
            v-model="form.T_remark"
            :autosize="{ minRows: 4, maxRows: 6 }"
            type="textarea"
            placeholder="请输入备注信息"
          />
        </el-form-item>
        <div class="btn">
          <el-button @click="closeDrawer">取消</el-button>
          <el-button type="primary" @click="addOutStock(ruleFormRef)">提交</el-button>
        </div>
      </el-form>
    </Drawer>
    <InStorageEdit ref="InStorageRef" :options="options" @onUpdateList="searchHandle" />
  </div>
</template>

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

.out-stock {
  @include f-direction;

  :deep(.el-drawer__header) {
    margin-bottom: 0;
  }
  .input-suffix {
    width: 100%;
    .inline-flex {
      white-space: nowrap;
    }
  }
  .btn {
    display: flex;
    justify-content: center;
    .el-button {
      padding: 0 20px;
    }
  }
}
</style>
