<template>
  <div class="app-container">
    <el-row>
      <el-col :span="10">
        <div id="fatherBox_left">
          <div class="title_box_left">
            <span class="text_left">基 础 信 息</span>
          </div>
          <el-form
            id="froms"
            ref="form"
            :model="form"
            :rules="rules"
            label-width="134px"
            size="small"
          >
            <el-form-item label="检查队列" prop="queueId">
              <el-select
                v-model="form.queueId"
                clearable
                placeholder="请选择检查队列"
                size="small"
                style="width: 60%"
                @change="queueChange"
              >
                <el-option
                  v-for="dict in queueList"
                  :key="dict.id"
                  :label="dict.queueName"
                  :value="dict.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="上午时间" prop="amStartTime">
              <el-time-select
                v-model="form.amStartTime"
                :picker-options="{
                  start: '06:00',
                  step: '00:30',
                  end: '12:00',
                }"
                placeholder="上班时间"
                style="width: 29%"
                @change="onChangeSyncSchedule"
              >
              </el-time-select>
              <el-time-select
                v-model="form.amEndTime"
                :picker-options="{
                  start: '07:00',
                  step: '00:30',
                  end: '12:00',
                  minTime: form.amStartTime,
                }"
                placeholder="下班时间"
                style="width: 30%"
                @change="onChangeSyncSchedule"
              >
              </el-time-select>
            </el-form-item>
            <el-form-item label="下午时间" prop="pmStartTime">
              <el-time-select
                v-model="form.pmStartTime"
                :picker-options="{
                  start: '12:00',
                  step: '00:30',
                  end: '23:30',
                }"
                placeholder="上班时间"
                style="width: 29%"
                @change="onChangeSyncSchedule"
              >
              </el-time-select>
              <el-time-select
                v-model="form.pmEndTime"
                :picker-options="{
                  start: '12:00',
                  step: '00:30',
                  end: '23:30',
                  minTime: form.pmStartTime,
                }"
                placeholder="下班时间"
                style="width: 30%"
                @change="onChangeSyncSchedule"
              >
              </el-time-select>
            </el-form-item>
            <el-form-item label="单个时段时长" prop="singleTimeCount">
              <el-col :span="12">
                <el-select
                  v-model="form.singleTimeCount"
                  clearable
                  placeholder="请选时段"
                  style="width: 100%"
                  @change="onChangeSyncSchedule"
                >
                  <el-option
                    v-for="item in timeList"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-col>
              <el-col :span="1" style="width: 100px; margin-left: 10px">
                分钟
              </el-col>
            </el-form-item>
            <el-form-item label="单个检查时长" prop="singleCheckCount">
              <el-col :span="12">
                <el-input-number
                  v-model="form.singleCheckCount"
                  :min="1"
                  placeholder="请输入单个检查时长"
                  style="width: 100%"
                  @change="onChangeSyncSchedule"
                />
              </el-col>
              <el-col :span="1" style="width: 100px; margin-left: 10px">
                分钟
              </el-col>
            </el-form-item>
            <el-form-item label="上午设备数量" prop="amDeviceCount">
              <el-col :span="12">
                <el-input-number
                  v-model="form.amDeviceCount"
                  :min="0"
                  placeholder="请输入上午设备数量"
                  style="width: 100%"
                  @change="onChangeSyncSchedule"
                />
              </el-col>
              <el-col :span="1" style="width: 100px; margin-left: 10px">台</el-col>
            </el-form-item>
            <el-form-item label="下午设备数量" prop="pmDeviceCount">
              <el-col :span="12">
                <el-input-number
                  v-model="form.pmDeviceCount"
                  :min="0"
                  placeholder="请输入下午设备数量"
                  style="width: 100%"
                  @change="onChangeSyncSchedule"
                />
              </el-col>
              <el-col :span="1" style="width: 100px; margin-left: 10px">台</el-col>
            </el-form-item>
            <el-form-item label="号源生成天数" prop="produceDays">
              <el-col :span="12">
                <el-input-number
                  v-model="form.produceDays"
                  :min="0"
                  placeholder="请输入号源生成天数"
                  style="width: 100%"
                />
              </el-col>
              <el-col :span="1" style="width: 100px; margin-left: 10px">天</el-col>
            </el-form-item>
            <el-form-item label="上午住院比例" prop="amInRatio">
              <el-col :span="12">
                <el-input-number
                  v-model="form.amInRatio"
                  :max="100" :min="0"
                  :precision="0" :step="10" style="width: 100%"
                  @change="onChangeSyncSchedule"
                />
              </el-col>
              <el-col :span="1" style="width: 100px; margin-left: 10px">%</el-col>
            </el-form-item>
            <el-form-item label="下午住院比例" prop="pmInRatio">
              <el-col :span="12">
                <el-input-number
                  v-model="form.pmInRatio"
                  :max="100" :min="0"
                  :precision="0" :step="10" style="width: 100%"
                  @change="onChangeSyncSchedule"
                />
              </el-col>
              <el-col :span="1" style="width: 100px; margin-left: 10px">%</el-col>
            </el-form-item>
            <el-form-item label="空腹号源比例" prop="emptyStomachRatio">
              <el-col :span="12">
                <el-input
                  v-model="form.emptyStomachRatio"
                  placeholder="该项为必填项"
                />
              </el-col>
              <el-col :span="1" style="width: 100px; margin-left: 10px">%</el-col>
            </el-form-item>
            <el-form-item label="空腹时间限制" prop="emptyStomachTime">
              <el-col :span="12">
                <el-time-picker
                  v-model="form.emptyStomachTime"
                  format="HH:mm"
                  placeholder="请选择时间"
                  style="width: 100%"
                  value-format="HH:mm"
                />
              </el-col>
              <el-col :span="1" style="width: 100px; margin-left: 10px">之前</el-col>
            </el-form-item>
            <el-form-item label="预约项目时间间隔" prop="intervalTime">
              <el-col :span="12">
                <el-input-number
                  v-model="form.intervalTime" :max="100"
                  :min="0" :precision="0" :step="10"
                  style="width: 100%"
                />
              </el-col>
              <el-col :span="1" style="width: 100px; margin-left: 10px">分钟</el-col>
            </el-form-item>
            <el-form-item label="号表说明" prop="remarks">
              <el-input
                v-model="form.remarks"
                :autosize="{ minRows: 2}"
                placeholder="请输入备注"
                style="width: 60%"
                type="textarea"
              />
            </el-form-item>
          </el-form>
          <div class="dialog-footers">
            <el-button type="primary" @click="submitForm">保存排班模板</el-button>
            <el-button @click="cancel">重 置</el-button>
          </div>
        </div>
      </el-col>
      <el-col :span="14">
        <div class="doublebox_right">
          <div class="title_box_right">
            <span class="text_right">详 细 排 班</span>
          </div>
          <!--          <div id="fatherBox_right" style="padding: 0 15px">
                      <div class="box_right_childen">
                        <el-checkbox
                          :indeterminate="isIndeterminate"
                          v-model="checkAll"
                          @change="handleCheckAllChange"
                        >全选(生成排班模板)
                        </el-checkbox>

                        <div style="padding: 10px 0"></div>
                        <el-checkbox-group
                          v-model="checkedSchedule"
                          @change="handleCheckedCitiesChange"
                        >
                          <el-checkbox v-for="city in scheduleOptions" :label="city" :key="city">{{ city }}</el-checkbox>
                          <el-tooltip placement="top" content="同步第一天的排班到其它日期" effect="light">
                            <el-button style="margin-left: 30px" size="mini" type="primary" @click="scheduleSync">排班同步</el-button>
                          </el-tooltip>
                        </el-checkbox-group>
                      </div>
                    </div>-->
          <!--          <schedule-edit :schedule-list="scheduleList"/>-->
          <ScheduleManage ref="scheduleManage" v-model="checkWeekFrame" :schedule-list="scheduleList"/>
        </div>
      </el-col>
    </el-row>
    <el-row></el-row>
  </div>
</template>
<style scoped>
.dialog-footers {
  padding: 10px;
  text-align: center;
  margin-right: 100px;
}

.doublebox_right {
  min-height: 607px;
  border: 0.3px solid #c0c0c0;
}

.title_box_right {
  height: 40px;
  background: hsla(216, 39%, 76%, 0.849);
  margin-bottom: 15px;
  color: #ffffff;
}

.title_box_left {
  height: 40px;
  background: hsla(216, 39%, 76%, 0.849);
  margin-bottom: 15px;
  color: #ffffff;
}

.title_box_left {
  line-height: 40px;
  padding-left: 15px;
}

.title_box_right {
  line-height: 40px;
  padding-left: 15px;
}

#fatherBox_left {
  border: 1px solid #c0c0c0;
  margin-right: 10px;
}

.right_liner {
  border: 0.3px solid #c0c0c0;
  background: #f7f7f8;
  display: flex;
  flex-direction: row;
  line-height: 45px;
}

.text_box_left {
  width: 30px;
  height: 45px;
  line-height: 45px;
  border-right: 1px solid #c0c0c0;
}

.text_box_right {
  width: 10px;
  height: 45px;
  line-height: 45px;
  margin-left: 310px;
  border-left: 1px solid #c0c0c0;
}

.spanbox {
  margin-left: 20px;
}

.box_right_childen {
  height: auto;
  overflow: auto;
}

#fatherBox_left {
  border: 1px solid #c0c0c0;
}

#froms {
  padding-right: 20px;
}

#fatherBox_right {
  height: auto;
}
</style>

<script>
import ScheduleManage from '@/views/resource/addNumTable/components/ScheduleManage'
// 常用星期
const weekOptions = [
  '星期一',
  '星期二',
  '星期三',
  '星期四',
  '星期五',
  '星期六',
  '星期日'
]
const scheduleOptions = [
  '星期一',
  '星期二',
  '星期三',
  '星期四',
  '星期五',
  '星期六',
  '星期日'
]
// 默认选中所有星期上下午
const defaultWeekFrame = [
  '1-am', '2-am', '3-am', '4-am', '5-am', '6-am', '7-am',
  '1-pm', '2-pm', '3-pm', '4-pm', '5-pm', '6-pm', '7-pm'
]
// 表单默认值
const formDefault = {
  id: null,  // 队列设置ID
  queueId: null,  // 队列ID
  amStartTime: '08:30',
  amEndTime: null,
  pmStartTime: '14:00',
  pmEndTime: null,
  singleTimeCount: 30, // 单个时段时长
  singleCheckCount: 1, // 单个检查时长
  remarks: '',
  amDeviceCount: 1, // 上午设备数量
  pmDeviceCount: 1, // 下午设备数量
  produceDays: 7,   // 号源生成天数
  amInRatio: 30,    // 上午住院比例
  pmInRatio: 70,    // 下午住院比例
  emptyStomachRatio: 30,
  intervalTime: 20,
  emptyStomachTime: '11:00'
}
import { addQueueBasicNum, listAllQueueBasicNum, resetQueueBasicNum } from '@/api/resource/queueBasicNum'
import { listVisitType } from '@/api/basis/visitType'
import { listQueue } from '@/api/resource/queue'
import {
  listQueueSet,
  getQueueSet,
  delQueueSet,
  addQueueSet,
  updateQueueSet,
  exportQueueSet,
  generateSchedule, getQueueSetByQueueId
} from '@/api/resource/queueSet'
import SourceModel from '@/components/SourceNumWeek/index'
import ScheduleEdit from '@/views/resource/addNumTable/components/ScheduleEdit'

export default {
  name: 'AddNumTable',
  components: {
    ScheduleManage,
    ScheduleEdit,
    'source-model': SourceModel
  },
  data() {
    return {
      checkAll: false,
      checkedSchedule: [
        /*"星期一",
        "星期二",
        "星期三",
        "星期四",
        "星期五",
        "星期六",
        "星期日",*/
      ],
      // 排班列表数据
      scheduleList: [],
      checkWeekFrame: defaultWeekFrame,
      // 排版星期字典
      scheduleOptions: scheduleOptions,
      isIndeterminate: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 队列设置表格数据
      queueList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 预约成功短信通知，0为不通知，1为通知。字典
      isReserveMsgOptions: [],
      // 自动取消预约短信通知，0为不通知，1 为通知。字典
      isAutoCancelMsgOptions: [],
      // 手动取消预约短信通知，0为不通知，1为通知。字典
      isArtificalCancelMsgOptions: [],
      // 强制取消预约短信通知，0为不通知，1为通知。字典
      isForcedCancelMsgOptions: [],
      // 改约短信通知，0为不通知，1为通知。字典
      isChangeMsgOptions: [],
      isUsedOptions: [],
      // 检查类型
      Examtypes: [],
      checked: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        queueId: null,
        visitTypeId: null,
        isUsed: null
      },
      // 表单参数
      form: formDefault,
      timeList: [30, 60, 90, 120],
      //就诊类型
      vtList: [],
      // 表单校验
      rules: {
        queueId: [{ required: true, message: '队列不能为空', trigger: 'blur' }],
        amStartTime: [{ required: true, message: '上午开始时间不能为空', trigger: 'blur' }],
        amEndTime: [{ required: true, message: '上午结束时间不能为空', trigger: 'blur' }],
        pmStartTime: [{ required: true, message: '下午开始时间不能为空', trigger: 'blur' }],
        pmEndTime: [{ required: true, message: '下午结束时间不能为空', trigger: 'blur' }],
        singleTimeCount: [{ required: true, message: '单个时段时长不能为空', trigger: 'blur' }],
        singleCheckCount: [{ required: true, message: '单个检查时长不能为空', trigger: 'blur' }],
        amDeviceCount: [{ required: true, message: '上午设备数量不能为空', trigger: 'blur' }],
        pmDeviceCount: [{ required: true, message: '下午设备数量不能为空', trigger: 'blur' }],
        produceDays: [{ required: true, message: '号源生成天数不能为空', trigger: 'blur' }],
        amInRatio: [{ required: true, message: '上午住院比例不能为空', trigger: 'blur' }],
        pmInRatio: [{ required: true, message: '下午住院比例不能为空', trigger: 'blur' }],
        emptyStomachTime: [{ required: true, message: '空腹时间限制不能为空', trigger: 'blur' }],
        intervalTime: [{ required: true, message: '项目间隔时间不能为空', trigger: 'blur' }],
        emptyStomachRatio: [{ required: true, message: '空腹号源比例不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getQueueList()
    this.getVtList()

    this.getDicts('notice_status').then((response) => {
      this.isReserveMsgOptions = response.data
    })
    this.getDicts('notice_status').then((response) => {
      this.isAutoCancelMsgOptions = response.data
    })
    this.getDicts('notice_status').then((response) => {
      this.isArtificalCancelMsgOptions = response.data
    })
    this.getDicts('notice_status').then((response) => {
      this.isForcedCancelMsgOptions = response.data
    })
    this.getDicts('notice_status').then((response) => {
      this.isChangeMsgOptions = response.data
    })
    this.getDicts('sys_yes_no').then((response) => {
      this.isUsedOptions = response.data
    })
    if (this.$route.query && this.$route.query.queueId) {
      let queueId = parseInt(this.$route.query.queueId)
      this.form.queueId = queueId
      this.queueChange(queueId)
    }
  },
  methods: {
    handleCheckAllChange(val) {
      if (val) {
        this.syncSchedule(scheduleOptions)
      } else {
        this.syncSchedule([])
      }
      this.checkedSchedule = val ? scheduleOptions : []
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange(value) {
      this.syncSchedule(value)
      let checkedCount = value.length
      this.checkAll = checkedCount === this.scheduleOptions.length
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.scheduleOptions.length
    },
    /** 查询就诊类型列表 */
    getVtList() {
      listVisitType(this.queryParams).then((response) => {
        this.vtList = response.rows
      })
    },
    changeVisitType(val) {
      let name = ''
      for (var i = 0; i < val.length; i++) {
        this.vtList.forEach((item) => {
          if (item.typeName == val[i]) {
            if (i < val.length - 1) {
              name += item.typeCode + ','
            } else {
              name += item.typeCode
            }
          }
        })
      }
      this.form.visitTypeId = name
      console.log(this.form.visitTypeId)
    },
    getQueueList() {
      listQueue().then((res) => {
        this.queueList = res.rows
      })
    },
    // 取消按钮
    cancel() {
      if (this.form.queueId){
        this.queueChange(this.form.queueId)
      }else {
        this.form = formDefault
        this.checkWeekFrame = defaultWeekFrame
        this.scheduleList = []
      }
    },
    // 队列选择事件,切换正在修改的队列,并回显数据
    queueChange(val) {
      if (val) {
        getQueueSetByQueueId(val).then(({ code, data }) => {
          if (code === 200 && data) {
            this.form = {
              id: data.id,
              queueId: val,
              amStartTime: data.amStartTime,
              amEndTime: data.amEndTime,
              pmStartTime: data.pmStartTime,
              pmEndTime: data.pmEndTime,
              singleTimeCount: data.singleTimeCount,
              singleCheckCount: data.singleCheckCount,
              remarks: data.remarks,
              amDeviceCount: data.amDeviceCount,
              pmDeviceCount: data.pmDeviceCount,
              produceDays: data.produceDays,
              amInRatio: data.amInRatio,
              pmInRatio: data.pmInRatio,
              emptyStomachRatio: data.emptyStomachRatio,
              intervalTime: data.intervalTime,
              emptyStomachTime: data.emptyStomachTime
            }
            // 加载排班信息
            this.initSchedule(data)
          } else {
            // 没有队列设置意味着是添加,只需要保留队列ID
            this.form = {
              ...formDefault,
              queueId: this.form.queueId
            }
            this.checkWeekFrame = defaultWeekFrame
            this.scheduleList = []
          }
        })
      } else {
        this.form = formDefault
        this.checkWeekFrame = defaultWeekFrame
        this.scheduleList = []
      }
      this.$refs['scheduleManage'].clearWarns()
    },
    // 切换排班后查询重置排班信息
    initSchedule(data) {
      const { scheduleTime,scheduleList } = data
      if (scheduleTime && scheduleTime.length > 0){
        this.checkWeekFrame = scheduleTime.split(',')
      }else {
        this.checkWeekFrame = []
      }
      if (scheduleList && scheduleList.length > 0){
        const list = JSON.parse(scheduleList)
        this.scheduleList = list
      }else {
        this.scheduleList = []
      }
    },
    // 表单修改时同步方法
    onChangeSyncSchedule() {
      // 先判断必须参数是否已经设置
      const {
        amStartTime,
        amEndTime,
        pmStartTime,
        pmEndTime,
        singleTimeCount,
        singleCheckCount,
        amDeviceCount,
        pmDeviceCount,
        amInRatio,
        pmInRatio
      } = this.form
      if (amStartTime && amEndTime && pmStartTime && pmEndTime && singleTimeCount &&
        singleCheckCount && amDeviceCount && pmDeviceCount && amInRatio && pmInRatio) {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.syncSchedule()
            this.$message.info('模板已重置')
            this.$refs['scheduleManage'].clearWarns()
          }
        })
      }
    },
    /** 开始排班,右侧生成模拟排班数据 */
    submitForm() {
      this.$confirm('保存排班会重置号表详情,请稍后重新设置!', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(_ => {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            if (this.scheduleList.length === 0) {
              this.$message({ showClose: true, message: '请先生成号源排班信息', type: 'warning' })
            } else {
              for (let i = 0; i < this.scheduleList.length; i++) {
                if (parseInt(this.scheduleList[i].sourceCount) !== (parseInt(this.scheduleList[i].inSingleSourceCount)
                  + parseInt(this.scheduleList[i].outSingleSourceCount) + parseInt(this.scheduleList[i].phySingleSourceCount))) {
                  this.$message({
                    showClose: true,
                    message: `${this.scheduleList[i].startTime}-${this.scheduleList[i].endTime} 时段设置号源的总数不等于总号源数`,
                    type: 'warning'
                  })
                  return
                }
              }
              if (this.form.id) {
                // 有queueSetId执行修改
                updateQueueSet({
                  ...this.form,
                  scheduleTime: (this.checkWeekFrame && this.checkWeekFrame.length > 0) ? this.checkWeekFrame.join(',') : '',
                  scheduleList: JSON.stringify(this.scheduleList)
                }).then(({ code }) => {
                  if (code === 200) {
                    resetQueueBasicNum({
                      queueId: this.form.queueId,
                      queueSetId: this.form.id
                    }).then(res => {
                      if (res.code === 200) {
                        this.$message({ showClose: true, message: '保存成功', type: 'success' })
                      }
                    })
                  } else {
                    this.$message({ showClose: true, message: '保存排班配置错误', type: 'error' })
                  }
                })
              } else {
                // 添加的时候默认给短信策略
                addQueueSet({
                  ...this.form,
                  scheduleTime: (this.checkWeekFrame && this.checkWeekFrame.length > 0) ? this.checkWeekFrame.join(',') : '',
                  scheduleList: JSON.stringify(this.scheduleList),
                  isReserveMsg: 1,
                  isAutoCancelMsg: 1,
                  isArtificalCancelMsg: 1,
                  isForcedCancelMsg: 1,
                  isChangeMsg: 1
                }).then(({ code, data }) => {
                  if (code === 200) {
                    resetQueueBasicNum({
                      queueId: this.form.queueId,
                      queueSetId: data
                    }).then(res => {
                      if (res.code === 200) {
                        this.$message({ showClose: true, message: '保存成功', type: 'success' })
                      }
                    })
                  } else {
                    this.$message({ showClose: true, message: '保存排班配置错误', type: 'error' })
                  }
                })
              }
            }
          }
        })
      })

    },
    /**
     * 获取时间段
     * @param start  开始时段     08:00
     * @param end    结束时段     11:30
     * @param step   时段长度     30 分钟
     * @param single 单个检查时长  1分钟
     */
    getTimeBucket(start, end, step, single) {
      // 每分钟毫秒数
      let stepMilliseconds = 1000 * 60
      // 预设开始时间,结束时间
      let startTime = new Date(`2022-01-01 ${start}`)
      let endTime = new Date(`2022-01-01 ${end}`)
      // 计算相隔分钟数
      let segregate = parseInt(parseInt(endTime.getTime() - startTime.getTime() + '') / stepMilliseconds + '')
      // 计算分隔了多少个时段
      let length = parseInt(segregate / step + '')
      // 计算剩余不完整时段
      let incomplete = parseInt(segregate % step + '')
      // 定义时段数组
      let arr = []
      // 正常单个时段号源数量(无设备数计算)
      let singleCount = parseInt(step / single + '')
      for (let i = 0; i < length; i++) {
        let startStr = this.formatDate(startTime).substring(11, 16)
        startTime.setTime(startTime.getTime() + step * stepMilliseconds)
        let endStr = this.formatDate(startTime).substring(11, 16)
        arr.push({ startTime: startStr, endTime: endStr, count: singleCount })
      }
      if (incomplete > 0) {
        let startStr = this.formatDate(startTime).substring(11, 16)
        startTime.setTime(startTime.getTime() + incomplete * stepMilliseconds)
        let endStr = this.formatDate(startTime).substring(11, 16)
        arr.push({ startTime: startStr, endTime: endStr, count: parseInt(stepMilliseconds / single + '') })
      }
      return arr
    },
    formatDate(date) {
      let year = date.getFullYear()
      let month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      let day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      let hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      let minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      let seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
    },
    // 排班table同步
    syncSchedule() {
      const {
        amStartTime,
        amEndTime,
        pmStartTime,
        pmEndTime,
        singleTimeCount,
        singleCheckCount,
        amDeviceCount,
        pmDeviceCount,
        amInRatio,
        pmInRatio
      } = this.form
      // 上午时段数据生成
      const amBucket = this.getTimeBucket(amStartTime, amEndTime, singleTimeCount, singleCheckCount)
      // 下午时段数据生成
      const pmBucket = this.getTimeBucket(pmStartTime, pmEndTime, singleTimeCount, singleCheckCount)
      // 列表数据生成
      let tempList = []
      amBucket.forEach(item => {
        let sourceCount = parseInt(item.count * amDeviceCount + '')
        let inSingleSourceCount = parseInt(sourceCount * amInRatio / 100 + '')
        tempList.push({
          timeFrame: '上午',
          startTime: item.startTime,
          endTime: item.endTime,
          sourceCount,
          inSingleSourceCount,
          outSingleSourceCount: parseInt(sourceCount - inSingleSourceCount + ''),
          phySingleSourceCount: 0
        })
      })
      pmBucket.forEach(item => {
        let sourceCount = parseInt(item.count * pmDeviceCount + '')
        let inSingleSourceCount = parseInt(sourceCount * pmInRatio / 100 + '')
        tempList.push({
          timeFrame: '下午',
          startTime: item.startTime,
          endTime: item.endTime,
          sourceCount,
          inSingleSourceCount,
          outSingleSourceCount: parseInt(sourceCount - inSingleSourceCount + ''),
          phySingleSourceCount: 0
        })
      })
      this.scheduleList = tempList
    },
    // 计算天添加的起始下标
    getAddIndex(arr = [], week) {
      const size = scheduleOptions.indexOf(week)
      for (let i = 0; i < arr.length; i++) {
        if (size < scheduleOptions.indexOf(arr[i].week)) {
          return i
        }
      }
      return arr.length
    },
    // 获取数组中最后一个匹配的值的下标
    getLastIndex(arr = [], predicate) {
      for (let i = arr.length - 1; i >= 0; i--) {
        if (predicate(arr[i])) {
          return i
        }
      }
      return -1
    },
    // 同步第一天的排班到其它星期
    scheduleSync() {
      if (this.scheduleList.length === 0) {
        return
      }
      if (this.checkedSchedule.length <= 1) {
        return
      }
      // 先拿出第一天的模板排班
      let firstWeek = this.scheduleList[0].week
      let firstScheduleList = this.scheduleList.filter(item => (!item.flag && !item.blankLine) && item.week === firstWeek)
      let i = 0  // 存放下标
      this.scheduleList.forEach((value, index) => {
        if (value.week !== firstWeek) {
          if (!value.flag && !value.blankLine) {
            if (i === firstScheduleList.length) {
              i = 0  // 下标归零
            }
            this.scheduleList.splice(index, 1, {
              ...value,
              mz: firstScheduleList[i].mz,
              zy: firstScheduleList[i].zy,
              tj: firstScheduleList[i].tj,
              jz: firstScheduleList[i].jz,
              wx: firstScheduleList[i].wx
            })
            i++
          }
        }
      })
    }
  }
}
</script>
<style scoped>
.tip {
  padding: 8px 16px;
  background-color: #ecf8ff;
  border-radius: 4px;
  border-left: 5px solid #50bfff;
  margin: 20px 0;
}
</style>
