<template>
  <el-drawer title="新建到货单" size="900px">
    <el-row class="page-search" justify="space-between" align="middle">
      <el-form ref="queryFormRef" :model="queryParams.params" label-width="60px" label-position="left">
        <el-row :gutter="21">
          <el-col :span="7">
            <el-form-item label="组织" prop="erpFactory">
              <el-select v-model="queryParams.params.erpFactory" placeholder="下拉选择" style="width: 160px">
                <el-option v-for="item in state.orgList" :key="item.ERPFACTORY" :label="item.DESCRIPTION"
                           :value="item.ERPFACTORY" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="采购单号" prop="receiveRequestName">
              <el-Input v-model="queryParams.params.receiveRequestName" placeholder="单号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="订单状态" prop="receiveRequestState">
              <el-select v-model="queryParams.params.receiveRequestState" placeholder="下拉选择" style="width: 160px">
                <el-option v-for="item in state.orderStatus" :key="item.label" :label="item.label"
                           :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="料号" prop="materialSpecName">
              <el-Input v-model="queryParams.params.materialSpecName" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="品名" prop="descCn">
              <el-Input v-model="queryParams.params.descCn" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="开始时间" prop="fromDate">
              <el-date-picker v-model="queryParams.params.fromDate" value-format="YYYYMMDD" type="date"
                              placeholder="选择开始时间" />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="结束时间" prop="toDate">
              <el-date-picker v-model="queryParams.params.toDate" value-format="YYYYMMDD" type="date"
                              placeholder="选择结束时间" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="page-search-btns">
        <el-button type="primary" @click="queryInfo">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
        <el-button type="primary" @click="handleCreate" v-loading="state.btnLoading">创建</el-button>
      </div>
    </el-row>

    <div class="vue-element-page-table">
      <div class="page-table-operate">
        <div class="page-table-title">
          <span>采购订单</span>
        </div>
      </div>
      <el-table border v-loading="loading" :data="state.dataList"
                highlight-current-row row-key="id" @selection-change="handleSelection">
        <el-table-column type="selection" width="55" />
        <template v-for="(col, index) in column" :key="index">
          <el-table-column v-if="!col.hide" :label="col.header" :width="col.width" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ scope.row[col.field] }}</span>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <div>
        <pagination v-if="total > 0" :total="total" v-model:pageNumTo="queryParams.pageNum"
                    v-model:pageSizeTo="queryParams.pageSize" @pagination="handleQuery" />
      </div>
    </div>

    <div class="vue-element-page-table">
      <div class="page-table-operate">
        <div class="page-table-title">
          <span>订单详情</span>
        </div>
      </div>
      <el-table border v-loading="receiveLoading" :data="state.receiveList"
                highlight-current-row row-key="id">
        <el-table-column prop="receiveRequestName" fixed="left" label="单号"/>
        <el-table-column prop="receiveRequestDetailName" fixed="left" label="详情号"/>
        <el-table-column prop="materialSpecName" fixed="left" label="料号"/>
        <el-table-column prop="requestQuantity" label="订单数量" width="180"/>
        <el-table-column prop="deliveryNum" label="到库数量" width="180">
          <template #default="scope">
            <el-Input v-model="scope.row.deliveryNum" placeholder="请输入到库数量" clearable />
          </template>
        </el-table-column>
      </el-table>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import { getCurrentInstance, onMounted, reactive, ref, toRefs } from 'vue'
import { ElForm, ElMessageBox, ElTable } from 'element-plus'
import { localStorage } from '@/utils/storage'
import { createDelivery, getReceiveList, getReceiveDetail } from '@/api/delivery'
import { getORG } from '@/api/auth'

const queryFormRef = ref(ElForm)
const { proxy }: any = getCurrentInstance()

const props = defineProps<{
  deliveryType: string;
}>();

// 变量
let state = reactive({
  dataList: [] as any, // 表格数据
  total: 0, // 总数
  selection: [] as any, // 多选
  btnLoading: false,
  loading: true,
  receiveLoading: false,
  receiveList: [] as any,
  column: [] as any,
  // 工厂
  orgList: [] as any,
  // 订单状态
  orderStatus: [{
    label: "未完成",
    value: "Created"
  },{
    label: "完成",
    value: "Completed"
  }],
  // 查询参数
  queryParams: {
    params: {
      // siteName
      siteName: localStorage.get('siteName') || 'SDK',
      // 组织
      erpFactory: '',
      // 单号名称
      receiveRequestName: '',
      // 订单状态
      receiveRequestState: '',
      // 料号
      materialSpecName: '',
      // 品名
      descCn: '',
      // 开始时间
      fromDate: '',
      // 结束时间
      toDate: '',
      // 类型
      deliveryType: ''
    },
    pageNum: 1,
    pageSize: 10
  }
})
const { queryParams, column, loading, total, receiveLoading } = toRefs(state)
onMounted(()=> {
  state.column = [
    { header: "组织", field: "erpFactory", hide: false },
    { header: "组织(CN)", field: "orgName", hide: false },
    { header: "订单编号", field: "receiveRequestName", hide: false },
    // { header: "料号", field: "materialSpecName", hide: false },
    // { header: "品名", field: "descCn", hide: false },
    { header: "出入库类型编码", field: "receiveRequestType", hide: false },
    { header: "订单状态", field: "receiveRequestState", hide: false },
    { header: "供应商编号", field: "supplierNo", hide: false },
    { header: "单据日期" , field: "orderDate", hide: false},
    { header: "供应商名称", field: "supplierName", hide: false },
    // { header: "创建日期", field: "createTime", hide: false },
    { header: "最后操作名称", field: "lastEventName", hide: false },
    { header: "最后操作时间", field: "lastEventTime", hide: false },
    { header: "最后操作人", field: "lastEventUser", hide: false },
    { header: "最后操作注释", field: "lastEventComment", hide: false },
  ]
  // 组织
  getORG({ orgNo: null }).then((res: any) => {
    state.orgList = res.resultObj
  })
  handleQuery()
})
// 多选
const handleSelection = (val: any) => {
  if (val.length === 0) {
    state.receiveList = []
    return
  }
  state.selection = val
  state.receiveLoading = true
  let nameList: any = []
  val.forEach((item: any) => nameList.push(item.receiveRequestName))
  // 加载详情
  getReceiveDetail({nameList: nameList}).then((res: any) => {
    state.receiveList = res.resultObj
    state.receiveLoading = false
  })
}
// 查询
function queryInfo() {
  state.queryParams.pageNum = 1
  handleQuery()
}
// 查询
async function handleQuery() {
  state.loading = true
  state.receiveList = []
  state.queryParams.params.deliveryType = props.deliveryType
  await getReceiveList(state.queryParams).then((res: any) => {
    state.dataList = res.resultObj.list
    state.total = res.resultObj.total
    state.loading = false
  })
}
const emits = defineEmits(['refresh'])
// 创建入库单
function handleCreate() {
  if (state.selection.length == 0) {
    ElMessageBox.alert('请选择条目', { confirmButtonText: 'OK' })
    return
  }
  let name = "DK" + Date.now()
  createDelivery({
    deliveryName: name,
    deliveryType: props.deliveryType,
    siteName: 'SDK',
    receiveList: state.receiveList
  }).then((res: any) => {
    if (res.errorCode == 200) {
      proxy.$ElMessage.success(res.message)
      emits('refresh', name)
    } else {
      proxy.$ElMessage.error(res.message)
    }
  })
}
function resetQuery() {
  queryFormRef.value.resetFields();
  state.queryParams.params.erpFactory = '';
  state.queryParams.params.receiveRequestName = '';
  state.queryParams.params.receiveRequestState = '';
  state.queryParams.params.materialSpecName = '';
  state.queryParams.params.descCn = '';
  state.queryParams.params.fromDate = '';
  state.queryParams.params.toDate = '';
  queryInfo();
}
</script>