<template>
  <el-dialog
    :title="isEdit ? '编辑入口' : '添加入口'"
    width="800px"
    :visible.sync="visible"
    :destroy-on-close="false"
    :close-on-click-modal="false"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-position="left"
      label-width="110px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="入口名称" prop="entryName">
            <el-input
              v-model="form.entryName"
              placeholder="请输入入口名称"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="显示序号" prop="num">
            <el-input-number v-model="form.num" :min="1" label="序号" style="width: 140px" />
            <span style="color: rgba(144, 147, 153, 1);">（越小越靠上）</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="开放时间" prop="openTime">
            <el-time-picker
              v-model="form.openTime"
              is-range
              style="width: 100%"
              :picker-options="startPickerOptions"
              format="HH:mm"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <TagCard title="预约时间段">
        <div
          v-for="(item, index) in form.timePeriod"
          :key="item.key"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                class="aaa"
                :label="`时间段${index + 1}`"
                :rules="{
                  required: true,
                  message: '请选择时间段',
                  trigger: 'change',
                }"
              >
                <el-time-picker
                  v-model="item.timeRange"
                  is-range
                  style="width: 100%"
                  format="HH:mm"
                  value-format="HH:mm"
                  range-separator="至"
                  start-placeholder="选择开始时间"
                  end-placeholder="选择结束时间"
                  placeholder="选择时间范围"
                  @change="timePickerChange(index, $event)"
                />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item
                class="aaa"
                :label="`人流峰值`"
                :rules="{
                  required: true,
                  message: '请输入人流峰值',
                  trigger: ['blur', 'change'],
                }"
              >
                <el-input-number v-model="item.num" :min="1" label="序号" style="width: 140px" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-button
                v-if="index"
                icon="el-icon-close"
                circle
                @click="deleteTimePeriod(item)"
              />
              <el-button
                icon="el-icon-plus"
                circle
                @click="addTimePeriod"
              />
            </el-col>
          </el-row>
        </div>
      </TagCard>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false"> 取消 </el-button>
      <el-button type="primary" :loading="submitLoading" @click="submit">
        确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import TagCard from '@/components/TagCard';
import { parseTime } from '@/utils/index';
export default {
  components: {
    TagCard
  },
  props: {
  },
  data() {
    return {
      form: {
        entryName: '', // 入口名称
        num: 1, // 序号
        openTime: null, // 开放时间
        timePeriod: [
          {
            key: 1,
            num: 0,
            timeRange: null
          }
        ]
      },
      rules: {
        entryName: [
          { required: true, message: '请输入入口名称', trigger: 'blur' }
        ],
        num: [
          { required: true, message: '请输入显示序号', trigger: 'blur' }
        ],
        openTime: [
          { required: true, message: '请选择开放时间', trigger: 'change' }
        ]
      },
      visible: false,
      submitLoading: false,
      isEdit: false
    };
  },
  computed: {
    startDate() {
      let params = {
        min: '00:00',
        max: '23:59'
      };
      if (this.form.openTime && this.form.openTime.length > 0) {
        console.log(this.form.openTime);
        params = {
          min: parseTime(this.form.openTime[0], '{h}:{i}'),
          max: parseTime(this.form.openTime[1], '{h}:{i}')
        };
      }
      console.log(params);
      return params;
    },
    startPickerOptions() {
      const _this = this;
      return {
        selectableRange(time) {
          if (_this.form.endTime && _this.form.endTime !== '') {
            return time.getTime() > new Date(_this.form.endTime).getTime(); // 禁用true值
          }
          return false;
        }
      };
    }
  },
  methods: {
    open(obj) {
      this.visible = true;
      this.submitLoading = false;
      this.$nextTick(() => {
        this.$refs.form.resetFields();
        if (obj && Object.keys(obj).length > 0) {
          console.log(obj);
          this.form.id = obj.id;
          this.form = {
            // dingdingPushUserId: obj.dingdingPushUserId,
            // name: obj.name, // 姓名
            // phone: obj.phone, // 手机号
            // jobNumber: obj.jobNumber, // 工号
            // department: obj.department, // 部门名称
            // zoneDeviceIdList: (obj.zoneDeviceIdList || [])
          };
          this.isEdit = true;
        } else {
          this.isEdit = false;
        }
      });
    },
    // 功能增加
    addTimePeriod() {
      this.form.timePeriod.push({
        num: 0,
        timeRange: null,
        key: new Date().getTime() + (this.form.timePeriod.length + 1)
      });
      console.log(this.form.timePeriod);
    },
    // 功能刪除
    deleteTimePeriod(item) {
      const index = this.form.timePeriod.findIndex(
        (v) => v.key === item.key
      );
      if (index !== -1) {
        this.form.timePeriod.splice(index, 1);
      }
    },
    // 取消
    cloneFn() {
      this.dialogVisible = false;
      this.$refs.form?.clearValidate(); // 清空表单校验
      this.form = {
        entryName: '', // 入口名称
        num: 1, // 序号
        openTime: null, // 开放时间
        timePeriod: [
          {
            key: new Date().getTime() + 1,
            num: 0,
            timeRange: null
          }
        ]
      };
    },
    timePickerChange(index, e) {
      console.log(index, e);
    },
    // 确认按钮
    submit() {
      this.$refs.form.validate(async(pass) => {
        if (!pass) {
          this.submitLoading = false;
          return false;
        }
        if (this.submitLoading) {
          return;
        }
        this.submitLoading = true;
        const ruleConfigs = this.form.timePeriod.map(
          (item, index) => {
            return {
              startTime: item.timeRange[0],
              endTime: item.timeRange[1],
              key: new Date().getTime() + index,
              index
            };
          }
        );

        const sortedRuleConfigs = ruleConfigs.sort((a, b) => {
          const timeA = new Date(`1970-01-01T${a.startTime}`);
          const timeB = new Date(`1970-01-01T${b.startTime}`);
          return timeA - timeB;
        });
        // 打印按时间先后排序后的数组
        console.log(sortedRuleConfigs);
        for (let i = 1; i < sortedRuleConfigs.length; i++) {
          if (
            sortedRuleConfigs[i].startTime < sortedRuleConfigs[i - 1].endTime
          ) {
            this.$message({
              type: 'error',
              message: `时间段${sortedRuleConfigs[i].index + 1}和时间段${sortedRuleConfigs[i - 1].index + 1}有重叠!,请重新安排时间`
            });
            return;
          }
        }
        const res = {
          // productName: this.form.productName,
          // productDesc: this.form.productDesc,
          // productImages: this.form.productImages.map((item) => {
          //   return item?.response?.data || item.url;
          // }),
          // onSale: 0,
          id: this.isEdit ? this.form.id : undefined
        };
        console.log(res);

        // await doEditShop(res);
        // await this.fetchData();
        // this.$message.success(`${this.dialogTitle}成功`);
        this.submitLoading = false;
        // await this.cloneFn();
      });
    }
    // submit(e) {
    // e.preventDefault();
    // this.$refs.form.validate(async(valid) => {
    //   if (!valid) {
    //     return false;
    //   }
    //   if (this.submitLoading) {
    //     return;
    //   }
    //   this.submitLoading = true;
    //   try {
    //     await addOrUpdatePushConfig({
    //       ...this.form,
    //       adminId: this.$store.getters.adminId
    //     });
    //     this.visible = false;
    //     this.$emit('success', this.isEdit);
    //   } catch (e) {
    //     this.$refs.form.resetFields();
    //   } finally {
    //     this.submitLoading = false;
    //   }
    // });
    // }
  }
};
</script>

<style lang="scss" scoped>

.wrap-content {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  &__item {
    width: calc(50% - 10px);
  }
}
</style>
