<template>
    <el-dialog title="客户服务预约" :visible.sync="dislogFormVisible" width="900px" :close-on-click-modal="false" center
        :modal="true">
        <el-form ref="updateAddressForm" :model="updateAddressForm" :rules="updateAddressFormRules" status-icon
            label-position="center" label-width="100px">
            <el-row v-if="updateAddressForm.status==8">
                <el-form-item label="客户意向" prop="expect">
                    <el-radio-group v-model="updateAddressForm.expect" @change="expectChange">
                        <el-radio :label="1">预约</el-radio>
                        <el-radio :label="2">有预期</el-radio>
                        <el-radio :label="3">暂不预约</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="预约联系人" prop="consignee">
                        <el-input v-model="updateAddressForm.consignee" clearable placeholder="请输入预约联系人" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="预约电话" prop="mobile">
                        <el-input v-model="updateAddressForm.mobile" clearable placeholder="请输入预约联系人的电话" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="服务地址" prop="addressDetail">
                        <el-input v-model="updateAddressForm.addressDetail" placeholder="请输入客户详细服务地址">
                            <i slot="suffix" class="el-icon-location" style="font-size:25px;cursor: pointer;margin-top:6px"
                                @click="btnSearchClick"></i></el-input>
                        <!-- <el-button type="primary" size="mini" @click=" btnSearchClick ">查询地址</el-button> -->
                    </el-form-item>
                </el-col>
                <el-col :span="12" style="display: flex;">
                    <el-form-item label="服务日期" prop="bookDate" style="margin-bottom: 2px">
                        <el-date-picker v-model="updateAddressForm.bookDate" :disabled="updateAddressForm.expect == 3" type="date" placeholder="请选择服务日期"
                            style="width: 180px" value-format="yyyy-MM-dd" />
                        <el-select v-model="updateAddressForm.bookTime" clearable :disabled="updateAddressForm.expect == 3" style="width: 140px" class="filter-item"
                            placeholder="服务时间段">
                            <el-option v-for="item in  timerange" :key="item" :label="item" :value="item" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="服务人员" prop="servantId">
                        <el-select v-model="updateAddressForm.servantId" :disabled="updateAddressForm.expect != 1" clearable class="filter-item" style="width:100%"
                            placeholder="服务人员" filterable>
                            <el-option v-for="item in  fraWorkers " :key="item.id"  :label="item.name+'('+item.tel+')'"  :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="7">
                    <el-form-item label="计提金额" prop="servantFee">
                        <el-input v-model="updateAddressForm.servantFee" type="number" :disabled="updateAddressForm.expect != 1" placeholder="服务者的计提" />
                    </el-form-item>
                </el-col>
                <el-col :span="5" style="text-align: right;">
                    <el-button @click="dislogFormVisible = false">取消</el-button>
                    <el-button type="success" @click="submit">保存</el-button>
                </el-col>
            </el-row>

        </el-form>
        <div id="container" style=" height: 450px; width: 100%;"></div>

    </el-dialog>
</template>


<script>
import moment from "moment";
import { updateOrderAddressV2, getGoodsTimeRange, getWorkerByFraId } from "@/api/order";
import { getLngLat } from "@/api/address"
export default {
    name: 'serviceBookRef',
    data() {
        var validBookDate = (rule, value, callback) => {
            if (this.updateAddressForm.expect == 3) {
                callback();
            } else {
                if (this.updateAddressForm.bookDate == null || this.updateAddressForm.bookTime == null)
                    callback(new Error("请选择日期"));
                else 
                callback();
            }
        };
        return {
            servantList: [],
            timerange: [],
            dislogFormVisible: false,
            map: "",
            marker: '',
            fraWorkers: [],//加盟商的兼职阿姨
            updateAddressForm: {
                consignee: '',
                mobile: '',
                addressDetail: '',
                cancelBookOrderDetail: 0,
                location: '',//经纬度
                orderId: '',
            },
            updateAddressFormRules: {
                bookTime: [{ validator:validBookDate,required: true, message: "请选择服务时间", trigger: "blur" },],
                bookDate: [{ validator:validBookDate,required: true, message: "请选择服务日期", trigger: "blur" },],
                consignee: [
                    { required: true, message: "请输入客户名称", trigger: "blur" },
                ],
                mobile: [
                    { required: true, message: "请输入客户电话", trigger: "blur" },
                ],
                area: [{ required: true, message: "请选择省市区", trigger: "change" }],
                addressDetail: [
                    { required: true, message: "请输入客户地址", trigger: "blur" },
                ],
                cancelBookOrderDetail: [
                    {
                        required: true,
                        message: "是否取消已预约未服务工单",
                        trigger: "blur",
                    },
                ]
            }
        }
    },
    mounted() {
    },
    methods: {
        expectChange() {
            if (this.updateAddressForm.expect == 3) {
                this.updateAddressForm.bookDate = null;
                this.updateAddressForm.bookTime = null;
                this.updateAddressForm.servantId = null;
                this.updateAddressForm.servantFee = null;
            }
            if (this.updateAddressForm.expect == 2) {
                this.updateAddressForm.servantId = null;
                this.updateAddressForm.servantFee = null;
            }

        },
        btnSearchClick() {
            if (!this.updateAddressForm.addressDetail || this.updateAddressForm.addressDetail == '' || this.updateAddressForm.addressDetail.length < 12) {
                this.$notify.warning({
                    title: "提醒",
                    message: "请输入客户详细地址",
                });
                return;
            }
            getLngLat({ address: this.updateAddressForm.addressDetail }).then(res => {
                this.updateAddressForm.location = res.data.data;
                this.makeMarker();
            }).catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg
          })
        })
        },
        init(data) {
            this.dislogFormVisible = true;
            let location = [];
            if (data.lng) {
                location.push(data.lng);
                location.push(data.lat);
            }
            // console.info(location)

            this.getGoodsTimeRange(data.orderId);
            this.getFraWorkers(data.fraId);
            this.updateAddressForm = {
                mobile: data.mobile,
                consignee: data.consignee,
                addressDetail: data.address,
                cancelBookOrderDetail: 0,
                location: location,
                orderId: data.orderId,
                bookDate: data.bookDate,
                bookTime: (data.bookStartTime ? (data.bookStartTime + '-' + data.bookEndTime) : ''),
                serviceId: data.id,
                servantId: data.servantId?parseInt(data.servantId):'',
                servantName: data.servantName,
                servantMobile: data.servantMobile,
                servantFee:data.servantFee,
                orderChannel:data.orderChannel,
                status:data.status,
                expect:1
            }

            // console.info(this.updateAddressForm)
            if (this.marker != '')
                this.marker.setMap(null);
            setTimeout(() => {
                this.initMap();
                this.makeMarker('init');
            }, 1000);
        },
        submit() {
            //预约时间是否小于今天
            let now = moment(new Date()).format("YYYY-MM-DD");
            if (this.updateAddressForm.bookDate < now) {
                this.$notify.warning({
                    title: "提醒",
                    message: "预约时间不能小于当天",
                });
                return;
            }
            if(this.updateAddressForm.location.length<2){
                this.$notify.warning({
                    title: "提醒",
                    message: "请点击地址框后的图标 定位客户地址",
                });
                return;
            }

            this.$refs["updateAddressForm"].validate((valid) => {
                console.info(valid)
                if (valid) {
                    const loading = this.$loading({
                        lock: true,
                        text: "提交中...",
                        spinner: "el-icon-loading",
                        background: "rgba(0, 0, 0, 0.5)",
                    });
                    console.info(this.updateAddressForm.location)
                    if (this.updateAddressForm.servantId) {
                        let servnats = this.fraWorkers.filter(item => { return item.id == this.updateAddressForm.servantId });
                        if (servnats.length > 0) {
                            this.updateAddressForm.servantName = servnats[0].name;
                            this.updateAddressForm.servantMobile = servnats[0].tel;
                        }

                    }
                    updateOrderAddressV2({
                        addressDto: {
                            addressDetail: this.updateAddressForm.addressDetail,
                            name: this.updateAddressForm.consignee,
                            tel: this.updateAddressForm.mobile,
                            lng: this.updateAddressForm.location[0],
                            lat: this.updateAddressForm.location[1],
                        },
                        serviceId: this.updateAddressForm.serviceId,
                        bookDate: this.updateAddressForm.bookDate,
                        bookTime: this.updateAddressForm.bookTime,
                        orderId: this.updateAddressForm.orderId,
                        servantId: this.updateAddressForm.servantId,
                        servantName: this.updateAddressForm.servantName,
                        servantMobile: this.updateAddressForm.servantMobile,
                        servantFee:this.updateAddressForm.servantFee,
                        cancelBookOrderDetail: this.updateAddressForm.cancelBookOrderDetail,
                        expect:this.updateAddressForm.expect
                    })
                        .then((response) => {
                            loading.close();
                            this.dislogFormVisible = false;
                            this.$notify.success({
                                title: "成功",
                                message: "修改成功,请刷新查看",
                            });
                            this.$emit('success',
                                {
                                    serviceId: this.updateAddressForm.serviceId,
                                    orderId: this.updateAddressForm.orderId,
                                    address: this.updateAddressForm.addressDetail,
                                    mobile: this.updateAddressForm.mobile,
                                    consignee: this.updateAddressForm.consignee,
                                    position: this.updateAddressForm.location.join(','),
                                    workerId: this.updateAddressForm.servantId,
                                    workerName: this.updateAddressForm.servantName,
                                    workerTel: this.updateAddressForm.servantMobile,
                                    bookTime: this.updateAddressForm.bookDate + " " + this.updateAddressForm.bookTime.split('-')[0],
                                    bookStartTime: this.updateAddressForm.bookTime.split('-')[0],
                                    bookEndTime: this.updateAddressForm.bookTime.split('-')[1]
                                });
                        })
                        .catch((response) => {
                            loading.close();
                            this.$notify.error({
                                title: "修改失败",
                                message: response.data.errmsg,
                            });
                        });
                    // });
                }
            });
        },
        initMap() {
            if (this.map) return;
            let that = this;
            this.map = new AMap.Map("container", {
                resizeEnable: true
            });
            this.map.setDefaultCursor("pointer");
            this.map.on('click', function (e) {
                that.updateAddressForm.location = [];
                that.updateAddressForm.location.push(e.lnglat.getLng())
                that.updateAddressForm.location.push(e.lnglat.getLat())
                console.info(that.updateAddressForm.location)
                that.makeMarker('');
            });
        },
        getFraWorkers(fraId) {
            getWorkerByFraId({ fraId: fraId }).then(res => {
                this.fraWorkers = res.data.data
            })
        },
        getGoodsTimeRange(orderId) {
            getGoodsTimeRange({ orderId: orderId }).then(res => {
                this.timerange = res.data.data;
            })
        },
        makeMarker(type) {
            console.info('makeMarker')
            if (this.updateAddressForm.location == '' || this.updateAddressForm.location.length == 0) return;
            if (this.marker == '') {
                this.marker = new AMap.Marker({
                    icon: "https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png",
                    position: this.updateAddressForm.location,
                    offset: new AMap.Pixel(-15, -15),
                    map: this.map
                });
                this.marker.setLabel({
                    offset: new AMap.Pixel(0, -10),  //设置文本标注偏移量
                    content: "<div class='info'>" + this.updateAddressForm.addressDetail + "</div>", //设置文本标注内容
                    direction: 'right' //设置文本标注方位
                });
            }
            else {
                this.marker.setMap(this.map);
                this.marker.setPosition(this.updateAddressForm.location);
                this.marker.setLabel({
                    offset: new AMap.Pixel(0, -10),  //设置文本标注偏移量
                    content: "<div class='info'>" + this.updateAddressForm.addressDetail + "</div>", //设置文本标注内容
                    direction: 'right' //设置文本标注方位
                });
            }

            this.map.setCenter(this.updateAddressForm.location);
            if (type && type == "init")
                this.map.setZoom(15);
        }
    }
}
</script>

<style>
.marker {
    position: absolute;
    top: -20px;
    right: -118px;
    color: #fff;
    padding: 4px 10px;
    box-shadow: 1px 1px 1px rgba(10, 10, 10, .2);
    white-space: nowrap;
    font-size: 12px;
    font-family: "";
    background-color: #25A5F7;
    border-radius: 3px;
}

.dialog-footer {
    text-align: right;
}

.amap-icon img,
.amap-marker-content img {
    width: 25px;
    height: 34px;
}

.marker {
    position: absolute;
    top: -20px;
    right: -118px;
    color: #fff;
    padding: 4px 10px;
    box-shadow: 1px 1px 1px rgba(10, 10, 10, .2);
    white-space: nowrap;
    font-size: 12px;
    font-family: "";
    background-color: #25A5F7;
    border-radius: 3px;
}

.el-dialog--center .el-dialog__body {
    padding-top: 10px;
    padding-bottom: 5px;
}
</style>
