<template>
<el-card class="hl-card">
  <template #header>
    <span>订单发货</span>
  </template>
    <ContentWrap class="borderxx">
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="110px"
    >
      <el-form-item label="发货单号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入发货单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="项目编号" prop="saleOrderCode">
        <el-input
          v-model="queryParams.saleOrderCode"
          placeholder="请输入项目编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="发货日期" prop="deliverDate">
        <el-date-picker
          v-model="queryParams.deliverDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="发货单状态" prop="deliverStatus">
        <el-select
          v-model="queryParams.deliverStatus"
          placeholder="请选择发货单状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.HELI_DELIVER_ORDER_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" type="primary"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openDetail('create')"
          v-hasPermi="['heli:deliver-order:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
<!--        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['heli:deliver-order:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>-->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" class="hl-table">
      <el-table-column type="index" width="100" fixed label="序号" align="center" />
      <el-table-column fixed label="发货单号" align="center" prop="code" width="180" >
        <template #default="scope">
            <el-button text type="primary" @click="openDetail('detail',scope.row.id)">
              {{scope.row.code}}
            </el-button>
          </template>
      </el-table-column>
      <el-table-column fixed label="项目编号" align="center" prop="saleOrderCode" width="220" />
      <el-table-column
        fixed
        label="发货日期"
        align="center"
        prop="deliverDate"
        :formatter="dateFormatter2"
        width="180"
      />
      <el-table-column label="客户名称" align="center" prop="customerName" width="220" />
      <el-table-column label="合同号" align="center" prop="contractNo" width="180" />
      <el-table-column label="项目名称" align="center" prop="projectName" width="180" />
      <el-table-column label="性质" align="center" prop="property" width="100" >
        <template #default="scope">
          {{getOrderProperty(scope.row.property)}}
        </template>
      </el-table-column>
      <el-table-column label="发货人姓名" align="center" prop="deliverPersonName" width="120" />
      <el-table-column label="发货人电话" align="center" prop="deliverPersonMobile" width="160" />
      <el-table-column label="收货人姓名" align="center" prop="receivePersonName" width="120" />
      <el-table-column label="收货人电话" align="center" prop="receivePersonMobile" width="160" />
      <el-table-column label="收货详细地址" align="center" prop="receiveAddress" width="180" />
      <el-table-column label="司机姓名" align="center" prop="transportDriverName" width="120" />
      <el-table-column label="司机电话" align="center" prop="transportDriverMobile" width="160" />
      <el-table-column label="发货备注" align="center" prop="remark" width="180" />
      <el-table-column fixed="right" label="发货单状态" align="center" prop="deliverStatus" width="120">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.HELI_DELIVER_ORDER_STATUS" :value="scope.row.deliverStatus" />
        </template>
      </el-table-column>
      <el-table-column fixed="right"  align="right" width="220">
         <template #header> <span style="margin-right: 30%">操作</span>
         </template>
        <template #default="scope">
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id,scope.row.deliverStatus)"
          >
            删除
          </el-button>
          <el-button
            v-if="scope.row.deliverStatus == 1"
            link
            type="primary"
            @click="openDetail('update', scope.row.id)"
          >
            编辑
          </el-button>
<!--		  <el-button-->
<!--		   v-if="scope.row.deliverStatus != 1&&scope.row.deliverStatus != 4"-->
<!--		    link-->
<!--		    type="primary"-->
<!--		    @click="actionmoney( scope.row.id)"-->
<!--		  >-->
<!--		    质保金-->
<!--		  </el-button>-->
          <el-button
            link
            type="primary"
            @click="openDetail('detail', scope.row.id)"
          >
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

</el-card>
</template>

<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions, getDictLabel} from '@/utils/dict'
import {dateFormatter2} from '@/utils/formatTime'
import download from '@/utils/download'
import * as DeliverOrderApi from '@/api/heli/deliverorder'
import routeParamsCache from '@/utils/routeParamsCache'
defineOptions({ name: 'DeliverOrder' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const router = useRouter()

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  saleOrderCode: undefined,
  customerName: undefined,
  deliverDate: [],
  deliverStatus: undefined,
  deliverPerson: undefined,
  deliverPersonMobile: undefined,
  deliverMode: undefined,
  receivePersonMobile: undefined,
  transportDriverName: undefined,
  transportDriverMobile: undefined,
  transportBusNumber: undefined,
  transportWeight: undefined,
  transportSize: undefined,
  remark: undefined,
  status: undefined,
  createTime: [],
  receivePersonName: undefined,
  receiveAddress: undefined,
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {

	    const id = history.state.idid;
	  	  if(id){
	  	  		 queryParams.code=id
	  	  }
    const data = await DeliverOrderApi.getDeliverOrderPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const openDetail = (type: string, id?: number) => {
  router.push({
    name: 'DeliverOrderDetail',
    query: {
      active: type,
      id: id,
      operateId: Math.random()
    }
  })
}
// 收取质保金
// const actionmoney = ( id?: number) => {
// debugger



// }
const actionmoney =  (id?: number) => {
   ElMessageBox.confirm('是否确认已收取质保金?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  .then(async () => {

     selectshowmoneyok(id)
      ElMessage({
        type: 'success',
        message: '确认成功!'
      });
  })
  .catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消确认'
    });
  });
};

const selectshowmoneyok = async (id: number) => {
  try {
    await DeliverOrderApi.showzbmoneyok(id);
    await getList()
  }  catch (error) { console.error(error); }
}

/** 删除按钮操作 */
const handleDelete = async (id: number,deliverStatus: number) => {
  try {
    if (deliverStatus==2){
      await message.confirm('该发货单已发货,确认要删除?')
    }else {
      // 删除的二次确认
      await message.delConfirm()
    }

    // 发起删除
    await DeliverOrderApi.deleteDeliverOrder(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await DeliverOrderApi.exportDeliverOrder(queryParams)
    download.excel(data, '发货订单.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const getOrderProperty = (property) => {
  if(!property) return "";
  let properties = property.split(",");
  let result = "";
  for (let i = 0; i < properties.length; i++) {
    result += getDictLabel(DICT_TYPE.HELI_PROJECT_PROPERTY, properties[i]) + ","
  }
  return result.substring(0, result.length-1)
}

/** 初始化 **/
const route = useRoute()
onMounted(async () => {
  let params = routeParamsCache.get(route.path);
  if (params ) {
    Object.assign(queryParams, params);
  }
  getList()
})
onBeforeUnmount(() => {
  const plainParams = JSON.parse(JSON.stringify(queryParams));
  routeParamsCache.set(route.path, plainParams);
});

window.addEventListener('beforeunload', () => {
  const plainParams = JSON.parse(JSON.stringify(queryParams));
  routeParamsCache.set(route.path, plainParams);
});
</script>
