<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单ID" prop="ocode">
        <el-input
          v-model="queryParams.ocode"
          placeholder="请输入订单ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>  
      <el-form-item label="师傅" prop="workerUid">
        <el-select v-model="queryParams.workerUid"  filterable   placeholder="请选择师傅" clearable>
          <el-option
            v-for="type in usersDataList"
            :key="type.id"
            :label="type.name"
            :value="type.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    

    <el-table v-loading="loading" :data="OrderSoundList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center"  width="55" prop="id" />
      <el-table-column label="订单编号" align="center" prop="ocode" />
      <el-table-column label="师傅" align="center" prop="workerName" />
      <el-table-column label="录音文件" align="center" prop="file">
        <template slot-scope="scope">
          <span v-if="scope.row.file" style="cursor:pointer;">
            <svg v-if="playingRowId !== scope.row.id" @click="startAudio(scope.row)" width="24" height="24" viewBox="0 0 24 24" fill="#409EFF" style="vertical-align: middle;">
              <polygon points="8,5 19,12 8,19" />
            </svg>
            <svg v-else @click="stopAudio()" width="24" height="24" viewBox="0 0 24 24" fill="#F56C6C" style="vertical-align: middle;">
              <rect x="6" y="6" width="12" height="12" rx="2"/>
            </svg>
            <!-- 进度条 -->
            <div style="display:inline-block;width:100px;vertical-align:middle;margin:0 8px;">
              <el-progress
                :percentage="audioProgress[scope.row.id] || 0"
                :show-text="false"
                :stroke-width="4"
                style="vertical-align:middle;"
              />
            </div>
            <!-- 当前时间/总时长 -->
            <span style="font-size:12px;color:#888;">
              {{ formatTime(audioCurrentTime[scope.row.id] || 0) }}/{{ formatTime(audioDuration[scope.row.id] || 0) }}
            </span>
          </span>
          <span v-else style="color: #ccc;">无</span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" align="center" prop="createdAt" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

     
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改服务订单录音文件对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单ID" prop="oid">
          <el-input v-model="form.oid" placeholder="请输入订单ID" />
        </el-form-item>
        <el-form-item label="文件路径" prop="file">
          <file-upload v-model="form.file"/>
        </el-form-item>
        <el-form-item label="师傅ID" prop="workerUid">
          <el-input v-model="form.workerUid" placeholder="请输入师傅ID" />
        </el-form-item>
        <el-form-item label="${comment}" prop="createdAt">
          <el-date-picker clearable
            v-model="form.createdAt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择${comment}">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="${comment}" prop="updatedAt">
          <el-date-picker clearable
            v-model="form.updatedAt"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择${comment}">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrderSound, getOrderSound, delOrderSound, addOrderSound, updateOrderSound,getUserDataList} from "@/api/system/OrderSound"

export default {
  name: "OrderSound",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,

    
      usersDataList: [],
      // 服务订单录音文件表格数据
      OrderSoundList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ocode: null,
        workerUid: null,
        file: null,
        workerUid: null,
        createdAt: null,
        updatedAt: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        oid: [
          { required: true, message: "订单ID不能为空", trigger: "blur" }
        ],
        file: [
          { required: true, message: "文件路径不能为空", trigger: "blur" }
        ],
      },
      playingRowId: null,
      audioPlayer: null,
      audioProgress: {}, // { [rowId]: 进度百分比 }
      audioDuration: {}, // { [rowId]: 总时长 }
      audioCurrentTime: {}, // { [rowId]: 当前播放时间 }
    }
  },
  created() {
    this.getList()
    this.getUserDataList()
  },
  methods: {
    /** 查询服务订单录音文件列表 */
    getList() {
      this.loading = true
      listOrderSound(this.queryParams).then(response => {
        this.OrderSoundList = response.rows
        this.total = response.total
        this.loading = false
        // 预加载所有音频的时长
        this.OrderSoundList.forEach(row => {
          if (row.file) {
            let fileUrl = row.file;
            if (fileUrl && !/^https?:\/\//.test(fileUrl)) {
              fileUrl = window.location.origin + fileUrl;
            }
            const audio = new Audio();
            audio.src = fileUrl;
            audio.crossOrigin = "anonymous";
            audio.onloadedmetadata = () => {
              this.$set(this.audioDuration, row.id, audio.duration);
            };
            // 兼容部分浏览器不自动加载元数据
            audio.load();
          }
        });
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        oid: null,
        file: null,
        workerUid: null,
        createdAt: null,
        updatedAt: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加服务订单录音文件"
    },

    getUserDataList(){
      getUserDataList('2').then(response => {
        this.usersDataList = response.data
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getOrderSound(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改服务订单录音文件"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrderSound(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addOrderSound(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除服务订单录音文件编号为"' + ids + '"的数据项？').then(function() {
        return delOrderSound(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    startAudio(row) {
      if (this.audioPlayer) {
        this.audioPlayer.pause();
        this.audioPlayer.currentTime = 0;
      }
      this.audioPlayer = new Audio(row.file);
      this.playingRowId = row.id;
      // 监听元数据加载，获取总时长
      this.audioPlayer.onloadedmetadata = () => {
        this.$set(this.audioDuration, row.id, this.audioPlayer.duration);
      };
      // 监听播放进度
      this.audioPlayer.ontimeupdate = () => {
        this.$set(this.audioCurrentTime, row.id, this.audioPlayer.currentTime);
        const percent = this.audioPlayer.duration
          ? (this.audioPlayer.currentTime / this.audioPlayer.duration) * 100
          : 0;
        this.$set(this.audioProgress, row.id, percent);
      };
      // 监听播放结束
      this.audioPlayer.onended = () => {
        this.playingRowId = null;
        this.$set(this.audioProgress, row.id, 0);
        this.$set(this.audioCurrentTime, row.id, 0);
      };
      this.audioPlayer.play();
    },
    stopAudio() {
      if (this.audioPlayer) {
        this.audioPlayer.pause();
        this.audioPlayer.currentTime = 0;
        if (this.playingRowId) {
          this.$set(this.audioProgress, this.playingRowId, 0);
          this.$set(this.audioCurrentTime, this.playingRowId, 0);
        }
        this.playingRowId = null;
      }
    },
    // 格式化时间为 mm:ss
    formatTime(seconds) {
      const m = Math.floor(seconds / 60)
        .toString()
        .padStart(2, "0");
      const s = Math.floor(seconds % 60)
        .toString()
        .padStart(2, "0");
      return `${m}:${s}`;
    },
  }
}
</script>
