<template>
  <div>
    <el-card class="order-container">
      <div class="data">
        <el-card class="data-item" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>订单状态</span>
            </div>
          </template>
          <div class="text-left">
            <el-text>创建时间：{{ state.data.createTime }} </el-text><br />
            <el-text
              >交易方式：{{ state.data.tradeType ? "线上" : "线下" }}
            </el-text>
            <br />
            <el-text>订单号：{{ state.data.orderNo }} </el-text><br />
            <el-text>订单状态：{{ state.data.orderStatusString }} </el-text
            ><br />
            <el-text>订单金额：¥{{ state.data.totalPrice / 100 }} </el-text
            ><br />
            <el-text>完成时间：{{ state.data.updateTime }} </el-text><br />
          </div>
        </el-card>
        <el-card class="data-item" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>收货人信息</span>
            </div>
          </template>
          <div v-if="state.data?.orderAddress?.userName">
            <el-text>姓名：{{ state.data.orderAddress?.userName }}</el-text
            ><br />
            <el-text>电话：{{ state.data.orderAddress?.userPhone }}</el-text>
            <br />
            <el-text
              >地址：
              {{
                state.data.orderAddress.provinceName +
                state.data.orderAddress.cityName +
                state.data.orderAddress.regionName +
                state.data.orderAddress.detailAddress
              }}
            </el-text>
          </div>
          <div v-else>暂无地址</div>
        </el-card>
        <el-card class="data-item" shadow="hover">
          <template #header>
            <div class="card-header flex items-center justify-between">
              <span>交易双方信息</span>
              <el-button
                v-if="complaint?.id"
                type="danger"
                link
                @click="complaintInfoVisible = true"
                >投诉信息 ></el-button
              >
            </div>
          </template>
          <div>
            <el-text>订单所属店铺：{{ state.data.shopName }}</el-text> <br />
            <el-text>店铺ID: {{ state.data.shopIds }}</el-text> <br />
            <el-text>店铺负责人电话: {{ state.data.principal }}</el-text> <br />

            <el-text>购买人ID: {{ state.data.userId }}</el-text> <br />
            <el-text>购买人昵称: {{ state.data?.userNickname || "-" }}</el-text
            ><br />
            <el-text>购买人电话: {{ state.data.userMobile }}</el-text> <br />

            <br />
          </div>
        </el-card>
      </div>
      <el-table
        :data="state.tableData"
        tooltip-effect="dark"
        style="width: 100%"
      >
        <el-table-column label="商品图片">
          <template #default="scope">
            <img
              style="width: 100px"
              :key="scope.row.goodsId"
              :src="scope.row.goodsCoverImg"
              alt="商品主图"
            />
          </template>
        </el-table-column>
        <el-table-column prop="goodsId" label="商品编号"> </el-table-column>
        <el-table-column prop="goodsName" label="商品名"></el-table-column>
        <el-table-column prop="goodsCount" label="商品数量"> </el-table-column>
        <el-table-column prop="sellingPrice" label="单价">
          <template #default="{ row }">
            {{ row.sellingPrice / 100 }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card
      title="交易备注"
      v-if="[4, 7].includes(state.data.orderStatus)"
      class="mt-6"
    >
      <template #header>
        <div class="flex justify-between">
          <span>交易备注</span>
          <el-button plain @click="onSaveComment">保存备注信息</el-button>
        </div>
      </template>
      <div>
        <el-input
          v-model="state.data.comment"
          type="textarea"
          :rows="5"
          placeholder="请输入交易备注"
          clearable
        />
        <div class="mt-4">
          <div class="mb-4">上传交易图片</div>
          <UploadOnlyImage
            v-model:url="state.images"
            :key="coverKey"
            type="image"
          />
          <!-- <UploadImage v-model:url="state.images" /> -->
        </div>
      </div>
    </el-card>
    <el-dialog
      v-model="complaintInfoVisible"
      title="投诉信息"
      @close="audioPause"
    >
      <el-form label>
        <el-form-item label="投诉内容">
          <div>{{ complaint.complaint }}</div>
        </el-form-item>
        <el-form-item v-if="complaint.voice" label="语音信息">
          <div class="flex">
            <div
              class="flex items-center border-0 bg-green-400 rounded-lg text-gray-700 text-sm w-fit py-2 px-4 cursor-pointer"
              @click="toggleComplaintPlay"
            >
              <div class="transform-gpu">
                <Microphone class="w-4 h-4" />
              </div>
              <span class="ml-2"
                >{{
                  complaintVoice.isPlaying
                    ? `${complaintVoice.currentTime}"`
                    : `${complaintVoice.duration || complaint.duration}"`
                }}
              </span>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="投诉时间">
          <div>{{ complaint.createAt }}</div>
        </el-form-item>
      </el-form>
      <div
        class="m-4 shadow border border-solid border-gray-100 p-4"
        v-if="complaint.shopComment"
      >
        <div
          class="flex items-center justify-between border-b border-solid border-gray-200"
        >
          <h2 class="font-bold text-base mb-2">商家处理信息</h2>
          <span class="text-sm text-gray-500"
            >{{ complaint.shopUpdateAt }}完成</span
          >
        </div>
        <div class="text-sm text-gray-700 whitespace-pre-wrap my-4">
          {{ complaint.shopComment }}
        </div>
        <div>
          <el-image
            v-for="(item, index) in complaint.shopImages"
            :initial-index="index"
            class="w-20 h-20 mb-2 mr-2 rounded"
            :key="index"
            :src="item"
            fit="cover"
            :preview-src-list="complaint.showImages"
          ></el-image>
        </div>
      </div>
      <div
        class="m-4 shadow border border-solid border-gray-100 p-4"
        v-if="complaint.mechanismComment"
      >
        <div
          class="flex items-center justify-between border-b border-solid border-gray-200"
        >
          <h2 class="font-bold text-base mb-2">平台处理信息</h2>
          <span class="text-sm text-gray-500"
            >{{ complaint.mechanismUpdateAt }}完成</span
          >
        </div>
        <div class="text-sm text-gray-700 whitespace-pre-wrap my-4">
          {{ complaint.mechanismComment }}
        </div>
        <div>
          <el-image
            v-for="(item, index) in complaint.mechanismImages"
            :initial-index="index"
            :key="index"
            :src="item"
            fit="cover"
            class="w-20 h-20 mb-2 mr-2 rounded"
            :preview-src-list="complaint.mechanismImages"
          ></el-image>
        </div>
      </div>
      <template #footer>
        <el-popconfirm
          title="确认要删除这个投诉吗？删除后不可恢复"
          width="240"
          icon="delete"
          @confirm="deleteComplaint"
        >
          <template #reference>
            <el-button type="danger" plain>删除</el-button>
          </template>
        </el-popconfirm>
        <template v-if="complaint.status == 2">
          <!-- <el-popconfirm
            title="确认该投诉已处理完成了吗？确定后，该状态不可更改"
            width="240"
            @confirm="completeComplaint"
          >
            <template #reference>
            </template>
            </el-popconfirm> -->
          <el-button type="primary" @click="openCompleteComplaint"
            >标记为已处理</el-button
          >
        </template>
      </template>
    </el-dialog>
    <el-dialog v-model="completeComplaintVisible" title="标记为已处理">
      <el-form label-position="top">
        <el-form-item required label="填写处理备注">
          <el-input
            v-model="completeComplaintDetail.comment"
            type="textarea"
            placeholder="请填写处理备注"
          ></el-input>
        </el-form-item>
        <el-form-item label="上传处理图片凭证">
          <UploadOnlyImage
            v-model:url="completeComplaintDetail.images"
            :key="Date.now()"
            type="image"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="completeComplaint">确定</el-button>
      </template>
    </el-dialog>
    <audio
      ref="audioRef"
      @pause="onPause"
      @play="onPlay"
      @timeupdate="onTimeupdate"
      @canplay="onLoadedmetadata"
      :src="complaint.voice"
      controls="controls"
      type="audio/mpeg"
      class="hidden"
    ></audio>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from "vue";
import { useRoute } from "vue-router";
import { request } from "@/utils/index";
import UploadImage from "@/components/UploadImage.vue";
import UploadOnlyImage from "@/components/UploadOnlyImage.vue";
import { ElMessage } from "element-plus";
import {
  Microphone,
  ArrowUp,
  ArrowDown,
  Delete,
  QuestionFilled
} from "@element-plus/icons-vue";
const route = useRoute();
const { id } = route.query;
const state = reactive({
  data: {},
  tableData: [],
  images: []
});
const coverKey = ref(Date.now());

const onSaveComment = () => {
  if (!state.data.comment) {
    return ElMessage.error("请输入备注");
  }
  request
    .put("/mallService/mechanism/orders/comment", {
      ids: [state.data.orderId],
      comment: state.data.comment,
      images: state.images.map(v => v.url)
    })
    .then(resp => {
      ElMessage.success(resp.message);
      getOrderDetail();
    });
};
const getOrderDetail = () => {
  request.get(`/mallService/mechanism/orders/${id}`).then(res => {
    state.data = res.data;

    state.images = res.data.images?.map((v, i) => {
      return {
        url: v,
        name: "images" + i,
        status: "success",
        uid: new Date().getTime()
      };
    });
    if (!state.images) {
      state.images = [];
    }
    state.tableData = res.data.orderItems;
  });
};
onMounted(() => {
  getOrderDetail();
  getComplaint();
});

const complaintInfoVisible = ref(false);
const complaint = ref({
  id: "",
  voice: "",
  complaint: "",
  status: 0,
  duration: 0
});
const complaintVoice = ref({
  isPlaying: false,
  currentTime: 0,
  duration: 0
});
const audioRef = ref();
const getComplaint = async () => {
  const { data } = await request.get(`/mallService/mechanism/order/complaint`, {
    params: {
      orderNo: route.query.id
    }
  });
  complaint.value = data || { id: "", voice: "", complaint: "", duration: 0 };
  audioPause();
};
const toggleComplaintPlay = async () => {
  complaintVoice.value.isPlaying ? audioPause() : audioPlay();
};
const onTimeupdate = res => {
  complaintVoice.value.currentTime = Math.floor(res.target.currentTime);
};
const onLoadedmetadata = res => {
  complaintVoice.value.duration = parseInt(res.target.duration);
};

const audioPlay = () => {
  audioRef.value.play();
};
const audioPause = () => {
  audioRef.value.pause();
};
const onPlay = () => {
  complaintVoice.value.isPlaying = true;
};
const onPause = () => {
  complaintVoice.value.isPlaying = false;
};
const deleteComplaint = async () => {
  await request.post(`/mallService/mechanism/complaint/delete`, {
    id: complaint.value.id
  });
  ElMessage.success("操作成功");
  complaintInfoVisible.value = false;
  getComplaint();
};
const completeComplaintVisible = ref(false);
const completeComplaintDetail = ref({
  comment: "",
  images: []
});
const openCompleteComplaint = () => {
  completeComplaintVisible.value = true;
};
const completeComplaint = async () => {
  if (!completeComplaintDetail.value.comment) {
    return ElMessage.error("请填写处理备注");
  }
  await request.post(`/mallService/mechanism/complaint/complete`, {
    id: complaint.value.id,
    comment: completeComplaintDetail.value.comment,
    images: completeComplaintDetail.value.images.map(v => v.url)
  });
  ElMessage.success("操作成功");
  complaintInfoVisible.value = false;
  completeComplaintVisible.value = false;
  getComplaint();
};
</script>

<style scoped>
.data {
  display: flex;
  margin-bottom: 50px;
}
.data .data-item {
  flex: 1;
  margin: 0 10px;
}
.el-table {
  border: 1px solid #ebeef5;
  border-bottom: none;
}
.has-gutter th {
  border-right: 1px solid #ebeef5;
}

.has-gutter th:last-child {
  border-right: none;
}
.el-table__row td {
  border-right: 1px solid #ebeef5;
}
.el-table__row td:last-child {
  border-right: none;
}
</style>
