<template>
  <div class="reassign-dialog">
    <el-drawer title="改派" :visible.sync="drawerShow" direction="rtl" size="70%">
      <template v-for="(item,index) in  workers" >
      <el-row :style="index==parentIndex?'color:#09afff':''"  :key="item.id"> 服务者{{ index + 1 }} ({{ item.skillName }}，{{ item.serviceLength }}小时，
        {{item.sort != null && item.sort > 0 ? '有序' : '无序' }})，
        {{ item.workerName }}{{ item.bookDate+' '+item.bookStartTime+'-'+item.bookEndTime }}</el-row>
      </template>
      <div style="padding:20px;overflow-y:scroll;">
        <el-form :inline="true" size="small" v-model="listQuery">
          <el-form-item label="时间">
            <el-date-picker v-model="listQuery.month" type="month" placeholder="选择日期" value-format="yyyy-MM" />

            <el-form-item label="服务技能">
              <el-select disabled v-model="listQuery.skillId" class="filter-item" style="width:100%" placeholder="服务技能"
                filterable @change="getServantList">
                <el-option v-for="item in  skilllist" :key="item.id" :label="item.skillName" :value="item.skillId" />
              </el-select>
            </el-form-item>
          </el-form-item>

          <el-form-item label="服务者">
            <el-select v-model="listQuery.worker" placeholder="请选择" filterable clearable>
              <el-option v-for="item in servantList" :key="item.code" :label="item.workerName" :value="item.workerId" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button icon="el-icon-search" type="primary" plan @click="querySearch">查询</el-button>
          </el-form-item>
        </el-form>

        <el-table :data="dataList" border v-loading="listLoading"  >
          <el-table-column property="workerId" label="服务者id" width="80" fixed></el-table-column>
          <el-table-column property="workerName" label="服务者姓名" width="100" fixed></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">
                <!-- {{scope.row.dayStock[item]}} -->
                <div @click="checkChange(item, item2, scope.$index, index2, scope.row.workerId, scope.row.workerName)">
                  <!--   -->
                  <!-- <el-checkbox v-model="item2.isChecked" :disabled="item2.isOccupy!=0" @change="checkChange(item,item2,scope.$index,index2)">
                    </el-checkbox>  -->
                  <!-- <i class="el-icon-circle-check" v-if="item2.isOccupy==1"></i> -->
                  {{ item2.startTime }}-{{ item2.endTime }}
                  <i class="el-icon-success" v-if="item2.isChecked && item2.isOccupy == 0"
                    style="color:#09afff;font-size:22px;"></i>
                  <i class="el-icon-success" v-if="!item2.isChecked && item2.isOccupy == 0"
                    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-column v-if="dayList.length<5" width="400">
            </el-table-column> -->
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize"
          @pagination="getList" />

        <div style="text-align:center;margin-top:20px;">
          <el-button type="primary" @click="confirmReassign2">确定</el-button>
        </div>
      </div>
    </el-drawer>


  </div>
</template>

<script>
import moment from "moment";
import axios from "axios";
import {
  detailOrder,
  listOrder,
  listChannel,
  orderBookDetail,
  orderBookReassign,
  getCalendarStock,
  getAssignmentPerson,
  getAssignmentPersonTime, getWorkerByFraId
} from "@/api/order";

import { allChannel } from "@/api/channel";
import { send, getSmsTemplate } from "@/api/sms";
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;

const orderTypeMap = {
  0: "默认下单",
  1: "代客下单",
  2: "赠送单",
  3: "理赔单",
};

export default {
  name: "Order",
  components: { Pagination },
  filters: {

  },
  data() {

    return {
      heights:'500px',
      drawerShow: false,
      tempSkillId: '',//防止篡改下拉框
      listQuery: {
        month: moment(new Date()).format("YYYY-MM"),
        detailId: '',
        worker: '',
        skillId: '',
        pageSize: 5,
        pageNo: 1
      },
      list: [],
      total: 1,
      activeName: "全职",
      listLoading: true, 
      skilllist: [],//{skillId: "1004", skillName: "开荒保洁", serviceTotal: 1}
      servantList: [],
      workers:[],//上个页面已选人员
      parentIndex:[],
      dataList: [

      ],
      dayList: [

      ],
      reassignForm: {
        servantId: '',
        workerName: '',
        bookDate: '',
        startTime: '',
        endTime: '',
        scheduleId: '',
      }


    }
  },
  computed: {},
  beforeCreate() {
    vm = this;
  },
  created() {
  },
  methods: {
    checkPermission,
    initDrawer(detailId, skilllist,skillId,workers,parentIndex) { 
      this.skilllist = skilllist;
      this.workers=workers;
      this.parentIndex=parentIndex;

      this.drawerShow = true;

      this.listQuery.detailId =detailId;
      this.listQuery.skillId=skillId;
      // if (this.skilllist != null && this.skilllist.length > 0) {
      //   this.listQuery.skillId = this.skilllist[0].skillId;
      // }

      this.reassignForm = {
        servantId: '',
        workerName: '',
        bookDate: '',
        startTime: '',
        endTime: '',
        scheduleId: '',
      };

      this.querySearch();
      this.getServantList();
    },
    checkChange(item1, item2, index1, index2, workerId, workerName) {

      console.log(item1);
      console.log(item2);
      if (!item2.isChecked && item2.isOccupy == 0) {
        var listObj = (JSON.stringify(this.dataList)).replace('true', 'false');
        var current = JSON.parse(listObj);
        this.dataList = current;

        this.$forceUpdate()
        console.log(current);
        var newList = JSON.parse(JSON.stringify(current));
        console.log(newList[index1].dayStock[item1][index2]);

        newList[index1].dayStock[item1][index2].isChecked = true;

        let item = newList[index1];
        this.$set(this.dataList, index1, item);

        this.$forceUpdate();
        this.reassignForm.servantId = workerId;
        this.reassignForm.workerName = workerName;
        this.reassignForm.bookDate = item1;
        this.reassignForm.startTime = item2.startTime;
        this.reassignForm.endTime = item2.endTime;
        this.reassignForm.scheduleId = item2.scheduleId;
      }
      else if (item2.isOccupy == 1) {
        let event = item2.cooupyEvent;
        //跳转到服务单
        this.$router.push({ path: "/goods/edit", query: { id: id } });
      }
    },
    querySearch() {
      this.listQuery.pigeNo = 1;
      this.getList();
    },
    getServantList() { 
      getAssignmentPerson({ detailId: this.listQuery.detailId, skillId: this.listQuery.skillId }).then((res) => {
        this.servantList = res.data.data; 
      });
    },
    reassignSuccess() {
      this.drawerShow = false;
      this.$parent.$parent.orderBookDetail();
    },
    confirmReassign2() {
      if (this.reassignForm.bookDate == '') {
        this.$message.error('请选择预约时段');
        return false;
      }

      let skillName = '';
      let that = this;
      this.skilllist.forEach(e => {
        if (e.skillId == that.tempSkillId) {
          skillName = e.skillName;
        }
      })

      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
      };
      console.log(resWorker);
      this.drawerShow = false;
      try {
        this.$parent.$parent.settingFullWorker(resWorker);
      } catch (error) {
        console.log(error);
      }

    },
    // confirmReassign() {
    //   if (this.reassignForm.bookDate == '') {
    //     this.$message.error('请选择改派日期');
    //     return false;

    //   }

    //   let params = {
    //     id: this.orderInfo.id,
    //     bookDate: this.reassignForm.bookDate,
    //     bookStartTime: this.reassignForm.startTime,
    //     bookEndTime: this.reassignForm.endTime,
    //     servantId: this.reassignForm.servantId,
    //   };
    //   orderBookReassign(params)
    //     .then((response) => {
    //       this.$message.success("改派成功");
    //       console.log(response);
    //       this.drawerShow = false;
    //       this.$parent.orderBookDetail(this.orderInfo.orderId);
    //     })
    //     .catch((response) => {
    //       this.$notify.error({
    //         title: "失败",
    //         message: response.data.errmsg,
    //       });
    //     });

    // },
    getList() {
      this.tempSkillId = this.listQuery.skillId;
      getCalendarStock({
        detailId: this.listQuery.detailId, 
        month: this.listQuery.month,
        workerName: this.listQuery.worker,
        skillId: this.listQuery.skillId,
        pageSize: this.listQuery.pageSize,
        pageNo: this.listQuery.pageNo,
      })
        .then((response) => {
          console.log(response);
          // this.list = response.data.data.list;
          this.total = response.data.data.total;
          this.dataList = response.data.data.dataList;
          this.dayList = response.data.data.dayList;

          this.listLoading = false;
        })
        .catch((err) => {
          console.log(err);
          this.$message.error(err.data.errmsg);
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    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;
}
 
</style>
