<template>
  <div class="app-container" style="font-size:14px">
      <p >设置服务人员 <b>{{$route.query.serverName}}</b> 的服务时间，在服务时间内允许顾客预约他/她的服务。</p>

    <el-row :gutter="20">
      <el-col :span="24">
        <el-card>
            停止接单：
            <el-switch
                v-model="params.stopOrder">
            </el-switch>
            <div class="tip">
                开启后，将不再接预约单
            </div>
        </el-card>
      </el-col>
      <br />

      <el-col :span="24">
        <el-card>
          接单间隔时长：
          <el-select v-model="params.serverGrap" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
          <div class="tip">
              上一个订单服务完成，到下一个订单之间的间隔时长（预留路上的时间）。<br/>
              系统会计算上个订单服务时间+间隔时长，来判断下个订单允许的预约时间。
          </div>
        </el-card>
      </el-col>

      <el-col>
        <el-card v-for="(item, index) in items">
          <!--            //如果true true 或者 true false样式为- -->
          <!--            如果false true样式为√-->
          <!--            如果false false样式为不勾-->
          <el-row style="margin-bottom: 20px">

              <el-checkbox
                :indeterminate="item.isIndeterminate"
                v-model="item.checkAll"
                @change="(val) => handleCheckAllChange(val, item)"
                ><b>每天</b></el-checkbox
            >
            <el-checkbox-group
                style="display:inline-block;margin-left:20px"
                v-model="item.weeks"
                @change="handleCheckedCitiesChange(item)"
            >
                <el-checkbox
                v-for="(Day, index) in DaysOptions"
                :label="Day.value"
                :key="Day.name"
                >{{ Day.day }}</el-checkbox
                >
            </el-checkbox-group>
            <el-checkbox
                v-for="(item, index) in items.weeks"
                v-model="item.checked"
            >
                //v-model绑定到每个item的checked属性
                {{ item.name }}
            </el-checkbox>
          </el-row>

          <el-time-select
            v-model="item.hoursFromString"
            :picker-options="{
              step: '00:30',
              start: '00:00',
              end: '23:59',
            }"
            placeholder="起始时间"
          >
          </el-time-select>
            <span style="margin: 0 10px">至</span>
          <el-time-select
            v-model="item.hoursEndString"
            :picker-options="{
              start: '00:00',
              step: '00:30',
              end: '23:59',
            }"
            placeholder="结束时间"
          >
          </el-time-select>
          <el-button
            @click="delInfo(item, index)"
            size="small"
            style="color: red;margin-left:50px"
            >删除</el-button
          >
        </el-card>
      </el-col>
      <!--        <el-col>-->
      <!--            <add-index-->
      <!--              ref="children"-->
      <!--              v-for="(item,index) in items"-->
      <!--              :key="index"-->
      <!--              :index="index"-->
      <!--              :items="items"-->
      <!--              :serverTimeList="serverTimeList "-->
      <!--              @deleteIndex="del"-->
      <!--              @handleCheckedCitiesChange="updateWeeks"-->

      <!--            >-->
      <!--            </add-index>-->
      <!--        </el-col>-->
    </el-row>

    <el-row>
      <el-col style="text-align:center;">
        <el-button @click="addMore">+ 再添加一个时间</el-button>
      </el-col>
    </el-row>
    <br />
    <br />
    <el-row>
      <el-col>
        <el-checkbox v-model="params.allowEdit"
          >允许此服务人员自己修改服务时间</el-checkbox
        >
      </el-col>
      <el-col  style="text-align:center;margin-top: 20px">
        <el-button type="primary" @click="UDateServerTime">保存</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import AddIndex from "./addIndex";
import moment from 'moment'
import {
  getTime,
  listTime,
  updateTime,
  editNew,
  getServerTimeInfo,
} from "../../../api/system/serverTime";
import {
  delSection,
  listSection,
  updateSection,
  addSection,
} from "../../../api/system/serverTimeSection";
export default {
  name: "index",
  components: { AddIndex },
  data() {
    return {
      value1: true,
      options: [
        {
          value: "选项1",
          label: "0.5",
        },
        {
          value: "选项2",
          label: "1.0",
        },
        {
          value: "选项3",
          label: "1.5",
        },
        {
          value: "选项4",
          label: "2.0",
        },
        {
          value: "选项5",
          label: "2.5",
        },
        {
          value: "选项6",
          label: "3.0",
        },
        {
          value: "选项7",
          label: "3.5",
        },
        {
          value: "选项8",
          label: "4.0",
        },
      ],
      Days: [
        {
          day: "周日",
          index: "0",
          checked: false,
        },
        {
          day: "周一",
          index: "1",
          checked: false,
        },
        {
          day: "周二",
          index: "2",
          checked: false,
        },
        {
          day: "周三",
          index: "3",
          checked: false,
        },
        {
          day: "周四",
          index: "4",
          checked: false,
        },
        {
          day: "周五",
          index: "5",
          checked: false,
        },
        {
          day: "周六",
          index: "6",
          checked: false,
        },
      ],
      DaysOptionsValue: ["0", "1", "2", "3", "4", "5", "6"],
      weekName: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
      DaysOptions: [
        {
          day: "周日",
          index: "0",
          value: "0",
        },
        {
          day: "周一",
          index: "1",
          value: "1",
        },
        {
          day: "周二",
          index: "2",
          value: "2",
        },
        {
          day: "周三",
          index: "3",
          value: "3",
        },
        {
          day: "周四",
          index: "4",
          value: "4",
        },
        {
          day: "周五",
          index: "5",
          value: "5",
        },
        {
          day: "周六",
          index: "6",
          value: "6",
        },
      ],
      checkAll: false,
      isIndeterminate: true,
      items: [{}],
      dataRec: [],
      checkedDays: [],
      params: {
        serverId: "",
        hoursFromString: null,
        hoursEndString: null,
        weeks: "",
        sectionId: "",
        serverGrap: "",
        allowEdit: "", //不允许自己修改时间
        stopOrder: false, //0表示正常接单
        isEnable: "", //0表示不启用
        step: "",
        merchantId: "",
      },
      serverTimeList: [],
      checked: true,
      param: {},
    };
  },
  created() {
    this.params.serverId = this.$route.query.serverId;
    this.getInfo();
    // this.getServerTime();
    this.del();
  },
  methods: {
    delInfo(item, index) {
      this.items.splice(index, 1);
    },
    getInfo() {
      getServerTimeInfo({ serverId: this.params.serverId }).then((res) => {
        if (res.data != null && res.data != undefined) {
          if (res.data.stopOrder == 1) {
            res.data.stopOrder = true;
          } else {
            res.data.stopOrder = false;
          }
          if (res.data.allowEdit == 1) {
            res.data.allowEdit = true;
          } else {
            res.data.allowEdit = false;
          }

          this.items = res.data.sectionList;
          res.data.sectionList.forEach((item) => {
            item.hoursFromString = moment(item.hoursFrom, 'HH:mm').format('HH:mm');
            item.hoursEndString = moment(item.hoursEnd, 'HH:mm').format('HH:mm');
            if (
              item.weeks != undefined &&
              item.weeks != null &&
              item.weeks != ""
            ) {
              item.weeks = item.weeks.split(",");
            }
            this.handleCheckedCitiesChange(item);
          });
          this.params = res.data;
        }
      });
    },
    // getServerTime(){
    //   listTime(this.params).then(res=>{
    //     this.serverTimeList=res.rows;
    //     //默认填充第一条服务时间 记录，如果有记录
    //     if(this.serverTimeList.length>0){
    //       let list =this.serverTimeList[0].weeks.split(',')
    //
    // if(this.serverTimeList[0].hoursEndString!==null){
    // 	this.params.hoursEndString=this.serverTimeList[0].hoursEndString;
    // }
    // else{
    // 	this.params.hoursEndString='00:00:00';
    // }
    // if(this.serverTimeList[0].hoursFromString!==null){
    // 	  this.params.hoursFromString=this.serverTimeList[0].hoursFromString;
    // }
    // else{
    // 	this.params.hoursFromString='24:00:00';
    // }
    //
    //       this.params.sectionId=this.serverTimeList[0].sectionId
    //       this.params.serverGrap=this.serverTimeList[0].serverGrap
    //      //初始化工作日
    //       for(let i in list){
    //         for(let index in this.Days){
    //           if(list[i]==this.Days[index].index){
    //             this.checkedDays.push(this.Days[index].day)
    //             this.Days[index].checked=true;
    //           }
    //           if(res.total==1){
    //             this.Days[index].checked=true;
    //           }
    //         }
    //       }
    //
    //       for(let i=1;i<this.serverTimeList.length;i++){
    //         if(this.items.length+1<this.serverTimeList.length){
    //           this.add()
    //         }
    //
    //       }
    //     }
    // else if(this.serverTimeList.length==0){
    // 	for(let i in this. Days){
    // 		this.Days[i].checked=true;
    // 	}
    // 	this.params.hoursEndString='24:00:00';
    // 	this.params.hoursFromString='00:00:00';
    // }
    //   })
    // },
    UDateServerTime() {
      const {items, params} = this
      // 1. 非空校验
      if (!items || items.length == 0) {
        this.$message.warning("至少添加一条时间");
        return
      }
      if (!params.serverGrap) {
        this.$message.warning("接单间隔时长不能为空");
        return
      }

      // 2. 时间正确性校验
      const weekTimes = []
      let count = 1
      for(const {weeks, hoursFromString, hoursEndString} of items){
        const index = count++
        if (!weeks || weeks.length === 0 || !hoursFromString || !hoursEndString) {
          this.$message.warning(`第${index}条日期和时间范围不能为空`);
          return
        }
        const start = moment(hoursFromString, 'HH:mm')
        const end = moment(hoursEndString, 'HH:mm')
        if (start.isSameOrAfter(end)) {
          this.$message.warning(`第${index}条结束时间必须大于起始时间`);
          return
        }
        weeks.forEach(week => {
          weekTimes[week] = [...weekTimes[week] || [], {start, end}]
        })
      }

      // 3. 时间段重复校验(按起始时间排序，判断是否存在重复区间)
      count = 0
      // 周提示信息
      let weekNames = [];
      for(const times of weekTimes){
        const index = count++
        if (!times || times.length === 0) {
          continue
        }
        times.sort((a, b) => a.start.isSameOrAfter(b.start) ? 1: -1)
        let prev = null
        for (const time of times) {
          if (!prev) {
            prev = time
            continue
          }
          if (prev.end.isSameOrAfter(time.start)) {
            weekNames.push(`${this.weekName[index]}`);
          }
        }
      }
      if (weekNames.length > 0) {
        this.$message.warning(weekNames.join("、") + "的时间段不能存在重复区间或连续")
        return
      }

      const param = {
        ...params,
        stopOrder: Number(params.stopOrder),
        sectionList: items.map(({weeks, hoursFromString, hoursEndString}) => ({
          weeks: weeks?.join(','),
          hoursFromString, hoursEndString
        }))
      }
      editNew(param).then((res) => {
        if (res.code == "200") {
          this.$message.success("保存成功");
          this.$router.push("/merchant/servicePeople");
        }
      })
    },
    handleCheckAllChange(val, item) {
      // if(checkFlag){
      item.weeks = val ? this.DaysOptionsValue : [];
      item.isIndeterminate = false;
      // var checkFlag = this.checkCan('1',val,item);
      // }
    },
    handleCheckedCitiesChange(value) {
      let checkedCount;
      // <!--            //如果true true 或者 true false样式为- -->
      // <!--            如果false true样式为√-->
      // <!--            如果false false样式为不勾-->
      checkedCount = value.weeks.length;
      value.checkAll = checkedCount === this.DaysOptions.length;
      value.isIndeterminate =
        checkedCount > 0 && checkedCount < this.DaysOptions.length;
      // 更改时间子组件的工作日
      // this.$refs.children[0].childernUpdateWeeks(value)
      // var checkFlag = this.checkCan('2',value);
    },
    checkCan(funFlag, value, item) {
      var that = this;
      var flag = true;
      if (funFlag == "2" || (funFlag == "1" && value)) {
        var weeksCommon = [];
        that.items.forEach((item) => {
          item.weeks.forEach((itemNew) => {
            if (itemNew != undefined && itemNew != null && itemNew != "") {
              if (weeksCommon.indexOf(itemNew) >= 0) {
                flag = false;
                return false;
              } else {
                weeksCommon.push(itemNew);
              }
            }
          });
        });
        if (!flag) {
          if (funFlag == "2") {
            value.weeks = [];
          }
          if (funFlag == "1") {
            item.weeks = [];
            item.isIndeterminate = false;
            item.checkAll = false;
          }
          this.$message.error("每天只能设定一个时间段");
        }
      }
      return flag;
    },

    //  添加时间组件
    add: function () {
      this.items.push({ index: "" });
    },
    addMore() {
      //长度可以判断是否可以继续添加
      if (this.items.length < 7) {
        this.items.push({ isIndeterminate: false, checkAll: false, weeks: [] });
      } else {
        this.$modal.msgError("该服务人员档期已安排满");
      }

      // let justifyArr=[];
      // listTime(this.params).then(res=>{
      //   let obj=res.rows;
      //   let arr=[];
      //   debugger
      //   for(let i in obj){
      //     arr.push(obj[i].weeks.split(','))
      //   }
      //   for(let index in arr){
      //     for(let j in arr[index]){
      //       justifyArr.push(arr[index][j])
      //     }
      //   }
      //   if(justifyArr.length<7){
      //     this.items.push({index:''})
      //   }
      //   else {
      //     this.$modal.msgError('该服务人员档期已安排满')
      //   }
      //
      // })
    },
    // 删除时间组件
    del: function (index) {
      this.items.splice(index, 1);
      console.log("deleted:", JSON.stringify(this.items));
      if (this.serverTimeList.length > 1) {
        delSection(this.serverTimeList[index + 1].sectionId).then((res) => {});
      }
    },

    //更改工作日
    updateWeeks(val) {
      let arr = [];
      if (val.length >= this.checkedDays.length) {
        for (let i = this.checkedDays.length; i < val.length; i++) {
          for (let index in this.Days) {
            if (val[i] === this.Days[index].day) {
              arr.push(this.Days[index].index);
            }
          }
        }
        for (let index in this.Days) {
          for (let i in this.checkedDays) {
            if (
              this.Days[index].day !== this.checkedDays[i] &&
              this.Days[index].checked === false
            ) {
              this.Days[index].checked = true;
            }
          }
          for (let j in arr) {
            this.Days[arr[j]].checked = false;
          }
        }
      }
    },
  },
};
</script>

<style scoped>
.el-card {
  margin-bottom: 20px;
}
.tip {
    color: #7F7F7F;
    font-size:14px;
    width:600px;
    margin-left:20px;
    display:inline-block;
    line-height:18px;
    vertical-align: middle;
}
</style>
