<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { GlobalStore } from '@/stores/index'
import { View, Van } 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_ListProduct, Storehouse_StockOut_Edit,StockOutExcel } from '@/api/storehouse/index'
import { depotHooks, delivery_type } from '@/hooks/useDepot'

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 columns: ColumnProps[] = [
  { type: 'index', label: '序号', width: 80 },
  { prop: 'T_number', label: '出库单号' },
  { prop: 'T_receive_name', label: '领取人' },
  { prop: 'T_date', label: '出库日期' },
  { prop: 'T_depot_name', label: '出库仓库' },
  { prop: 'T_project', label: '关联项目' },
  { prop: 'T_product_name', label: '产品名称', name: 'T_type' },
  { prop: 'T_product_model', label: '产品型号' },
  { prop: 'T_num', label: '数量' },

  { prop: 'T_product_relation_sn', label: '是否关联SN', name: 'T_product_relation_sn' },
    { prop: 'T_remark', label: '备注' },
  { prop: 'operation', label: '操作', width: 170, 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 dialogTableVisible = ref(false)
const gridData:any = ref([])
const preview = (list:any) => {
    let arr = [...list] || []
    gridData.value = arr.map((item:any)=>({sn:item}))
    dialogTableVisible.value = true
}

// 搜索
const T_date = ref<string[]>([])
const initParam = reactive({
  User_tokey: globalStore.GET_User_tokey,
  T_end_date: '',
  T_start_date: '',
  T_depot_id: '',
  T_product_name: '',
    T_product_model: '',
  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 { options } = depotHooks()

/**
 * Excel
 */
 const onclickExcel = async ()=>{
    const result:any = await StockOutExcel(initParam)
    console.log('导出',result)

    if (result.Code === 200)window.open(result.Data)
}
</script>

<template>
  <div class="out-stock">
    <TableBase ref="TableRef" :columns="columns" :requestApi="Storehouse_StockOut_ListProduct" :initParam="initParam">
      <template #table-header>
        <div class="input-suffix">
          <el-row :gutter="20" style="margin-bottom: 0">
            <el-col :xl="4" :lg="4" :md="4" style="display: flex">
                <span class="inline-flex items-center">关键字：</span>
                <el-input v-model="initParam.T_name" placeholder="出库单号，关联项目搜索" />
            </el-col> 
            <el-col :xl="4" :lg="4" :md="4" 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-input v-model="initParam.T_product_name" placeholder="产品名称" />
            </el-col>
            <el-col :xl="4" :lg="4" :md="4" style="display: flex">
                <span class="inline-flex items-center">产品型号：</span>
                <el-input v-model="initParam.T_product_model" placeholder="产品型号" />
            </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_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="4" :lg="4" :md="4" style="display: flex">
                <el-button type="primary" icon="Download" @click="onclickExcel">导出</el-button>
            </el-col>
          </el-row>
        </div>
      </template>
      <template #T_product_relation_sn="{ row }">
            <el-text class="mx-1" :type="row.T_product_relation_sn==1?'primary':'danger'">
                {{row.T_product_relation_sn==1?'是':'否'}}
            </el-text>
        </template>
      <template #right="{ row }">
        <el-button type="primary" size="small" v-show="row.T_product_relation_sn == 1" :icon="View"
                    @click="preview(row.T_device_list)">查看SN</el-button>
      </template>
    </TableBase>
    <el-dialog v-model="dialogTableVisible" title="查看SN" draggable>
        <el-table :data="gridData" border max-height="500">
            <el-table-column type="index" label="序号" width="100" />
            <el-table-column property="sn" label="SN" />
        </el-table>
    </el-dialog>
  </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>
