<template>
  <el-form
    ref="form"
    :model="form"
    :rules="rules"
    label-width="140px"
    class="el-form-box"
    :disabled="title == '详情'"
  >
    <ele-pro-table
      :columns="columns"
      :datasource="form.list"
      ref="table"
      height="300px"
      full-height="calc(100vh - 116px)"
      :needPage="false"
    >
      <template v-slot:toolbar v-if="title != '详情'">
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          class="ele-btn-icon"
          @click="handAdd()"
          style="margin-bottom: 5px"
        >
          新增
        </el-button>
        <!-- <el-popconfirm
          class="ele-action"
          title="确定要删除选中的信息吗？"
          @confirm="remove()"
        >
          <template v-slot:reference>
            <el-button
              type="danger"
              :underline="false"
              icon="el-icon-delete"
              :disabled="selection?.length === 0"
            >
              删除
            </el-button>
          </template>
        </el-popconfirm> -->
      </template>
      <template v-slot:dutyName="{ row, $index }">
        <el-form-item
          label-width="0"
          :prop="'list.' + $index + '.dutyName'"
          :rules="[
            {
              required: true,
              message: '出勤名称不能为空',
              trigger: 'blur'
            }
          ]"
        >
          <DictSelection
            dictName="班次出勤名称"
            clearable
            v-model="row.dutyName"
            filterable
            valueName="dictValue"
            allow-create
            default-first-option
            :isOne="$index === 0"
          >
          </DictSelection>
        </el-form-item>
      </template>
      <template v-slot:timeType="{ row, $index }">
        <el-form-item
          label-width="0"
          :prop="'list.' + $index + '.timeType'"
          :rules="[
            {
              required: true,
              message: '请选择时间类型',
              trigger: 'blur'
            }
          ]"
        >
          <el-select
            v-model="row.timeType"
            clearable
            style="width: 100%"
            @change="setFormtime"
          >
            <el-option :value="'1'" label="工作时间"></el-option>
            <el-option :value="'2'" label="休息时间"></el-option>
          </el-select>
        </el-form-item>
      </template>
      <template v-slot:startTime="{ row, $index }">
        <el-form-item
          label-width="0"
          :prop="'list.' + $index + '.startTime'"
          :rules="[
            {
              required: true,
              message: '请选择开始时间',
              trigger: 'blur'
            }
          ]"
        >
          <el-time-picker
            style="width: 100%"
            placeholder="开始时间"
            v-model="row.startTime"
            format="HH:mm"
            value-format="HH:mm"
            @change="changeTime(row, $index, 'startTime')"
            :disabled="!!form.list[$index - 1]?.endTime"
          >
          </el-time-picker>

          <!-- <el-time-select
            placeholder="开始时间"
            v-model="row.startTime"
            @change="changeTime(row, $index, 'startTime')"
            :disabled="!!form.list[$index - 1]?.endTime"
            :picker-options="{
              ...defTime,
              ...(form.list[$index - 1]
                ? {
                    minTime: form.list[$index - 1].endTime
                  }
                : {})
            }"
          >
          </el-time-select> -->
        </el-form-item>
      </template>
      <template v-slot:endTime="{ row, $index }">
        <el-form-item
          label-width="0"
          :prop="'list.' + $index + '.endTime'"
          :rules="[
            {
              required: true,
              message: '请选择结束时间',
              trigger: 'blur'
            }
          ]"
        >
          <el-time-picker
            style="width: 100%"
            placeholder="结束时间"
            v-model="row.endTime"
            format="HH:mm"
            value-format="HH:mm"
            :disabled="!row.startTime"
            @change="changeTime(row, $index, 'endTime')"
            :picker-options="{
              selectableRange: row.startTime + ':00-23:59:59'
            }"
          >
          </el-time-picker>

          <!-- <el-time-select
            placeholder="结束时间"
            v-model="row.endTime"
            @change="changeTime(row, $index, 'endTime')"
            :picker-options="{
              ...defTime,
              ...{
                minTime: row.startTime
              }
            }"
          >
          </el-time-select> -->
        </el-form-item>
      </template>
      <template v-slot:columnRequired="{ column }">
        <span class="is-required">{{ column.label }}</span>
      </template>
      <template v-slot:note="{ row }">
        <el-input clearable v-model="row.note" placeholder="请输入" />
      </template>
      <template v-slot:action="{ row, $index }">
        <el-popconfirm
          class="ele-action"
          title="确定要删除此信息吗？"
          @confirm="remove($index)"
        >
          <template v-slot:reference>
            <el-link type="danger" :underline="false" icon="el-icon-delete">
              删除
            </el-link>
          </template>
        </el-popconfirm>
      </template>
    </ele-pro-table>
  </el-form>
</template>
<script>
  const defForm = {
    list: [] //表格数据
  };

  export default {
    data() {
      return {

        columns: [
          {
            width: 60,
            type: 'index',
            columnKey: 'index',
            label: '序号',
            align: 'center',
            fixed: 'left'
          },
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center'
          },
          {
            prop: 'dutyName',
            slot: 'dutyName',
            headerSlot: 'columnRequired',
            label: '出勤名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 180
          },
          {
            slot: 'timeType',
            prop: 'timeType',
            headerSlot: 'columnRequired',
            label: '时间类型',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'startTime',
            label: '开始时间',
            align: 'center',
            headerSlot: 'columnRequired',
            slot: 'startTime',
            showOverflowTooltip: true,
            minWidth: 170
          },
          {
            prop: 'endTime',
            minWidth: 170,
            headerSlot: 'columnRequired',
            slot: 'endTime',
            label: '结束时间',
            align: 'center'
          },
          {
            width: 160,
            prop: 'totalDuration',
            label: '总时长（分钟）',
            align: 'center'
          },
          {
            prop: 'note',
            slot: 'note',
            label: '备注',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 200
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 150,
            align: 'center',
            resizable: false,
            slot: 'action',
            showOverflowTooltip: true,
            fixed: 'right'
          }
        ],
        selection: [],

        form: { ...defForm },
        rules: {},
        title: '新增'
      };
    },
    mounted() {},
    created() {},

    methods: {
      //初始化
      async init(row = {}, type) {
        this.title = type == 'add' ? '新增' : type == 'edit' ? '修改' : '详情';
        this.form.list = row.list;
        this.form.list.forEach((item, index) => {
          item.key = index;
        });
      },
      handAdd() {
        if (
          this.form.list?.length &&
          !this.form.list[this.form.list?.length - 1].endTime
        ) {
          this.$message.error('请先填写前一条数据的结束时间');
          return;
        }
        this.form.list.push({
          startTime: this.form.list[this.form.list?.length - 1]?.endTime || '',
          endTime: '',
          note: '',
          totalDuration: '',
          dutyName: '',
          timeType: '1',
          key: this.form.list?.length || 0
        });
      },
      changeTime(row, index, type) {
        // return
        if (type == 'startTime') {
          this.$set(this.form.list[index], 'endTime', '');
          row.startTime =
            row.startTime.split(':')[0] +
            ':' +
            row.startTime.split(':')[1] +
            ':00';
        }

        this.removeFormtime(index);
        if (row.startTime && row.endTime) {
          let startTime = new Date(row.startTime).getTime();
          if (!startTime) {
            startTime = new Date('2025-01-01 ' + row.startTime).getTime();
          }
          let endTime = new Date('2025-01-01 ' + row.endTime).getTime();
          let val = (endTime - startTime) / 60000;

          this.$set(this.form.list[index], 'totalDuration', val);
        } else {
          this.$set(this.form.list[index], 'totalDuration', 0);
        }
        this.setFormtime();
      },
      removeFormtime(i) {
        this.form.list.splice(i + 1, this.form.list.length - i);
      },
      setFormtime() {
        if (this.form.list?.length) {
          let attendanceStartTime = this.form.list[0].startTime;
          let attendanceEndTime =
            this.form.list[this.form.list.length - 1].endTime;
          let totalWorkingMinutes = 0;
          let restDurationMinutes = 0;

          this.form.list.forEach((v, index) => {
            v.key = index;
            if (v.timeType == '1') {
              totalWorkingMinutes += v.totalDuration;
            } else {
              restDurationMinutes += v.totalDuration;
            }
          });
          this.$emit('setFormtime', {
            attendanceStartTime,
            attendanceEndTime,
            totalWorkingMinutes,
            restDurationMinutes
          });
        }
      },

      remove(index) {
        if (index != 0) {
          this.removeFormtime(index);
        }
        this.form.list.splice(index, 1);
        this.setFormtime();
        this.selection = [];
      },
      getTableValue() {
        return new Promise((resolve) => {
          this.$refs.form.validate((valid) => {
            if (!valid) {
              resolve([]);
            } else {
              resolve(this.form.list);
            }
          });
        });
      }
    }
  };
</script>
<style scoped lang="scss"></style>
