<template>
  <div>
    <div class="form-content">
      <el-form :model="form" ref="form" :rules="rules" label-width="140px" class="demo-ruleForm" label-position="right" v-loading="loading">
        <div class="form-section">
          <h3>自提点信息</h3>
          <el-form-item label="自提点类型" required>
            <template>
              <el-radio v-model="form.type" :label="1">从门店中选择</el-radio>
            </template>
          </el-form-item>
          <div v-if="integralMallPickUpPointId">
            <el-form-item label="自提点名称">
              <template>
                <el-input v-model="form.name" class="w-600" type="text" disabled></el-input>
              </template>
            </el-form-item>
            <el-form-item label="电话">
              <template>
                <el-input v-model="form.phone" class="w-600" type="text" disabled></el-input>
              </template>
            </el-form-item>
            <el-form-item label="自提点地址">
              <template>
                <el-input v-model="form.address" class="w-600" type="text" disabled></el-input>
              </template>
            </el-form-item>
            <el-form-item label="自提点图片">
              <div v-for="(item, index) in form.pickupUrl" :key="index" class="img-list">
                <img :src="item" alt />
              </div>
            </el-form-item>
            <el-form-item label="营业时间">
              <div v-for="(item, index) in form.businessTimeList" :key="index" class="time-list">
                <el-select v-model="item.weekdayShow" multiple placeholder="请选择" disabled class="mr10">
                  <el-option label="周一" value="周一"></el-option>
                  <el-option label="周二" value="周二"></el-option>
                  <el-option label="周三" value="周三"></el-option>
                  <el-option label="周四" value="周四"></el-option>
                  <el-option label="周五" value="周五"></el-option>
                  <el-option label="周六" value="周六"></el-option>
                  <el-option label="周日" value="周日"></el-option>
                </el-select>
                <el-time-select placeholder="起始时间" v-model="item.openTime" disabled style="width:170px" class="mr10"></el-time-select>
                <span style="font-size:14px;margin-right:10px;">至</span>
                <el-time-select placeholder="起始时间" v-model="item.closeTime" disabled style="width:170px"></el-time-select>
              </div>
            </el-form-item>
          </div>
          <el-form-item v-else>
            <template slot="label">
              <el-tooltip open-delay="200" class="item" effect="dark" content="不筛选则默认所有门店" placement="top">
                <span class="undeline-dash">门店选择</span>
              </el-tooltip>
            </template>
            <div class="store-select-box">
              门店选择器
            </div>
          </el-form-item>
        </div>
        <div class="form-section">
          <h3>自提点设置</h3>
          <el-form-item label="买家可选自提时间" style="margin-bottom:10px;">
            <el-switch v-model="form.openChooseTime"></el-switch>
          </el-form-item>
          <p class="warm-tip">开关开启，则买家需选择自提时间，商户需按约定时间备货完成，反之则默认买家付款后即可在任意时间提货</p>
          <el-form-item label="商户备货设置" required v-if="form.openChooseTime">
            <template>
              <div class="radio-item">
                <el-radio v-model="form.radio" :label="1" @change="handleChange" style="margin-right:10px;">下单当天</el-radio>
                <el-form-item style="display:inline-block;margin-left:0px" prop="timeHours">
                  <el-input type="text" v-model="form.timeHours" style="width:140px;" :disabled="form.radio === 2"></el-input>
                </el-form-item>
                <span>小时</span>
                <el-form-item style="display:inline-block;margin-left:0px" prop="timeMinuter">
                  <el-input type="text" v-model="form.timeMinuter" style="width:140px;" :disabled="form.radio === 2"></el-input>
                </el-form-item>
                <span>分钟后，买家可提货</span>
              </div>
              <div class="radio-item" style="margin-bottom:0px;">
                <el-radio v-model="form.radio" :label="2" @change="handleChange" style="margin-right:10px;">下单</el-radio>
                <el-form-item style="display:inline-block;margin-left:0px" prop="timeDay">
                  <el-input type="text" v-model="form.timeDay" style="width:120px;" :disabled="form.radio === 1"></el-input>
                </el-form-item>
                <span>天后，买家可提货</span>
              </div>
            </template>
          </el-form-item>
          <el-form-item label="买家自提时段" required v-if="form.openChooseTime"></el-form-item>
          <div style="margin-top:-45px;" v-if="form.openChooseTime">
            <el-form-item v-for="(v, i) in form.timeRangeList" :key="i" :prop="'timeRangeList.' + i + '.timeRange'" :rules="[{ validator: validateTime, trigger: 'change' }]" class="form-item">
              <el-time-picker :clearable="clearableBtn" class="w-280" format="HH:mm" is-range v-model="v.timeRange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围" @change="value => limitTimeSelect(i, value)" @focus="value => blurLimitTimeSelect(i, value)"></el-time-picker>
              <el-button v-if="i" type="text" @click="deleteTime(i)" class="delete-btn">删除</el-button>
              <span v-if="!i" class="time-tip">请使用24小时制输入时间，格式如11:00至14:30</span>
            </el-form-item>
            <p>
              <el-button type="text" class="add-time" @click="addTime"> <i class="el-icon-plus"></i>添加时间段 </el-button>
            </p>
          </div>
          <el-form-item style="margin-top:30px;font-size:0">
            <dm-perm-button type="primary" :disabled="$itemPerm($itemCode.GICIntegralUpdatePickUpPoint)" @click="handleSubmit('form')" v-if="integralMallPickUpPointId">保存</dm-perm-button>
            <dm-perm-button type="primary" :disabled="$itemPerm($itemCode.GICIntegralAddPickUpPoint)" @click="handleSubmit('form')" v-else>确认新建</dm-perm-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script>
import fetch from '@/api/gift.js';
const { insertPickupStore, getPickupDetails } = fetch;
import { getSeconds, getHours } from '../../utils/common.js';
export default {
  components: {},
  data() {
    let timeHoursValidator = (rule, value, callback) => {
      // var reg = /^[1-9]\d*$/;
      let reg = /^\+?(0|[1-9][0-9]*)$/;
      if (this.form.radio === 2) {
        if (!value) {
          callback();
        }
      } else if (this.form.radio === 1) {
        if (!value) {
          callback(new Error('请输入时间'));
        }
      }
      if (!reg.test(Number(value))) {
        callback(new Error('请输入0-23之间的整数'));
      } else if (Number(value) > 23) {
        callback(new Error('请输入0-23之间的整数'));
      } else {
        callback();
      }
    };
    let timeMinuterValidator = (rule, value, callback) => {
      // var reg = /^[1-9]\d*$/;
      let reg = /^\+?(0|[1-9][0-9]*)$/;
      if (this.form.radio === 2) {
        if (!value) {
          callback();
        }
      } else if (this.form.radio === 1) {
        if (!value) {
          callback(new Error('请输入时间'));
        }
      }
      if (!reg.test(Number(value))) {
        callback(new Error('请输入0-59之间的整数'));
      } else if (Number(value) > 59) {
        callback(new Error('请输入0-59之间的整数'));
      } else {
        callback();
      }
    };
    let timeDayValidator = (rule, value, callback) => {
      let reg = /^[1-9]\d*$/;
      // var reg = /^\+?(0|[1-9][0-9]*)$/;
      if (this.form.radio === 1) {
        if (!value) {
          callback();
        }
      } else if (this.form.radio === 2) {
        if (!value) {
          callback(new Error('请输入时间'));
        }
      }
      if (!reg.test(Number(value))) {
        callback(new Error('请输入1-90之间的整数'));
      } else if (Number(value) > 90) {
        callback(new Error('请输入1-90之间的整数'));
      } else {
        callback();
      }
    };
    let validateTime = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入时间'));
      } else {
        callback();
      }
    };
    return {
      getSeconds: getSeconds,
      getHours: getHours,
      form: {
        type: 1,
        openChooseTime: true,
        name: '',
        phone: '',
        address: '',
        pickupUrl: [],
        businessTimeList: [],
        radio: 1,
        timeHours: '',
        timeMinuter: '',
        timeDay: '',
        timeRangeList: [ { timeRange: '' } ]
      },
      rules: {
        timeHours: [ { validator: timeHoursValidator, trigger: 'blur' } ],
        timeMinuter: [ { validator: timeMinuterValidator, trigger: 'blur' } ],
        timeDay: [ { validator: timeDayValidator, trigger: 'blur' } ]
        // orderTimeHours: [{ required: true, message: '请输入时间', trigger: 'blur' }, { validator: orderTimeHoursValidator, trigger: 'blur' }]
      },
      validateTime,
      integralMallPickUpPointId: '',
      // 门店选择器
      projectName: 'integral-mall',
      rebackFlag: false,
      selectPeopleObj: '',
      storewidgetId: '',
      loading: false,
      submitLoading: false
    };
  },
  created() {
    this.$emit('updateBread', [  { breadName: '福利中心'  }, { breadName: 'GIC卡券包', breadPath: '/card-package/list' }, { breadName: this.isAdd ? '新建自提点' : '编辑自提点', breadPath: '' } ]);
    this.integralMallPickUpPointId = this.$route.query.integralMallPickUpPointId;
  },
  methods: {
    getMess() {
      let params = {
        id: this.integralMallPickUpPointId
      };
      this.loading = true;
      insertPickupStore(params).then(res => {
        let resResult = res.result;
        this.form.type = resResult.type;
        this.form.name = resResult.name;
        this.form.phone = resResult.phone;
        this.form.address = resResult.address;
        this.form.pickupUrl = resResult.pickupUrl ? JSON.parse(resResult.pickupUrl) : [];
        let businessHour = resResult.businessHour ? JSON.parse(resResult.businessHour) : [];
        for (let item of businessHour) {
          item.weekdayShow = item.weekdayShow.split('、');
          item.openTime = this.getSeconds(item.openTime);
          item.closeTime = this.getSeconds(item.closeTime);
        }
        this.form.businessTimeList = businessHour;
        this.form.openChooseTime = resResult.openChooseTime === 1 ? true : false;
        let goodsSetting = resResult.goodsSetting ? JSON.parse(resResult.goodsSetting) : { setType: 1, time: '' };
        this.form.radio = goodsSetting.setType;
        if (goodsSetting.setType === 1) {
          // time的单位是分钟
          this.form.timeHours = goodsSetting.time / 60 < 1 ? '' : parseInt(goodsSetting.time / 60);
          this.form.timeMinuter = goodsSetting.time % 60 === 0 ? '' : goodsSetting.time % 60;
        } else {
          this.form.timeDay = '';
        }
        if (goodsSetting.setType === 2) {
          // time的单位是天
          this.form.timeDay = goodsSetting.time;
          this.form.timeHours = '';
          this.form.timeMinuter = '';
        }

        if (resResult.openChooseTime === 0) {
          this.form.timeRangeList[0].timeRange = '';
        } else {
          this.form.timeRangeList = [];
          let pickupTime = JSON.parse(resResult.pickupTime);

          for (let item of pickupTime) {
            let currentYear = new Date().getFullYear();
            let currentMonth = new Date().getMonth() + 1;
            let currentDate = new Date().getDate();
            let time1 = new Date(new Date(currentYear + '-' + currentMonth + '-' + currentDate + ' ' + item.split('-')[0] + ':00').valueOf());
            let time2 = new Date(new Date(currentYear + '-' + currentMonth + '-' + currentDate + ' ' + item.split('-')[1] + ':00').valueOf());
            this.form.timeRangeList.push({ timeRange: [ time1, time2 ] });
          }
        }
      })
        .catch(error => {
          this.loading = false;
        });
    },
    // 添加时间段
    addTime() {
      if (this.form.timeRangeList.length >= 5) {
        this.$message.error('最多五个时间段');
        return false;
      }
      if (this.form.timeRangeList[this.form.timeRangeList.length - 1].timeRange) {
        // 上一个时间存在添加
        let time1 = new Date((new Date(this.form.timeRangeList[this.form.timeRangeList.length - 1].timeRange[1]).getTime() + 1000 * 60 * 1).valueOf());
        let time2 = new Date((new Date(this.form.timeRangeList[this.form.timeRangeList.length - 1].timeRange[1]).getTime() + 1000 * 60 * 2).valueOf());
        this.form.timeRangeList.push({ timeRange: [ time1, time2 ] });
      } else {
        this.form.timeRangeList.push({ timeRange: null });
      }
    },
    // 删除时间段
    deleteTime(index) {
      this.form.timeRangeList.splice(index, 1);
    },
    // 时间限制
    limitTimeSelect(index, val) {
      if (val) {
        let selectTime = new Date(val[0]).valueOf();
        let selectTimeEnd = new Date(val[1]).valueOf();
        if (selectTime === selectTimeEnd) {
          this.$message.error('时间不可重叠！');
          this.form.timeRangeList[index].timeRange = null;
        }
        if (index !== 0) {
          // 不是第一个
          // // 和前面的时间比较
          for (let i = index - 1; i >= 0; i--) {
            if (this.form.timeRangeList[i].timeRange) {
              let selectTimePrev = new Date(this.form.timeRangeList[i].timeRange[1]).valueOf();
              // 和前前一个的存在的结束时间比较

              if (selectTime < selectTimePrev) {
                this.$message.error('时间不可重叠！');
                this.form.timeRangeList[index].timeRange = null;
              }
            }
          }
          // 和后面的时间比较
          for (let j = index + 1; j < this.form.timeRangeList.length; j++) {
            if (this.form.timeRangeList[j].timeRange) {
              let selectTimeAfter = new Date(this.form.timeRangeList[j].timeRange[0]).valueOf();
              // 和后一个的存在的开始时间比较
              if (selectTime > selectTimeAfter || selectTimeEnd > selectTimeAfter) {
                this.$message.error('时间不可重叠！');
                this.form.timeRangeList[index].timeRange = null;
              }
            }
          }
        } else {
          // 和后面的时间比较
          for (let j = index + 1; j < this.form.timeRangeList.length; j++) {
            if (this.form.timeRangeList[j].timeRange) {
              let selectTimeAfter = new Date(this.form.timeRangeList[j].timeRange[0]).valueOf();
              // 和后一个的存在的开始时间比较
              if (selectTime > selectTimeAfter || selectTimeEnd > selectTimeAfter) {
                this.$message.error('时间不可重叠！');
                this.form.timeRangeList[index].timeRange = null;
              }
            }
          }
        }
      }
    },
    blurLimitTimeSelect(index, val) {
      let selectTime = new Date(val[0]).valueOf();
      let selectTimeEnd = new Date(val[1]).valueOf();
      if (selectTime === selectTimeEnd) {
        this.$message.error('时间不可重叠！');
        this.form.timeRangeList[index].timeRange = null;
      }
    },
    handleChange() {
      this.$refs['form'].clearValidate();
      if (this.form.radio === 1) {
        this.form.timeDay = '';
      } else if (this.form.radio === 2) {
        this.form.timeHours = '';
        this.form.timeMinuter = '';
      }
    },
    getPeopleId() {
      return;
      // let params = {
      //   authSearchParam: this.selectPeopleObj.dataResource.searchJson ? this.selectPeopleObj.dataResource.searchJson : '',
      //   writeBackParam: JSON.stringify(this.selectPeopleObj.condtionsList),
      //   searchParam: this.selectPeopleObj.abbrInfo
      // };
      // getPickupDetails(params).
      // request
      //   .post('/api-integral-mall/pickup/get-store', params)
      //   .then(res => {
      //     if (res.data.code === '0000') {
      //       this.storewidgetId = res.data.result;
      //     } else {
      //       this.$message.error(res.data.message);
      //     }
      //   })
      //   .catch(error => {
      //     this.$message.error({
      //       duration: 1000,
      //       message: error.message
      //     });
      //   });
    },
    handleSubmit(form) {
      if(this.submitLoading) return;
      this.$refs[form].validate(valid => {
        if (valid) {
          let goodsSetting = { setType: 1, time: '' };
          let pickupTime = [];
          if (this.form.openChooseTime) {
            goodsSetting = {
              setType: this.form.radio,
              time: this.form.radio === 1 ? this.form.timeHours * 60 + Number(this.form.timeMinuter) : this.form.timeDay
            };
            for (let item of this.form.timeRangeList) {
              if (item.timeRange) {
                pickupTime.push(this.getHours(item.timeRange[0]) + '-' + this.getHours(item.timeRange[1]));
              }
            }
          } else {
            goodsSetting = { setType: 1, time: '' };
            pickupTime = [];
          }

          let params = {};
          if (!this.integralMallPickUpPointId) {
            if (!this.selectPeopleObj) {
              this.$message.error('请选择门店');
              return false;
            }
          }

          if (this.integralMallPickUpPointId) {
            // 编辑
            params = {
              id: this.integralMallPickUpPointId,
              openChooseTime: this.form.openChooseTime ? 1 : 0,
              goodsSetting: JSON.stringify(goodsSetting),
              pickupTime: JSON.stringify(pickupTime)
            };
          } else {
            // this.getPeopleId();
            // return;
            params = {
              storewidgetId: this.storewidgetId,
              shopId: this.shopId,
              type: this.form.type,
              openChooseTime: this.form.openChooseTime ? 1 : 0,
              goodsSetting: JSON.stringify(goodsSetting),
              pickupTime: JSON.stringify(pickupTime)
            };
          }
          this.submitLoading = true;
          this.loading = true;
          getPickupDetails(params)
            .then(res => {
              if (res.data.code === '0000') {
                this.$router.push('/setting/pickup-list');
              }
            });
        } else {
          return false;
        }
      });
    }
  },
};
</script>
<style scoped>
.w-600 {
  width: 600px;
}
.form-section {
  margin-bottom: 20px;
  padding: 30px 20px;
}
.form-section h3 {
  color: #303133;
  font-weight: 500;
  font-size: 14px;
  margin-bottom: 20px;
}
.warm-tip {
  color: #909399;
  font-size: 12px;
  margin-bottom: 20px;
}
.radio-item {
  margin-bottom: 20px;
}
.add-time {
  color: #606266;
  margin-left: 140px;
}
.delete-btn {
  display: none;
  color: #909399;
  margin-left: 7px;
}
.delete-btn:hover {
  color: #2f54ed;
}
.form-item:hover .delete-btn {
  display: inline-block;
}
.add-time .el-icon-plus {
  margin-right: 5px;
}
.time-tip {
  color: #909399;
  font-size: 12px;
  margin-left: 7px;
}
.fixed-btn {
  width: 100%;
  height: 56px;
  line-height: 56px;
  position: fixed;
  bottom: 0px;
  left: 200px;
  background: #fff;
  border-top: 1px solid #e4e7ed;
  text-align: center;
  margin-left: -100px;
  z-index: 2;
}
.img-list {
  display: inline-block;
  margin-right: 10px;
  vertical-align: top;
}
.img-list img {
  width: 110px;
  height: 110px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}
.time-list {
  font-size: 0;
  margin-bottom: 22px;
}
</style>
