<template>
    <el-dialog title="修改预约" :visible.sync="dislogFormVisible" width="1350px" :close-on-click-modal="false" center
        :modal="true">
        <div style="width:1310px;height:680px;">
            <div style="width:600px;border-right: 2px solid #f4f4f5;float:left;">
                <el-row class="titlename">
                    <h3>客户信息</h3>
                </el-row>

                <el-form ref="updateAddressForm" :model="updateAddressForm" :rules="updateAddressFormRules" status-icon
                    label-position="center" label-width="100px">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="预约联系人" prop="bookName">
                                <el-input v-model="updateAddressForm.bookName" clearable placeholder="请输入预约联系人" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="预约电话" prop="bookTel">
                                <el-input v-model="updateAddressForm.bookTel" clearable placeholder="请输入预约联系人的电话" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-form-item label="服务地址" prop="bookAddress">
                            <el-input style="width:420px;" v-model="updateAddressForm.bookAddress"
                                placeholder="请输入客户详细服务地址">
                                <i slot="suffix" class="el-icon-location"
                                    style="font-size:25px;cursor: pointer;margin-top:6px"
                                    @click="btnSearchClick"></i></el-input>
                            <div style="color:red;font-size: 12px;position: absolute;">
                                客户信息修改后，请点击保存（地址输入后，需点击后面小图标定位后再保存）</div>
                            <el-button type="primary" size="mini" @click="submit">保存</el-button>
                        </el-form-item>

                        <!-- <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-form>
                <div id="container" style=" margin-top:20px;height: 450px; width: 100%;"></div>
            </div>

            <div style="width:700px;float:right;">
                <el-row class="titlename">
                    <h3>服务信息（工单编号：{{updateAddressForm.detailId}}）</h3>
                </el-row>
                <el-row><span class="servicename">商品名称：</span>{{ bookservantInfo.productName }}</el-row>
                <el-row><span class="servicename">服务人数：</span>{{ bookservantInfo.assignedWorkerTotal }}/{{
        bookservantInfo.workerTotal }} &nbsp;&nbsp;&nbsp; {{ bookservantInfo.skillMsg }}</el-row>
                <el-row><span class="servicename">客户预约时间：</span>{{ bookservantInfo.bookTime }}</el-row>
                <div :style="bookservantInfo.workers.length > 2 ? 'overflow-y:scroll;height: 500px;' : ''">
                    <el-row v-for="(bk, index) in bookservantInfo.workers" :key="index">
                        <hr />
                        <div style="width:400px;font-size: 20px;font-weight: bold;margin-top:20px;margin-bottom: 10px;">
                            服务者{{ index + 1 }} ({{ bk.skillName }}，{{ bk.serviceLength }}小时，{{
        bk.sort != null && bk.sort > 0 ? '有序' : '无序' }})
                        </div>
                        <div>
                            <el-form labelPosition="right" label-width="90px">
                                <el-row>
                                    <el-col :span="9">
                                        <el-form-item label="人员类型">
                                            <el-select v-model="bk.type" class="filter-item" placeholder="人员类型"
                                                filterable @change="selectWorkerType(bk, index)">
                                                <el-option v-for="item in  servantType " :key="item.type"
                                                    :label="item.name" :value="item.type" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="15">
                                        <el-form-item label="服务人员">
                                            <el-select v-if="bk.type == null || bk.type == 1" v-model="bk.workerId"
                                                @change="changeTempWorker(bk, index)" 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>
                                            <template v-else>
                                                <el-input disabled style="width:220px;" v-model="bk.workerName"
                                                    clearable />
                                                <span @click="showFullBook(index,bk.workerSkillId)"
                                                    style="color:deepskyblue;cursor:pointer;">改派全职</span>
                                                <span @click="changeFUllWorker(bk)" v-if="bk.workerName != ''"
                                                    style="color:deepskyblue;cursor:pointer;">清除</span>
                                            </template>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="9">
                                        <el-form-item label="服务技能">
                                            <el-select v-model="bk.workerSkillId" class="filter-item" disabled
                                                style="width:100%" placeholder="服务技能">
                                                <el-option v-for="item in  bookservantInfo.skillWorkerTotalList "
                                                    :key="item.id" :label="item.skillName" :value="item.skillId" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="15">
                                        <el-form-item label="服务日期" style="margin-bottom: 2px">
                                            <el-date-picker v-model="bk.bookDate" type="date"
                                                :disabled="bk.type != null && bk.type == 0" placeholder="请选择服务日期"
                                                style="width: 160px" value-format="yyyy-MM-dd" popper-class='noClear' />
                                            <el-select v-model="bk.timested" style="width: 140px"  @change="setTimeStEd(bk)"
                                                :disabled="bk.type != null && bk.type == 0" class="filter-item"
                                                placeholder="服务时间段">
                                                <el-option v-for="item in  getskillTimeRange(bk.serviceLength)"
                                                    :key="item" :label="item" :value="item" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>

                                </el-row>
                            </el-form>
                        </div>

                    </el-row>
                </div>
                <el-row style="color:red;font-size:12px;">*多人服务时，日期不可跨天,相同技能服务时间需一致</el-row>
            </div>

        </div>

        <div style="text-align:right;margin-top:10px;height:60px;">
            <el-button type="info" plain @click="dislogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="updateWorker">提交</el-button>
        </div>
        <reassignOrder ref="reassignOrderRef" />
    </el-dialog>
</template>


<script>
import moment from "moment";
import { updateOrderAddressV2, getGoodsTimeRange, getWorkerByFraId } from "@/api/order";
import { getDetailWorker, modifyBookAddress, changeWorker } from "@/api/orderBookDetail";
import { getLngLat } from "@/api/address"
import { enableConsult } from '@/api/ticketConsult';
import reassignOrder from "@/views/order/components/reassignOrder";
export default {
    name: 'serviceBookRef',
    components: { reassignOrder },
    data() {

        return {
            failworker: '',
            tempRow: { id: '', orderId: '', fraId: '' },//工单id，订单id，加盟商id
            tempIndex: '',//选全职时标记行
            servantType: [{ type: 0, name: '全职' }, { type: 1, name: '兼职' }],
            bookservantInfo: {
                skillWorkerTotalList: [],//技能对应人数
                workers: []
            },
            skillTimerange: [],
            dislogFormVisible: false,
            map: "",
            marker: '',
            fraWorkers: [],//加盟商的兼职阿姨
            updateAddressForm: {//客户信息
                detailId: '',
                orderId: '',
                fraId: '',
                bookName: '',
                bookTel: '',
                bookAddress: '',
                lat: '',
                lng: '',
            },
            updateAddressFormRules: {

                bookName: [
                    { required: true, message: "请输入客户名称", trigger: "blur" },
                ],
                bookTel: [
                    { required: true, message: "请输入客户电话", trigger: "blur" },
                ],

                bookAddress: [
                    { required: true, message: "请输入客户地址", trigger: "blur" },
                ],
            }
        }
    },
    mounted() {
    },
    methods: {
        init(data) {
            console.info(data)

            this.dislogFormVisible = true;
            this.tempRow = data;
            this.updateAddressForm = {
                detailId: data.id,
                orderId: data.orderId,
                fraId: data.fraId,
                bookName: '',
                bookTel: '',
                bookAddress: '',
                lat: '',
                lng: '',
            }


            this.getbookServantInfo();//工单上服务人员信息
            this.getGoodsTimeRange();
            this.getFraWorkers();//兼职人员

            if (this.marker != '')
                this.marker.setMap(null);
            setTimeout(() => {
                this.initMap();
                this.makeMarker('init');
            }, 1000);
        },
        showFullBook(index,skillId) {
            //标记被选的行
            this.tempIndex = index;
            console.log(this.tempIndex);
            this.$refs.reassignOrderRef.initDrawer(this.tempRow.id, this.bookservantInfo.skillWorkerTotalList,skillId,this.bookservantInfo.workers,index);
        },
        settingFullWorker(resWorker) {
            //接收全职人员的信息
            //         let resWorker={
            //       type:0,
            //       workerId:this.reassignForm.servantId,
            //       workerName:this.reassignForm.workerName,
            //       scheduleId:this.reassignForm.scheduleId,
            //       workerSkillId:this.tempSkillId,
            //       skillName:skillName,
            //       bookDate :this.reassignForm.bookDate,
            //       bookStartTime :this.reassignForm.startTime,
            //       bookEndTime : this.reassignForm.endTime
            //   };
            let tempworker = this.bookservantInfo.workers[this.tempIndex];
            tempworker.type = 0;
            tempworker.workerId = resWorker.workerId;
            tempworker.workerName = resWorker.workerName;
            tempworker.scheduleId = resWorker.scheduleId;
            tempworker.workerSkillId = resWorker.workerSkillId;
            tempworker.skillName = resWorker.skillName;
            tempworker.bookDate = resWorker.bookDate;
            tempworker.timested = resWorker.bookStartTime + '-' + resWorker.bookEndTime;
            tempworker.bookStartTime=resWorker.bookStartTime;
            tempworker.bookEndTime=resWorker.bookEndTime;

            this.bookservantInfo.workers[this.tempIndex] = tempworker;
            console.log(this.bookservantInfo.workers[this.tempIndex]);
        },
        updateWorker() {
            let worker = this.validChooseWorker();
            if (this.failworker != '') {
                this.$message({
                    type: "warning",
                    message: this.failworker
                });
                return;
            }
            const loading = this.$loading({
                lock: true,
                text: "提交中...",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.5)",
            });
            let req = {
                detailId: this.updateAddressForm.detailId,
                fraId: this.updateAddressForm.fraId,
                // bookDate: worker.length == 0 ? this.bookservantInfo.bookDate : worker[0].bookDate,
                // bookStartTime: worker.length == 0 ? this.bookservantInfo.bookStartTime : worker[0].timested.split('-')[0],
                // bookEndTime: worker.length == 0 ? this.bookservantInfo.bookEndTime : worker[0].timested.split('-')[1],
                workerInfoList: worker.length == 0 ? this.bookservantInfo.workers2 : worker
            }
            changeWorker(req).then(res => {
                loading.close();
                this.dislogFormVisible = false;
                this.$notify.success({
                    title: "成功",
                    message: "修改成功",
                });
                this.$parent.getList();
            }).catch(response => {
                loading.close();
                this.$notify.error({
                    title: "失败",
                    message: response.data.errmsg,
                });
            })

        },
        validChooseWorker() {
            //如果条件任意一个没选，丢弃结果
            //校验预约时间不能小于当天，且预约日期要统一
            console.log(this.bookservantInfo.workers);
            let validWorker = [];
            let failworker = '';
            let ss=0;
            this.bookservantInfo.workers.forEach(e => {
                ss++;
                if(e.bookDate==null||e.bookDate==''||e.bookStartTime==null||e.bookStartTime==''){
                    failworker=failworker+'第'+ss+'个服务人员，没选服务时间；';
                }
                if (e.workerId != null && e.workerId != '' && e.workerName != null && e.workerName != '' &&
                    (e.type == null || e.workerSkillId == null || e.workerSkillId == '' || e.workerName == null || e.workerName == ''
                    )
                ) {
                    failworker =  failworker + e.workerName + " 服务技能或人员类型未选；"
                }

                if (e.type != null && e.workerSkillId != null && e.workerSkillId != ''
                    && e.workerId != null && e.workerId != '' && e.workerName != null && e.workerName != ''
                ) {
                    if (e.type == 0 && e.scheduleId != null && e.scheduleId != '') {
                        validWorker.push(e);
                    } else {
                        validWorker.push(e);
                    }
                }
            })
            this.failworker = failworker;
            if (validWorker.length > 1) {
                //同技能时，校验相同日期时间要一致
                for (var i = 0; i < validWorker.length; i++) {
                    let tm = validWorker[i].bookDate + validWorker[i].timested;
                    let wk = validWorker[i].workerId;
                    for (var k = 0; k < validWorker.length; k++) {
                        let tm2 = validWorker[k].bookDate + validWorker[k].timested;
                        let wk2 = validWorker[k].workerId;
                        if (validWorker[i].bookDate != validWorker[k].bookDate) {
                            this.failworker = this.failworker + '多人服务时，日期不可跨天；';
                            return [];
                        }
                        if (validWorker[i].workerSkillId == validWorker[k].workerSkillId && tm != tm2) {
                            this.failworker = this.failworker + '相同技能，服务时间必须一致；';
                            return [];
                        }
                        // if (wk == wk2 && i != k) {
                        //     this.$message({
                        //         type: "warning",
                        //         message: "多人服务时，人员不能重复"
                        //     });
                        //     return;
                        // }
                    }
                }
            }

            validWorker.forEach(v => {
                this.fraWorkers.forEach(e => {
                    if (v.type == 1 && v.workerId == e.id) {
                        v.workerName = e.name;
                        v.workerTel = e.tel;
                    }
                })
            })

            return validWorker;
        },
        selectWorkerType(row, index) {
            let tempWorker = this.bookservantInfo.workers[index];
            //切换全职兼职类型，清空 技能，档期，人员姓名，人员id
            if (row.type == 1) {
                //变成了兼职
                tempWorker.workerId = '';
                tempWorker.workerName = '';
                tempWorker.workerTel = '';
                tempWorker.scheduleId = '';
            } else {
                tempWorker.workerId = '';
                tempWorker.workerName = '';
            }
        },
        changeFUllWorker(row) {
            row.workerId = '';
            row.workerName = '';
            row.workerTel = '';
            row.scheduleId = '';
        },
        changeTempWorker(row, index) {
            if (row.workerId == null || row.workerId == '') {
                row.workerName = null;
                return;
            }
            //选兼职时，填充人员
            this.fraWorkers.forEach(e => {
                if (row.workerId == e.id) {
                    row.workerName = e.name;
                }
            })
        },

        getbookServantInfo() {
            getDetailWorker({ detailId: this.updateAddressForm.detailId }).then(res => {
                if (res.data.errno == 0) {
                    let tempData = res.data.data;
                    tempData.workers2 = tempData.workers;//构造未修改信息

                    this.updateAddressForm.bookName = tempData.bookName;
                    this.updateAddressForm.bookTel = tempData.bookTel;
                    this.updateAddressForm.bookAddress = tempData.bookAddress;
                    this.updateAddressForm.lat = tempData.lat;
                    this.updateAddressForm.lng = tempData.lng;


                    res.data.data.workers.forEach(p => {
                        if (p.bookStartTime != null && p.bookStartTime != '' && p.bookStartTime != 'null') {
                            p.timested = p.bookStartTime + '-' + p.bookEndTime;
                        }
                    })
                    this.bookservantInfo = tempData;
                    console.log(this.bookservantInfo);
                }
            })
        },
        submit() {
            if (this.updateAddressForm.lng == null || this.updateAddressForm.lat == '') {
                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)",
                    });
                    modifyBookAddress(this.updateAddressForm).then((response) => {
                        loading.close();
                        this.dislogFormVisible = false;
                        this.getbookServantInfo();
                        this.$notify.success({
                            title: "成功",
                            message: "修改成功",
                        });
                        this.$parent.getList();
                    }).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.lng = e.lnglat.getLng();
                that.updateAddressForm.lat = e.lnglat.getLat();
                that.makeMarker('');
            });
        },
        getFraWorkers() {
            getWorkerByFraId({ fraId: this.updateAddressForm.fraId }).then(res => {
                this.fraWorkers = res.data.data
            })
        },
        getGoodsTimeRange() {
            getGoodsTimeRange({ orderId: this.updateAddressForm.orderId }).then(res => {
                this.skillTimerange = res.data.data;
            })
        },
        setTimeStEd(row){ 
            row.bookStartTime=row.timested.split('-')[0];
            row.bookEndTime=row.timested.split('-')[1];
            console.log(row);
        },
        getskillTimeRange(serviceLength) {
            let arr = [];
            this.skillTimerange.forEach(e => {
                if (e.serviceLength == serviceLength) {
                    arr = e.timeRange;
                }
            })
            return arr;
        },
        makeMarker(type) {
            console.info('makeMarker')
            if (this.updateAddressForm.lng == '' || this.updateAddressForm.lng == null) 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.lat, this.updateAddressForm.lng],
                    offset: new AMap.Pixel(-15, -15),
                    map: this.map
                });
                this.marker.setLabel({
                    offset: new AMap.Pixel(0, -10),  //设置文本标注偏移量
                    content: "<div class='info'>" + this.updateAddressForm.bookAddress + "</div>", //设置文本标注内容
                    direction: 'right' //设置文本标注方位
                });
            }
            else {
                this.marker.setMap(this.map);
                this.marker.setPosition([this.updateAddressForm.lng, this.updateAddressForm.lat]);
                this.marker.setLabel({
                    offset: new AMap.Pixel(0, -10),  //设置文本标注偏移量
                    content: "<div class='info'>" + this.updateAddressForm.bookAddress + "</div>", //设置文本标注内容
                    direction: 'right' //设置文本标注方位
                });
            }

            this.map.setCenter([this.updateAddressForm.lng, this.updateAddressForm.lat]);
            if (type && type == "init")
                this.map.setZoom(15);
        },
        btnSearchClick() {
            if (!this.updateAddressForm.bookAddress || this.updateAddressForm.bookAddress == '' || this.updateAddressForm.bookAddress.length < 12) {
                this.$notify.warning({
                    title: "提醒",
                    message: "请输入客户详细地址",
                });
                return;
            }
            getLngLat({ address: this.updateAddressForm.bookAddress }).then(res => {
                if (res.data.errno == 0 && res.data.data.length == 2) {
                    this.updateAddressForm.lng = res.data.data[0];
                    this.updateAddressForm.lat = res.data.data[1];
                    this.makeMarker();
                }
            }).catch(response => {
                this.$notify.error({
                    title: '失败',
                    message: response.data.errmsg
                })
            })
        },
    }
}
</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;
}

.titlename {
    background-color: #f4f4f5;
    margin-bottom: 10px;
    text-indent: 20px;
}

.servicename {
    font-size: 15px;
    font-weight: bold;
    line-height: 30px;
    margin-left: 20px;
}

/* 隐藏清空按钮 */
.el-date-editor .el-range-separator+.el-input__suffix .el-input__suffix-inner,
.el-date-editor .el-input__suffix .el-input__suffix-inner {
    display: none !important;
}
</style>
