<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef"  v-show="showSearch" label-width="80px">
      <el-row >
        <el-col :span="4">
          <el-form-item label="目的地" prop="destName">
            <el-input
              v-model="queryParams.destName"
              placeholder="请输入目的地"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="配送日期" prop="deliveryDate">
            <el-date-picker clearable
              v-model="queryParams.deliveryDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择配送日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="配送车牌" prop="vehiclePlate">
            <el-input
              v-model="queryParams.vehiclePlate"
              placeholder="请输入配送车牌"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="接收单位" prop="receiverOrgName">
            <el-input
              v-model="queryParams.receiverOrgName"
              placeholder="请输入接收单位"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="配送状态" >
            <el-select v-model="queryParams.orderStatus" placeholder="请选择配送状态" clearable style="width: 100%;" >
                <el-option  label="待配送" value="1" />
                <el-option  label="配送中" value="2" />
                <el-option  label="已完成" value="3" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      
    </el-form>

    <el-row :gutter="10" class="mb8">

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['document:order:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAddBill"
          
        >新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="配送单号" align="center" prop="orderNo"  width="200"/>
      <el-table-column label="出库单据号" align="center" prop="billNoCk"  width="200">
        <template #default="scope">
					<span v-if="scope.row.billNoCk">{{ scope.row.billNoCk }}</span>
					<el-tag type="danger" v-else>手动创建</el-tag>
				</template>
        <!-- <template #default="scope">
          <span>{{ scope.row.billNoCk || '手动创建' }}</span>
        </template> -->
      </el-table-column>
      <el-table-column label="起始地点名称" align="center" prop="originName" width="120"/>
      <el-table-column label="目的地点名称" align="center" prop="destName" width="150"/>
      <el-table-column label="配送日期" align="center" prop="deliveryDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.deliveryDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="配送车牌" align="center" prop="plateNo" />
      <el-table-column label="发货人姓名" align="center" prop="shipperName" />
      <el-table-column label="接收人姓名" align="center" prop="receiverName" />
      <el-table-column label="接收单位" align="center" prop="receiverOrgName" width="150" />
			<el-table-column label="明细数量" align="center" prop="itemCount">
				<template #default="scope">
					<span>{{ scope.row.items.length }}</span>
				</template>
			</el-table-column>
      <el-table-column label="状态" align="center" prop="orderStatus" >
        <template #default="scope">
          <span>{{ statusFun(scope.row.orderStatus) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleDetail(scope.row)" >明细</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改配送单据主对话框 -->
    <el-dialog title="物料明细" v-model="open"   append-to-body width="80%">
      <el-table v-loading="detailLoading"  :data="wlList" show-overflow-tooltip>
			<el-table-column label="项目号" align="center" prop="xmNo" width="150"/>
			<el-table-column label="项目描述" align="center" prop="xmMs" width="250"/>
			<el-table-column label="物料号" align="center" prop="wlNo" width="100"/>
			<el-table-column label="物料描述" align="center" prop="wlMs" width="250"/>
			<el-table-column label="供应商名称" align="center" prop="gysMc" width="200"/>
			<!-- <el-table-column label="合同单价" align="center" prop="htDj" /> -->
			<el-table-column label="订单编号" align="center" prop="sapNo" width="150"/>
			<el-table-column label="计量单位" align="center" prop="dw" />
			<el-table-column label="实际入库数量" align="center" prop="realQty" width="120"/>
			<!-- <el-table-column label="库位码" align="center" prop="pcode" width="120"/> -->
			<!-- <el-table-column label="托盘码" align="center" prop="trayCode" /> -->
			<!-- <el-table-column label="身份码" align="center" prop="entityId" width="200"/> -->
			<!-- <el-table-column label="物资类型" align="center" prop="wlTypeName" /> -->
			<!-- <el-table-column label="所属仓库" align="center" prop="cangkuName" width="150"/> -->


			<!-- <el-table-column label="库龄" align="center" prop="stockAge" /> -->
			<!-- <el-table-column label="理货员" align="center" prop="lihuoYName" /> -->

			<el-table-column label="备注" align="center" prop="remark" width="200"/>


		  </el-table>
    </el-dialog>
    <el-dialog title="添加配送单" v-model="openBill"  append-to-body width="80%" @close="cancel" :close-on-click-modal="false">
      <div class="container">
				<el-form :model="delieryData" ref="form" :rules="rules"  label-width="100">
					<el-divider content-position="left">配送信息</el-divider>
					<el-row>
						<el-col :span="8">
							<el-form-item label="起点" prop="originName">
								<el-input
								v-model="delieryData.originName"
								placeholder="请输入起点"
								clearable
								
								/>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="终点" prop="destName">
								<el-input
								v-model="delieryData.destName"
								placeholder="请输入终点"
								clearable
								/>
							</el-form-item>
						</el-col>
            <el-col :span="8">
							<el-form-item label="配送人" prop="shipperName">
								<el-select v-model="delieryData.shipperName" placeholder="请选择配送人" clearable >
									<el-option v-for="dict in personList" :key="dict.userId" :label="dict.userName" :value="dict.userName" />
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						
						<el-col :span="8">
							<el-form-item label="配送人电话" prop="shipperPhone">
								<el-input
								v-model="delieryData.shipperPhone"
                type="tel"
								placeholder="请输入配送人电话"
								clearable
								/>
							</el-form-item>
						</el-col>
            <el-col :span="8">
							<el-form-item label="收货人" prop="receiverName">
								<el-input
								v-model="delieryData.receiverName"
								placeholder="请输入收货人"
								clearable
								/>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="收货人电话" prop="receiverPhone">
								<el-input
								v-model="delieryData.receiverPhone"
                type="tel"
								placeholder="请输入收货人电话"
								clearable
								/>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="8">
							<el-form-item label="接收单位" prop="receiverOrgName">
								<el-input
								v-model="delieryData.receiverOrgName"
								placeholder="请输入接收单位"
								clearable
								/>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="配送日期" prop="deliveryDate">
				
								<el-date-picker
									v-model="delieryData.deliveryDate"
									type="date"
									format="YYYY-MM-DD"
									value-format="YYYY-MM-DD"
									style="width: 100%;"
								/>
							</el-form-item>
						</el-col>
					</el-row>
					<el-divider content-position="left">
            货物信息
            <el-button type="primary" size="small" @click="addLineFun" >添加</el-button>
          </el-divider>
          <!-- <el-row>
            <el-col :span="4" :offset="22">
              <el-button type="primary" size="small" @click="addLineFun" >添加</el-button>
            </el-col>
          </el-row> -->
					<el-table :data="goodsList" max-height="300"  show-overflow-tooltip :row-class-name="tableRowClassName" @selection-change="handleSelectionChange">
          <!-- <el-table-column type="selection" width="30" align="center" /> -->
          <el-table-column  width="40" align="center" >
            <template #default="scope" >
              <el-icon :size="22" @click="delLineFun(scope.$index)"><RemoveFilled /></el-icon>
            </template>
          </el-table-column>
          <el-table-column label="物料号" align="center" prop="wlNo" width="150">
            <template #default="scope" >
              <el-input  v-model="scope.row.wlNo" placeholder="请输入物料号" ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="物料描述" align="center" prop="wlMs" width="200">
            <template #default="scope" >
              <el-input  v-model="scope.row.wlMs" placeholder="请输入物料描述"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="单价" align="center" prop="htDj" width="80">
            <template #default="scope" >
              <el-input  v-model="scope.row.htDj" ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="单位" align="center" prop="dw" width="80">
            <template #default="scope" >
              <el-input  v-model="scope.row.dw" ></el-input>
            </template>
          </el-table-column>

      
          <el-table-column label="配送数量" align="center"  width="100">
            <template #default="scope">
              <el-input v-model="scope.row.realQty" placeholder="配送数量" @change="changeQty(scope.row.realQty,scope.$index)"></el-input>
                
            </template>
          </el-table-column>

          <el-table-column label="采购订单号" align="center" prop="sapNo" width="130" >
            <template #default="scope" >
              <el-input  v-model="scope.row.sapNo" placeholder="请输入订单号"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="项目号" align="center" prop="xmNo" width="150">
            <template #default="scope" >
              <el-input  v-model="scope.row.xmNo" placeholder="项目定义号"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="项目名称" align="center" prop="xmMs" width="300">
            <template #default="scope" >
              <el-input  v-model="scope.row.xmMs" placeholder="项目名称"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="供应商" align="center" prop="gysMc" width="200">
            <template #default="scope" >
              <el-input  v-model="scope.row.gysMc" placeholder="供应商"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center"  width="200">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注"></el-input>
            </template>
          </el-table-column>
      
          

        </el-table>
					<el-divider content-position="left">计算信息</el-divider>
          <el-row>
						<el-col :span="6">
							<el-form-item label="重量" prop="deliveryTon">
								<el-input
								v-model="delieryData.deliveryTon"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item label="体积" prop="goodsSize">
								<el-input
								v-model="delieryData.goodsSize"
								/>
							</el-form-item>
						</el-col>
            <el-col :span="6">
							<el-form-item label="公里数" prop="totalKm">
								<el-input
								v-model="delieryData.totalKm"
								placeholder="请输入公里数"
								clearable
								/>
							</el-form-item>
						</el-col>
            <el-col :span="4" :offset="2">
							<el-button type="primary" @click="calculateFun(null)">计算</el-button>
						</el-col>
					</el-row>
					<el-row>
						
						
					</el-row>
					<el-row>
						<el-col :span="6">
							<el-form-item label="推荐车型" v-for="(item, index) in delieryData.vehicleTypeNameList" :key="index">
								<el-select v-model="item.vehicleTypeId" placeholder="请选择推荐车型"  @change="changeCarType($event, index)">
									<el-option v-for="dict in carTypeList" :key="dict.id" :label="dict.name" :value="dict.id" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="6">
							<el-form-item label="建议费用" prop="suggestFee">
								<el-input
								v-model="delieryData.suggestFee"
								placeholder=""
								clearable
								disabled
								/>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</div>
			<template #footer>
				<div class="dialog-footer">
				<el-button type="primary"  @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
				</div>
			</template>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import { listOrder,detailOrder,calcTotalWv,calculate,addDelivery } from "@/api/waitDelivery/waitDelivery"
import { listType } from "@/api/document/type"
import {listUser} from "@/api/system/user";    //理货员
import { ref } from "vue";
const { proxy } = getCurrentInstance()

const orderList = ref([])
const open = ref(false)
const openBill = ref(false)
const loading = ref(true)
const detailLoading = ref(false)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const wlList = ref([])
const goodsList = ref([])
const carTypeList = ref([])	//推荐车型下拉数据
const personList = ref([]);   //理货员下拉数据
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    // orderStatusList:[1,2],
    destName:null,    // 目的地名称
    deliveryDate:null,  // 配送日期
    plateNo:null,   // 车牌号
    receiverOrgName:null, // 接收单位
    orderStatus:null,
    // xmMs: null,
    // xmNo: null,
    // wlNo: null,
    // wlMs: null,
    // realQty: null,
    // dw: null,
    // sapNo: null,
    // gysMc: null,
    // originName: null,
    // originLng: null,
    // originLat: null,
    // destName: null,
    // destLng: null,
    // destLat: null,
    // deliveryDate: null,
    // vehiclePlate: null,
    // shipperName: null,
    // shipperPhone: null,
    // receiverName: null,
    // receiverPhone: null,
    // receiverOrgName: null,
    // deliveryTon: null,
    isDelete: null
  },
  rules: {
		originName: [{ required: true, message: "起点不能为空", trigger: "change" }],
		destName: [{ required: true, message: "终点不能为空", trigger: "change" }],
		shipperName: [{ required: true, message: "配送人不能为空", trigger: "change" }],
    shipperPhone:[{ pattern: /^1[3456789]\d{9}$/, message: '请输入有效的电话号码', trigger: 'blur' }],
		receiverName: [{ required: true, message: "收货人不能为空", trigger: "change" }],
		receiverPhone: [
      { required: true, message: "收货人电话不能为空", trigger: "change" },
      { pattern: /^1[3456789]\d{9}$/, message: '请输入有效的电话号码', trigger: 'blur' }
    ],
		deliveryTon: [{ required: true, message: "重量不能为空", trigger: "change" }],
		goodsSize: [{ required: true, message: "体积不能为空", trigger: "change" }],
		totalKm: [{ required: true, message: "公里数不能为空", trigger: "change" }],
		vehicleTypeId: [{ required: true, message: "推荐车型不能为空", trigger: "change" }],
		suggestFee: [{ required: true, message: "建议费用不能为空", trigger: "change" }],
		deliveryDate:[{ required: true, message: "配送日期不能为空", trigger: "change" }]
	},
  //配送单提交的数据
	delieryData:{
		deliveryTon:null,	//重量
		goodsSize:null,	//体积
		items:[],
    vehicleTypeNameList:[{}]
	},   
})

const { queryParams,delieryData,rules } = toRefs(data)

/** 查询配送单据主列表 */
function getList() {
  loading.value = true
  listOrder(queryParams.value).then(response => {
    orderList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
//添加货物信息
function addLineFun(){

  const info = {
    dw:'',
    htDj:'',
    realQty:'',
    gysMc:'',
    wlNo:'',
    wlMs:'',
    sapNo:'',
    xmNo:'',
    xmMs:'',
    gysMc:'',
    remark:'',
    billNoCk:''
  }
  
  goodsList.value.push(info)
}
function delLineFun(index){
  // console.log(index)
  proxy.$modal.confirm('确定删除吗？').then(function() {
    
      goodsList.value.splice(index,1)
      changeQty()
      return true
    // console.log(goodsList.value)
}).then(() => {
  
}).catch(() => {});
  // if(checkPlanList.value.length==0){
  //   proxy.$modal.msgWarning("请勾选数据");
  //   return
  // }

}
function changeQty(){
  
  const data = goodsList.value.filter(item=>item.wlNo!='' && item.realQty!='').map(item=>({
    wlNo:item.wlNo,
    qty:item.realQty
  }))
  if(data.length>0){
    calcTotalWv({items:data}).then(response=>{
      let info = response.data
      delieryData.value.deliveryTon = info.totalWeightKg / 1000
      delieryData.value.goodsSize = info.totalVolumeM3
      // console.log(response)
      // delieryData.deliveryTon = response.data.deliveryTon
      // delieryData.goodsSize = response.data.goodsSize
    })
  }else{
    delieryData.value.deliveryTon = null
    delieryData.value.goodsSize = null

  }
  
}
//根据重量、体积、公里数计算车型、费用
function calculateFun(id) {
  if (
    !delieryData.value.deliveryTon ||
    !delieryData.value.goodsSize ||
    !delieryData.value.totalKm
  ) {
    proxy.$modal.msgWarning("请输入公里数、重量、体积");
    return;
  }
  let info = {
    weightTon: 0,
    volumeM3: 0,
    distanceKm: 0,
  };
	let hasVehicle = delieryData.value.vehicleTypeNameList.every(item => item.vehicleTypeId)
  if (hasVehicle) {
		info.vehicleTypeId = delieryData.value.vehicleTypeNameList.map(item => item.vehicleTypeId).join(',')
  }
  info.weightTon = delieryData.value.deliveryTon;
  info.volumeM3 = delieryData.value.goodsSize;
  info.distanceKm = delieryData.value.totalKm;
  calculate(info).then((response) => {
    // 检查后端是否返回了错误信息
    if (response.data.warningMessage) {
      proxy.$modal.msgError(response.data.warningMessage);
      return;
    }
    if (response.data.bestPlan.length > 0 && !id) {
      delieryData.value.vehicleTypeNameList = response.data.bestPlan;
    }
    carTypeList.value = response.data.candidates;
    delieryData.value.suggestFee = response.data.suggestFee;
    delieryData.value.vehicleTypeName = response.data.vehicleTypeName;
    console.log(delieryData.value)
  });
}
//切换车型
function changeCarType(id, index){
	if(!delieryData.value.totalKm || !delieryData.value.deliveryTon || !delieryData.value.goodsSize){
		proxy.$modal.msgWarning("请输入公里数、重量、体积");
		return
	}
	calculateFun(id)
}

// 取消按钮
function cancel() {
  delieryData.value.originName = null;
  delieryData.value.destName = null;
  delieryData.value.shipperName = null;
  delieryData.value.shipperPhone = null;
  delieryData.value.receiverName = null;
  delieryData.value.receiverPhone = null;
  delieryData.value.receiverOrgName = null;
  delieryData.value.deliveryDate = null;
  delieryData.value.totalKm = null;
  delieryData.value.vehicleTypeNameList = [{}];
  delieryData.value.suggestFee = null;
  goodsList.value = []
	proxy.$refs["form"].resetFields()
  openBill.value = false
}

// 表单重置
function reset() {
  proxy.resetForm("orderRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  queryParams.value.orderStatus = null
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加配送单据主"
}


function handleDetail(row) {
  open.value = true
  detailLoading.value = true
  detailOrder({orderNo:row.orderNo}).then(response=>{
    detailLoading.value = false
    wlList.value = response.data
    
  })
}

function statusFun(status){
  if(status==0 || status==1){
    return "待配送"
  }else if(status==2){
    return "配送中"
  }else if(status==3){
    return "已完成"
  }
} 

/** 提交按钮 */
function submitForm() {
  let hasVehicle = delieryData.value.vehicleTypeNameList.every(item => item.vehicleTypeId)
  if (!hasVehicle) {
    proxy.$modal.msgWarning('请选择配送车型')
    return
  }
  proxy.$refs["form"].validate(valid => {
    // console.log(delieryData.value)
    // return
    
      if (valid) {
        let obj = JSON.parse(JSON.stringify(delieryData.value))
        obj.vehicleTypeName = obj.vehicleTypeNameList.map(item => item.vehicleTypeName).join(',')
        obj.vehicleTypeId = obj.vehicleTypeNameList.map(item => item.vehicleTypeId).join(',')
        if(goodsList.value.length==0){
          proxy.$modal.msgWarning("请添加货物信息");
          return
        }
       obj.items = goodsList.value
        // console.log(delieryData.value)
        addDelivery(obj).then(response => {
            proxy.$modal.msgSuccess("操作成功")
            openBill.value = false
            getList()
        })
      }
  })
}


/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除配送单据主编号为"' + _ids + '"的数据项？').then(function() {
    return delOrder(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('document/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}
function handleAddBill(){
  
	
  openBill.value = true
  //车型下拉数据
	// listType({pageNum:1,pageSize:1000}).then(response => {
  //       carTypeList.value = response.rows
        
	// })
  //理货员下拉数据
	listUser().then(response=>{
		personList.value = response.rows
	})
}

getList()
</script>
<style scoped>
  /* .container{
    
  } */
</style>
