<template>
  <div class="reassign-dialog">
    <el-drawer title="一键派单" :visible.sync="drawerShow" direction="rtl" size="70%">
      <el-form
        ref="appointForm"
        :model="appointForm"
        status-icon
        label-position="right"
        label-width="120px"
        style="width: 800px; margin-left:20px;"
        :rules="appointRules"
      >
        <el-row>
          <el-col :span="18">
            <el-form-item label="服务地址" prop="addressDetail">
              <el-input v-model="appointForm.addressDetail" placeholder="请输入客户详细服务地址" clearable>
                <!-- <i
                  slot="suffix"
                  class="el-icon-location"
                  style="font-size:25px;cursor: pointer;margin-top:6px"
                  @click="btnSearchClick"
                ></i>-->
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <div
              style="display:inline-block;line-height:36px;margin-left:20px;color:#999;"
              :class="{'is-active':appointForm.addressDetail.length>5}"
              @click="addressCheck"
            >核对地址信息</div>
          </el-col>
        </el-row>
        <el-row v-if="!isAppoint">
          <el-col :span="12">
            <el-form-item label="预约客户" prop="customerName">
              <el-input v-model="appointForm.customerName" clearable placeholder="请输入预约客户" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预约电话" prop="customerPhone">
              <el-input
                v-model="appointForm.customerPhone"
                clearable
                placeholder="请输入预约电话"
                maxlength="11"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="服务频次" prop="bookDate">
              <el-select
                v-model="appointForm.type"
                style="width:100%"
                placeholder="请选择服务频次"
                @change="serviceTimesChange"
              >
                <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="12">
            <el-form-item label="服务时间" prop="bookedRangeTime">
              <el-cascader
                v-if="cascaderFlag"
                style="width:100%"
                :props="casProps"
                @change="casChange"
                v-model="appointForm.bookedRangeTime"
                :options="timeList"
                expand-trigger="click"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="首次服务日期" prop="startDate">
              <el-date-picker
                v-model="appointForm.startDate"
                type="date"
                placeholder="请选择首次服务日期"
                value-format="yyyy-MM-dd"
                style="width:100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="服务者" prop="workerName">
              <el-input
                v-model="appointForm.workerName"
                clearable
                placeholder="请输入服务者姓名"
                @input="change($event)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务者电话" prop="workerTel">
              <el-input
                v-model="appointForm.workerTel"
                clearable
                placeholder="请输入服务者电话"
                maxlength="11"
                @input="change($event)"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="margin:0 40px 20px 40px;text-align:left">
        <el-button type="primary" @click="queryStockBtn">查询库存</el-button>
      </div>

      <el-table :data="dataList" border v-loading="listLoading">
        <el-table-column property="workerId" label="服务者id" width="80"></el-table-column>
        <el-table-column property="workerName" label="服务者姓名" width="100"></el-table-column>
        <el-table-column
          v-for="(item, index) in dayList"
          :property="item"
          :label="item + '（' + getDateWeek(item) + '）'"
          :key="index"
          width="180"
        >
          <template slot-scope="scope">
            <div v-for="(item2, index2) in scope.row.dayStock[item]" :key="index2">
              <div
                @click="checkChange(item, item2, scope.$index, index2,  scope.row)"
              >
                {{ item2.startTime }}-{{ item2.endTime }}
                <i
                  class="el-icon-success"
                  v-if="item2.isChecked"
                  style="color:#09afff;font-size:22px;"
                ></i>
                <i
                  class="el-icon-success"
                  v-if="!item2.isChecked"
                  style="color:#ccc;font-size:22px;"
                ></i>
                <span
                  v-if="item2.isOccupy == 1"
                  style="font-size:10px;color:#09afff;cursor: pointer;"
                >
                  {{
                  item2.cooupyEvent }}
                </span>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <p style="margin-top:20px;">工单信息</p>
      <el-table
        :data="checkList.filter(item=>{return item.bookTime!=''&&item.bookTime!=null; })"
        border
        style="width:1000px;margin-top:40px;"
      >
        <el-table-column property="id" label="工单id" width="80" fixed></el-table-column>
        <el-table-column property="servantId" label="服务者Id" fixed></el-table-column>
        <el-table-column property="servantName" label="服务者姓名"></el-table-column>
        <el-table-column property="bookTime" label="服务时间"></el-table-column>

        <el-table-column align="center" label="操作" width="140">
          <template slot-scope="scope">
            <el-button type="danger" plain @click="handleDel(scope.row,scope.$index)">取消</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="text-align:center;margin-top:40px;">
        <el-button type="info" plain @click="drawerShow=false">取消</el-button>
        <el-button type="primary" @click="confirmDispatch">确定</el-button>
      </div>
    </el-drawer>

    <el-dialog
      title="地址核对"
      :visible.sync="mapDiaShow"
      width="800px"
      :close-on-click-modal="false"
      center
    >
      <div id="address-map" style=" height: 450px; width: 100%;"></div>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
import {
  getGoodsTimeRange,
  sendOrdersCheck,
  selectAddress,
  getStock,
  sendOrders
} from "@/api/order";
import { allRange } from "@/api/serviceTimeRange";
import {
  statusMap,
  statusModifyMap,
  bookStatusMap,
  ObjectToArray
} from "@/api/enumUtils";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import { formatDate } from "@/utils/date";
import { getUserCity } from "@/api/city";
import checkPermission from "@/utils/permission"; // 权限判断函数
import { getToken } from "@/utils/auth";

let vm;

export default {
  name: "Order",
  components: { Pagination },
  filters: {},
  data() {
    return {
      cascaderFlag: true,
      map: "",
      isAppoint: false,
      drawerShow: false,
      orderInfo: {},
      orderBookDetail: {},
      appointForm: {
        addressDetail: "",
        customerName: "",
        customerPhone: "",
        type: 1,
        startDate: "",
        bookedRangeTime: [],
        workerName: "",
        workerTel: ""
      },
      casProps: {
        multiple: false
      },
      timeList: [
        {
          value: 1,
          label: "周一"
        },
        { value: 2, label: "周二" },
        { value: 3, label: "周三" },
        { value: 4, label: "周四" },
        { value: 5, label: "周五" },
        { value: 6, label: "周六" },
        { value: 0, label: "周日" }
      ],
      appointRules: {
        addressDetail: [
          { required: true, message: "请输入客户详细服务地址", trigger: "blur" }
        ],
        customerName: [
          { required: true, message: "请输入预约客户", trigger: "blur" }
        ],
        customerPhone: [
          { required: true, message: "请输入预约电话", trigger: "blur" }
        ],
        startDate: [
          { required: true, message: "请选择首次服务日期", trigger: "blur" }
        ],
        bookedRangeTime: [
          { required: true, message: "请选择服务时间", trigger: "blur" }
        ],
        type: [{ required: true, message: "请选择服务频次", trigger: "blur" }]
      },
      checkList: [],
      mapDiaShow: false,

      listLoading: false,
      orderInfo: {},

      dataList: [],
      dayList: []
    };
  },

  computed: {},
  beforeCreate() {
    vm = this;
  },
  created() {},
  methods: {
    checkPermission,
    initDrawer(row, type) {
      this.orderInfo = row;
      this.drawerShow = true;
      this.dataList = [];
      this.checkList = [];
      sendOrdersCheck({
        bookId: row.id
      })
        .then(res => {
          if (res.data.errno == 0) {
            this.noServiceCount = res.data.data.noServiceCount;
            this.orderBookDetail = res.data.data.orderBookDetail;
            this.appointForm = {
              addressDetail: this.orderBookDetail.address,
              customerName: this.orderBookDetail.consignee,
              customerPhone: this.orderBookDetail.mobile,
              type: 1,
              workerName: "",
              workerTel: ""
            };
            this.checkList = res.data.data.orderBookDetailList;
          } else {
            this.$message.error(res.data.errmsg);
          }
        })
        .catch(err => {
          console.log(err);
        });
      getGoodsTimeRange({
        orderId: this.orderInfo.orderId
      }).then(res => {
        let list = res.data.data;
        list = list.map(item => {
          let obj = {
            value: item,
            label: item
          };
          return obj;
        });
        this.timeList = this.timeList.map(item => {
          item.children = list;
          return item;
        });
      });
    },

    addressCheck() {
      const loading = this.$loading({
        lock: true,
        text: "查询中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.5)"
      });
      this.mapDiaShow = true;
      setTimeout(() => {
        if (this.map == "") {
          this.map = new AMap.Map("address-map", {
            resizeEnable: true
          });
          this.map.setDefaultCursor("pointer");
        }

        this.map.clearMap();
        this.map.on("click", function(e) {
          console.log(e);
        });

        if (
          this.appointForm.addressDetail &&
          this.appointForm.addressDetail == this.orderBookDetail.address &&
          this.orderBookDetail.lng &&
          this.orderBookDetail.lat
        ) {
          var marker = new AMap.Marker({
            position: new AMap.LngLat(
              this.orderBookDetail.lng,
              this.orderBookDetail.lat
            )
          });
          this.map.add(marker);
          this.map.setFitView([marker]);
          loading.close();
        } else if (
          this.appointForm.addressDetail.length > 5 &&
          this.appointForm.addressDetail != this.orderBookDetail.address
        ) {
          selectAddress({
            address: this.appointForm.addressDetail,
            bookId: this.orderInfo.id,
            fraId: this.orderBookDetail.fraId
          }).then(res => {
            loading.close();
            if (res.data.errno == 0) {
              this.appointForm.lng = res.data.data.lng;
              this.appointForm.lat = res.data.data.lat;
              this.appointForm.fraId = res.data.data.fraId;
              this.appointForm.fraName = res.data.data.fraName;
              this.appointForm.serviceCityId = res.data.data.serviceCityId;
              this.appointForm.serviceCity = res.data.data.serviceCity;

              var marker = new AMap.Marker({
                position: new AMap.LngLat(res.data.data.lng, res.data.data.lat)
              });
              this.map.add(marker);
              this.map.setFitView([marker]);
              loading.close();
            } else {
              this.$message.error(res.data.errmsg);
            }
          });
        }
      }, 500);
    },
    queryStockBtn() {
      this.$refs["appointForm"].validate(valid => {
        if (valid) {
          if (
            this.orderBookDetail.address == this.appointForm.addressDetail &&
            this.orderBookDetail.address
          ) {
            this.appointForm.lng = this.orderBookDetail.lng;
            this.appointForm.lat = this.orderBookDetail.lat;
            this.appointForm.fraId = this.orderBookDetail.fraId;
            this.appointForm.fraName = this.orderBookDetail.fraName;
            this.appointForm.serviceCityId = this.orderBookDetail.serviceCityId;
            this.appointForm.serviceCity = this.orderBookDetail.serviceCity;
            this.queryStock();
          } else {
            selectAddress({
              address: this.appointForm.addressDetail,
              bookId: this.orderInfo.id,
              fraId: this.orderBookDetail.fraId
            }).then(res => {
              loading.close();
              if (res.data.errno == 0) {
                this.appointForm.lng = res.data.data.lng;
                this.appointForm.lat = res.data.data.lat;
                this.appointForm.fraId = res.data.data.fraId;
                this.appointForm.fraName = res.data.data.fraName;
                this.appointForm.serviceCityId = res.data.data.serviceCityId;
                this.appointForm.serviceCity = res.data.data.serviceCity;

                this.queryStock();
              }
            });
          }
        }
      });
    },
    queryStock() {
      console.log(this.appointForm.bookedRangeTime);
      if (
        this.appointForm.type == 2 &&
        this.appointForm.bookedRangeTime.length == 1
      ) {
        this.$message.warning("请选择两个服务时间");
        return false;
      }
      let weeks = [];
      if (this.appointForm.type == 2) {
        let list = this.appointForm.bookedRangeTime;
        list.forEach(item => {
          let obj = {
            dayOfWeek: item[0],
            startTime: item[1].split("-")[0],
            endTime: item[1].split("-")[1]
          };
          weeks.push(obj);
        });
      } else {
        weeks = [
          {
            dayOfWeek: this.appointForm.bookedRangeTime[0],
            startTime: this.appointForm.bookedRangeTime[1].split("-")[0],
            endTime: this.appointForm.bookedRangeTime[1].split("-")[1]
          }
        ];
      }
      this.listLoading = true;
      getStock({
        orderBookId: this.orderInfo.id,
        fraId: this.appointForm.fraId,
        lng: this.appointForm.lng,
        lat: this.appointForm.lat,
        serviceCityId: this.appointForm.serviceCityId,
        workerName: this.appointForm.workerName,
        workerTel: this.appointForm.workerTel,
        orderDate: {
          startDate: this.appointForm.startDate,
          weeks: weeks,
          type: this.appointForm.type
        }
      })
        .then(response => {
          console.log(response);
          if (response.data.data.dataList == 0) {
            this.$message.warning("无可用服务者");
          }
          this.dataList = response.data.data.dataList;
          this.dayList = response.data.data.dayList;

          this.listLoading = false;
        })
        .catch(err => {
          console.log(err);
          this.dataList = [];
          this.listLoading = false;

          this.$message.error(err.data.errmsg);
        });
    },
    handleDel(row, index) {
      let len = this.dataList.length;
      for (var i = 0; i < len; i++) {
        if (row.servantId == this.dataList[i].workerId) {
          if (this.dayList.includes(row.bookDate)) {
            if (this.dataList[i].dayStock[row.bookDate].length >= 1) {
              if (
                row.bookStartTime ==
                  this.dataList[i].dayStock[row.bookDate][0].startTime &&
                row.bookEndTime ==
                  this.dataList[i].dayStock[row.bookDate][0].endTime
              ) {
                this.dataList[i].dayStock[row.bookDate][0].isChecked = false;
                this.$forceUpdate();
                break;
              } else if (this.dataList[i].dayStock[row.bookDate].length == 2) {
                if (
                  row.bookStartTime ==
                    this.dataList[i].dayStock[row.bookDate][1].startTime &&
                  row.bookEndTime ==
                    this.dataList[i].dayStock[row.bookDate][1].endTime
                ) {
                  this.dataList[i].dayStock[row.bookDate][1].isChecked = false;
                  this.$forceUpdate();
                  break;
                }
              }
            }
          }
        }
      }
      let list = [];
      this.checkList.forEach(item => {
        let obj = item;
        if (item.id == row.id) {
          obj.servantId = "";
          obj.servantName = "";
          obj.bookTime = "";
        }
        list.push(obj);
      });

      this.checkList = list;
    },
    serviceTimesChange(value) {
      console.log(value);
      if (value == 2) {
        this.casProps = {
          multiple: true
        };
      } else {
        this.casProps = {
          multiple: false
        };
      }
      this.appointForm.bookedRangeTime = [];
       this.cascaderFlag = false;
      this.$nextTick(() => {
          this.cascaderFlag = true;
        });
    },
    casChange(val) {
      console.log(val);
      if (this.appointForm.type == 2 && val.length > 2) {
        // let restle=JSON.parse(JSON.stringify(val.slice(0,2)));
        // console.log(restle.toString());
        this.appointForm.bookedRangeTime = val.slice(0, 2);
        this.cascaderFlag = false;
        this.$nextTick(() => {
          this.cascaderFlag = true;
        });
      } else {
      }
    },
    checkChange(item1, item2, index1, index2, row) {
      console.log(item1, item2, index1, index2,row);
      if (item2.isChecked) {
        // 取消选中
        let list = [];
        this.checkList.forEach(item => {
          let obj = item;
          if (item.servantId == row.workerId && item.bookTime) {
            let date = item.bookTime.split(" ");
            if (
              item1 == date[0] &&
              item2.startTime == date[1].split("-")[0] &&
              item2.endTime == date[1].split("-")[1]
            ) {
              console.log("check" + item2);
              obj.servantId = "";
              obj.servantName = "";
              obj.bookTime = "";
              obj.workerTel='';
            }
          }
          list.push(obj);
        });
        console.log(list);
        this.checkList = list;

        var newList = JSON.parse(JSON.stringify(this.dataList));

        newList[index1].dayStock[item1][index2].isChecked = false;
        let item = newList[index1];
        this.$set(this.dataList, index1, item);

        this.$forceUpdate();
      } else {
        let isCanAppoint = this.checkList.some(appoint => {
          return appoint.servantId == null || appoint.bookTime == null||appoint.servantId == ''||appoint.bookTime == '';
        });
        if (!isCanAppoint) {
          this.$message.warning("请先取消已经预约好的服务单");

          return false;
        }

        let len = this.checkList.length;
        for (let i = 0; i < len; i++) {
          let item = this.checkList[i];
          if (item.servantId == "" || item.bookTime == ""||item.servantId==null||item.bookTime==null) {
            console.log('serviceindex'+i);
            this.checkList[i].servantId = row.workerId;
            this.checkList[i].servantName = row.workerName;
            this.checkList[i].workerTel = row.workerTel;
            this.checkList[i].bookDate = item1;
            this.checkList[i].bookStartTime = item2.startTime;
            this.checkList[i].bookEndTime = item2.endTime;
            this.checkList[i].bookTime =
              item1 + " " + item2.startTime + "-" + item2.endTime;
            console.log(this.checkList[i]);
            this.$forceUpdate();
            break;
          }
        }

        var newList = JSON.parse(JSON.stringify(this.dataList));

        newList[index1].dayStock[item1][index2].isChecked = true;
        let item = newList[index1];
        this.$set(this.dataList, index1, item);
        this.$forceUpdate();
      }
    },

    getServantList(id) {
      getAssignmentPerson(id).then(res => {
        this.servantList = res.data.data;
      });
    },

    confirmDispatch() {
      if (this.appointForm.addressDetail == "") {
        this.$message.error("请输入服务地址");
        return false;
      } else if (this.appointForm.customerName == "") {
        this.$message.error("请输入预约客户");
        return false;
      } else if (this.appointForm.customerPhone == "") {
        this.$message.error("请输入预约电话");
        return false;
      } else if (
        this.appointForm.addressDetail != this.orderBookDetail.address &&
        this.appointForm.lng == this.orderBookDetail.lng
      ) {
        this.$message.error("请先核对地址信息");
        return false;
      }
      let list = [];
      this.checkList.forEach(item => {
        let obj = {
          id: item.id,
          bookTime: item.bookTime,
          workerId: item.servantId,
          workerName: item.servantName,
          workerTel: item.workerTel||item.servantMobile
        };
        list.push(obj);
      });
      let params = {
        bookId: this.orderInfo.id,
        serviceCity: this.appointForm.serviceCity,
        serviceCityId: this.appointForm.serviceCityId,
        consignee: this.appointForm.customerName,
        mobile: this.appointForm.customerPhone,
        lat: this.appointForm.lat,
        lng: this.appointForm.lng,
        fraId: this.appointForm.fraId,
        fraName: this.appointForm.fraName,
        address: this.appointForm.addressDetail,
        orderBookTimeWorkers: list
      };
      sendOrders(params)
        .then(response => {
          this.$message.success("操作成功");
          console.log(response);
          this.drawerShow = false;
          this.$parent.getList();
        })
        .catch(response => {
          this.$notify.error({
            title: "失败",
            message: response.data.errmsg
          });
        });
    },

    getDateWeek(date) {
      var date = new Date(date);
      var day = date.getDay();
      let wstr = "";
      switch (day) {
        case 0:
          wstr = "星期日";
          break;
        case 1:
          wstr = "星期一";
          break;
        case 2:
          wstr = "星期二";
          break;
        case 3:
          wstr = "星期三";
          break;
        case 4:
          wstr = "星期四";
          break;
        case 5:
          wstr = "星期五";
          break;
        case 6:
          wstr = "星期六";
          break;
        default:
          wstr = "";
      }
      return wstr;
    }
  }
};
</script>

<style scoped>
>>> .el-drawer__body {
  padding: 20px !important;
  height: 500px;
  overflow-y: scroll;
}
.is-active {
  color: #20b6eb !important;
}
.is-active:hover {
  cursor: pointer;
}
.appoint-info {
  padding: 20px 0 20px 40px;
  width: 800px;
}
</style>
