<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="货物名称" prop="goodsName">
                <el-input v-model="queryParams.goodsName" placeholder="请输入货物名称" clearable
                    @keyup.enter="handleQuery" />
            </el-form-item>
			<el-form-item label="货物类型" prop="goodsClass">
			    <el-select v-model="queryParams.goodsClass" placeholder="请选择" @change="handleQuery">
			    	<el-option
			    	  v-for="item in sys_goods_type"
			    	  :key="item.value"
			    	  :label="item.label"
			    	  :value="item.value">
			    	</el-option>
			    </el-select>
			</el-form-item>
            <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-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd"
                    v-hasPermi="['waybill:waybill:add']">新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
                    v-hasPermi="['waybill:waybill:remove']">删除
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport"
                    v-hasPermi="['waybill:waybill:export']">导出
                </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="waybillList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column type="expand" width="30">
                <template #default="scope">
                    <div class="padding">
                        <el-descriptions :column="3">
                            <el-descriptions-item label="编号">
                                {{scope.row.waybillId}}
                            </el-descriptions-item>
                            <el-descriptions-item label="货物名称">
                                {{scope.row.goodsName}}
                            </el-descriptions-item>
                            <el-descriptions-item label="货物类型">
								<dict-tag :options="sys_goods_type" :value="scope.row.goodsClass" style="display: inline-block;"/>
                            </el-descriptions-item>
                            <el-descriptions-item label="货物重量">
                                {{scope.row.goodsWeight}}
								<dict-tag :options="sys_goods_unit" :value="scope.row.goodsWeightUnit" style="display: inline-block;"/>
                            </el-descriptions-item>
                            <el-descriptions-item label="单价">
                                ￥{{scope.row.unitPrice}}
                            </el-descriptions-item>
							<el-descriptions-item label="总价">
							    ￥{{parseFloat(scope.row.unitPrice)*parseFloat(scope.row.goodsWeight)}}
							</el-descriptions-item>
                            <el-descriptions-item label="提货联系人">
                                {{scope.row.pickingContact}}
                            </el-descriptions-item>
						    <el-descriptions-item label="卸货联系人">
						        {{scope.row.unloadingContact}}
						    </el-descriptions-item>
							<el-descriptions-item label="客户名称">
							    <TextTag :options="corporateList" column="corporateId" label="corporateName" :value="scope.row.corporateId"
							        isText style="display: inline-block;"/>
							</el-descriptions-item>
						    <el-descriptions-item label="提货联系电话">
						        {{scope.row.pickingPhone}}
						    </el-descriptions-item>
						    <el-descriptions-item label="卸货联系电话">
						        {{scope.row.unloadingPhone}}
						    </el-descriptions-item>
							<el-descriptions-item label="备注">
								 {{scope.row.remarks}}
							</el-descriptions-item>
                            <el-descriptions-item label="提货时间">
                                {{ parseTime(scope.row.pickingDate, '{y}-{m}-{d}')}}
                            </el-descriptions-item>
                            <el-descriptions-item label="卸货时间">
                                {{parseTime(scope.row.unloadingDate, '{y}-{m}-{d}')}}
                            </el-descriptions-item>
							<el-descriptions-item label="分配船舶">
								粤广州货8966
							</el-descriptions-item>
                            <el-descriptions-item label="提货地址">
                                {{scope.row.pickingAddress}}
                            </el-descriptions-item>
						    <el-descriptions-item label="卸货地址">
						        {{scope.row.unloadingAddress}}
						    </el-descriptions-item>
							<el-descriptions-item label="">
							</el-descriptions-item>
                        </el-descriptions>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="货物名称" align="center" prop="goodsName" />
            <el-table-column label="重量" align="center" prop="goodsWeight" />
            <el-table-column label="单价" align="center" prop="unitPrice" />
            <el-table-column label="提货时间" align="center" prop="pickingDate" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.pickingDate, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
			<el-table-column label="提货地址" align="center" prop="pickingAddress" />
            <el-table-column label="卸货时间" align="center" prop="unloadingDate" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.unloadingDate, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
			<el-table-column label="卸货地址" align="center" prop="unloadingAddress" />
			<el-table-column label="运单状态" align="center" prop="waybillState">
				<template #default="scope">
				    <dict-tag :options="sys_waybill_status" :value="scope.row.waybillState" />
				</template>
			</el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200" fixed="right">
                <template #default="scope">
                    <el-button link type="success" icon="Edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['waybill:waybill:edit']" v-if="scope.row.waybillState == 10">修改
                    </el-button>
                    <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['waybill:waybill:remove']">删除
                    </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="title" v-model="open" width="1000px" append-to-body>
            <el-form ref="waybillRef" :model="form" :rules="rules" label-width="120px" class="grid col-2">
				<el-form-item label="货物名称" prop="goodsName">
				    <el-input v-model="form.goodsName" placeholder="请输入货物名称" />
				</el-form-item>
				<el-form-item label="货物类型" prop="goodsClass">
					<el-select v-model="form.goodsClass" placeholder="请选择">
						<el-option
						  v-for="item in sys_goods_type"
						  :key="item.value"
						  :label="item.label"
						  :value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
                <el-form-item label="货物重量" prop="goodsWeight">
                    <el-input placeholder="请输入重量" v-model="form.goodsWeight">
						<template #prepend>
							<el-select v-model="form.goodsWeightUnit" placeholder="请选择">
								<el-option
									v-for="item in sys_goods_unit"
									:key="item.value"
									:label="item.label"
									:value="item.value">
								</el-option>
							</el-select>
						</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="期望单价" prop="unitPrice">
                    <el-input v-model="form.unitPrice" placeholder="请输入单价" />
                </el-form-item>
                <el-form-item label="期望总价" prop="totalPrice">
                    <el-input disabled :value="form.unitPrice*form.goodsWeight" placeholder="请输入总价" />
                </el-form-item>
				<el-form-item label="客户名称" prop="corporateId">
				    <el-select v-model="form.corporateId" placeholder="请选择">
				    	<el-option
				    	  v-for="item in corporateList"
				    	  :key="item.corporateId"
				    	  :label="item.corporateName"
				    	  :value="item.corporateId">
							<span style="float: left;margin-right: 30px;">{{ item.corporateName }}</span>
							<span style="float: right; color: #8492a6; font-size: 13px">{{ item.contacts }} - {{ item.contactNumber }}</span>
				    	</el-option>
				    </el-select>
				</el-form-item>
				<el-form-item label="提货联系人" prop="pickingContact" class="margin-top">
				    <el-input v-model="form.pickingContact" placeholder="请输入提货联系人" />
				</el-form-item>
				<el-form-item label="卸货联系人" prop="unloadingContact" class="margin-top">
				    <el-input v-model="form.unloadingContact" placeholder="请输入卸货联系人" />
				</el-form-item>
				<el-form-item label="联系电话" prop="pickingPhone">
				    <el-input v-model="form.pickingPhone" placeholder="请输入联系人" />
				</el-form-item>
				<el-form-item label="联系电话" prop="unloadingPhone">
				    <el-input v-model="form.unloadingPhone" placeholder="请输入联系人" />
				</el-form-item>
                <el-form-item label="提货时间" prop="pickingDate">
                    <el-date-picker clearable v-model="form.pickingDate" type="date" value-format="YYYY-MM-DD"
                        placeholder="请选择提货时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="卸货时间" prop="unloadingDate">
                    <el-date-picker clearable v-model="form.unloadingDate" type="date" value-format="YYYY-MM-DD"
                        placeholder="请选择卸货时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="提货地址" prop="pickingAddress">
                    <el-input v-model="form.pickingAddress" type="textarea" :rows="3" placeholder="请输入提货地址" />
                </el-form-item>
                <el-form-item label="卸货地址" prop="unloadingAddress">
                    <el-input v-model="form.unloadingAddress" type="textarea" :rows="3" placeholder="请输入卸货地址" />
                </el-form-item>
				<el-form-item label="备注" prop="remark">
				    <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
				</el-form-item>
            </el-form>
            <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="Waybill">
// import { listWaybill, getWaybill, delWaybill, addWaybill, updateWaybill,downloadWaybill } from "@/api/waybill/waybill";
// import { treeselect } from "@/api/system/dept";
// import { listDept } from "@/api/system/dept";
const { proxy } = getCurrentInstance();
const { sys_goods_unit, sys_goods_type, sys_waybill_status } = proxy.useDict('sys_goods_unit', 'sys_goods_type','sys_waybill_status');
const waybillList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const corporateList = ref([]);
const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsName: null,
        goodsClass: null,
    },
    rules: {
		goodsName: [{required: true, message: "货物名称不能为空", trigger: "blur" }],
		goodsClass: [{required: true, message: "货物类型不能为空", trigger: "blur" }],
		goodsWeight: [{required: true, message: "货物重量不能为空", trigger: "blur" }],
		goodsWeightUnit: [{required: true, message: "货物重量单位不能为空", trigger: "blur" }],
		unitPrice: [{required: true, message: "货物单价不能为空", trigger: "blur" }],
		corporateId: [{required: true, message: "客户信息不能为空", trigger: "blur" }],
		pickingContact: [{required: true, message: "提货联系人不能为空", trigger: "blur" }],
		unloadingContact: [{required: true, message: "卸货联系人不能为空", trigger: "blur" }],
		pickingPhone: [{required: true, message: "提货联系电话不能为空", trigger: "blur" }],
		unloadingPhone: [{required: true, message: "卸货联系电话不能为空", trigger: "blur" }],
		pickingDate: [{required: true, message: "提货时间不能为空", trigger: "blur" }],
		unloadingDate: [{required: true, message: "卸货时间不能为空", trigger: "blur" }],
		pickingAddress: [{required: true, message: "提货地址不能为空", trigger: "blur" }],
		unloadingAddress: [{required: true, message: "卸货地址不能为空", trigger: "blur" }],
    }
});

const { queryParams, form, rules } = toRefs(data);
const baseUrl = import.meta.env.VITE_APP_BASE_API;
function handlePreview(_src){
	 if (!/\.(pdf|PDF)$/.test(_src)) { 
		window.open(import.meta.env.VITE_APP_BASE_API + _src,"_blank");
        return false;
    } else {
		
	}
}
/** 查询订单列表 */
function getList() {
    loading.value = true;
    // listWaybill(queryParams.value).then(response => {
    //     waybillList.value = response.rows;
    //     total.value = response.total;
		waybillList.value = [{
			waybillId: "1562455480510550016",
			goodsName:"机制砂",
			goodsClass: "20",
			goodsWeight: 350000,
			goodsWeightUnit: "4",
			unitPrice: 155,
			totalPrice: null,
			corporateId: 13,
			pickingContact: "小李",
			unloadingContact: "小师",
			pickingPhone: "13302012019",
			unloadingPhone: "15536942019",
			pickingDate: "2022-08-01",
			unloadingDate: "2024-08-01",
			pickingAddress: "广东省惠州市龙门县惠州市龙门县龙江镇龙江路50号",
			unloadingAddress: "广东省佛山市三水区三水华润城",
			remarks:"",
			waybillState: 30
		}];
		total.value = 1;
        loading.value = false;
    // });
}

function addList() {
    loading.value = true;
    listWaybill(queryParams.value)
        .then(response => {
            waybillList.value.push(...response.rows);
            total.value = response.total;
            if (waybillList.value.length >= total.value) finished.value = true;
            loading.value = false;
        })
        .catch(response => {
            loading.value = false;
        });
}

// 下拉刷新
function handlePullDownRefresh() {
    queryParams.value.pageNum = 1;
    waybillList.value = [];
    addList();
}

// 滚动到底部的事件
function handleReachBottom() {
    queryParams.value.pageNum++;
    addList();
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 表单重置
function reset() {
    form.value = {
        waybillId: null,
		goodsName: null,
        goodsClass: null,
        goodsWeight: null,
        goodsWeightUnit: "1",
        unitPrice: null,
        totalPrice: null,
        corporateId: null,
        pickingContact: null,
        unloadingContact: null,
        pickingPhone: null,
        unloadingPhone: null,
        pickingDate: null,
        unloadingDate: null,
        pickingAddress: null,
        unloadingAddress: null,
		remarks:null
    };
    proxy.resetForm("waybillRef");
}

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

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
}

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

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

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const waybillId = row.waybillId || ids.value
    // getWaybill(waybillId).then(response => {
        // form.value = response.data;
		form.value = JSON.parse(JSON.stringify(row));
        open.value = true;
        title.value = "修改订单";
    // });
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["waybillRef"].validate(valid => {
        if (valid) {
            if (form.value.waybillId != null) {
                updateWaybill(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                addWaybill(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}

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

/** 导出按钮操作 */
function handleExport() {
    downloadWaybill(queryParams.value)
    // proxy.download('certificate/certificate/export', {
    //   ...queryParams.value
    // }, `certificate_${new Date().getTime()}.xlsx`)
}

/** 详细按钮操作 */
function handleView(row) {
}

/** 查询部门下拉树结构 */
function getTreeselect() {
	corporateList.value = [{
							corporateId:12,
							corporateName:"易站智联科技（广州）有限公司",
							contacts:"陈志朋",
							contactNumber:"13570960169",
							companyAddress:"广东省广州市天河区天顺路粤港澳大湾区创新创业孵化基地B栋413"
						},{
							corporateId:13,
							corporateName:"广州扬海公司",
							contacts:"吕",
							contactNumber:"84989925",
							companyAddress:"广东省广州市南沙区兴发大街107号"
						}];
    // treeselect().then(response => {
    //     deptOptions.value = response.data;
    // });
};


function initialData() {
    getTreeselect();
    getList();
}

onActivated(() => {
    // console.log("onActivated")
    initialData();
})
onMounted(() => {
    // console.log("onMounted")
    initialData();
})
</script>

