<template>
  <el-card class="order-container">
    <template #header>
      <div class="header flex items-center flex-wrap">
        <el-input
          style="width: 200px; margin-right: 10px"
          placeholder="请输入订单号"
          v-model="state.orderNo"
          @change="handleOption"
          clearable
        />
        <el-select
          @change="handleOption"
          v-model="state.orderStatus"
          filterable
          style="width: 200px; margin-right: 10px"
        >
          <el-option
            v-for="item in state.options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          @change="handleOption"
          v-model="state.tradeType"
          filterable
          style="width: 200px; margin-right: 10px"
        >
          <el-option label="全部交易方式" :value="-1" />
          <el-option
            v-for="item in tradeTypeList"
            :key="item.v"
            :label="item.k"
            :value="item.v"
          />
        </el-select>
        <el-select
          @change="handleOption"
          v-model="state.payType"
          filterable
          style="width: 200px; margin-right: 10px"
        >
          <el-option label="全部支付方式" :value="-1" />
          <el-option
            v-for="item in payTypeList"
            :key="item.v"
            :label="item.k"
            :value="item.v"
          />
        </el-select>
        <!-- <el-select
          @change="handleOption"
          v-model="state.shopId"
          filterable
          style="width: 200px; margin-right: 10px"
        >
          <el-option label="全部店铺" :value="-1" />
          <el-option
            v-for="item in state.shopList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select> -->

        <!-- <el-button type="primary" size="small" icon="el-icon-edit">修改订单</el-button> -->
        <!-- <el-button type="primary" :icon="HomeFilled" @click="handleConfig()"
          >配货完成</el-button
        >
        <el-button type="primary" :icon="HomeFilled" @click="handleSend()"
          >出库</el-button
        > -->
        <el-button type="danger" :icon="Delete" @click="handleClose()"
          >关闭订单</el-button
        >
        <!-- <div class="flex justify-end flex-1">
          <div class="border border-solid border-gray-300 rounded p-2 cursor-pointer text-sm" @click="complaintVisible = true">
            <span>投诉信息：</span>
            <span class=" " :class="complaintWaitTotal ? 'text-red-600 font-bold' : 'text-green-600'">{{ complaintWaitTotal }}条待处理</span>
          </div>
        </div> -->
        <el-button
          class="ml-4"
          :icon="Download"
          type="success"
          @click="state.visibleExportOrder = true"
          >导出订单</el-button
        >
      </div>
    </template>
    <el-table
      :data="state.tableData"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="orderNo" label="订单号"> </el-table-column>
      <!-- <el-table-column prop="orderNo" label="商品">
        <template #default="{ row }">
          <el-text tag="b">{{ row.goodsName }}</el-text>
        </template>
      </el-table-column>
      <el-table-column prop="goodsCount" label="数量"> </el-table-column> -->

      <el-table-column prop="totalPrice" label="订单总价">
        <template #default="scope">
          <span>{{ scope.row.totalPrice / 100 }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="orderStatus" label="订单状态">
        <template #default="scope">
          <el-tag t type="success" v-if="scope.row.orderStatus == 4">{{
            farmatOrderMap(scope.row.orderStatus)
          }}</el-tag>
          <span v-else>{{ farmatOrderMap(scope.row.orderStatus) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="交易方式" prop="tradeType" width="">
        <template #default="{ row }">
          <el-text>{{ tradeTypeList[row.tradeType].k }}</el-text>
        </template>
      </el-table-column>

      <el-table-column prop="payType" label="支付方式">
        <template #default="scope">
          <span v-if="scope.row.payType == 1">微信支付</span>
          <span v-else-if="scope.row.payType == 2">支付宝支付</span>
          <span v-else-if="9">其他</span>
          <span v-else>系统</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间"> </el-table-column>
      <el-table-column prop="updateTime" label="完成时间"> </el-table-column>
      <el-table-column prop="targetName" label="补贴对象">
        <template #default="{ row }">
          {{ row.targetName || "-" }}
        </template>
      </el-table-column>

      <el-table-column
        label="所属店铺"
        prop="shopName"
        width=""
      ></el-table-column>
      <el-table-column label="操作" width="240">
        <template #default="scope">
          <div class="">
            <el-popconfirm
              v-if="scope.row.orderStatus < 4"
              title="确定关闭订单吗？"
              @confirm="handleClose(scope.row.orderId)"
              confirm-button-text="确定"
              cancel-button-text="取消"
            >
              <template #reference>
                <el-button type="primary" link style="margin-right: 10px"
                  >关闭订单</el-button
                >
              </template>
            </el-popconfirm>
            <router-link
              :to="{
                path: '/myShop/order/detail',
                query: { id: scope.row.orderNo }
              }"
            >
              <el-button type="primary" link>订单详情</el-button>
            </router-link>
            <!-- <el-button
              type="primary"
              v-if="scope.row.orderStatus < 4"
              link
              style="margin-left: 10px"
              @click="
                () => {
                  rowData = scope.row;
                  remarkVisible = true;
                }
              "
              >完成订单</el-button
            > -->
            <el-button
              type="primary"
              v-if="scope.row.orderStatus < 4"
              link
              :disabled="scope.row.orderStatus"
              @click="handleCompleteOrder(scope.row.orderId)"
              >完成订单</el-button
            >
          </div>
          <!-- <el-popconfirm
            v-if="scope.row.orderStatus < 4"
            title="确定要完成订单吗？"
            @confirm="handleCompleteOrder([scope.row.orderId])"
            confirm-button-text="确定"
            cancel-button-text="取消"
          >
            <template #reference>
              <el-button type="primary" link :disabled="scope.row.orderStatus"
                >完成订单</el-button
              >
            </template>
          </el-popconfirm> -->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="mt-4 justify-end"
      background
      layout="prev, pager, next"
      :total="state.total"
      :page-size="state.pageSize"
      @current-change="changePage"
    />
    <el-dialog v-model="complaintVisible" title="投诉信息">
      <div class="flex justify-between">
        <el-button
          type="primary"
          plain
          @click="
            complaintFilter.page = 1;
            getComplaintList();
          "
          >刷新</el-button
        >
        <el-select
          v-model="complaintFilter.status"
          @change="
            complaintFilter.page = 1;
            getComplaintList();
          "
        >
          <el-option label="全部" :value="-1"></el-option>
          <el-option
            v-for="(item, index) in complaintStatusToText"
            :key="index"
            :label="item"
            :value="index"
          ></el-option>
        </el-select>
      </div>
      <el-table :data="complaintList">
        <el-table-column label="订单编号" prop="orderNo"></el-table-column>
        <el-table-column label="投诉时间" prop="createAt"></el-table-column>
        <el-table-column label="投诉处理状态">
          <template #default="{ row }">
            <span
              :class="
                [
                  'text-orange-500',
                  'text-blue-500',
                  'text-red-500',
                  'text-green-500'
                ][row.status]
              "
              >{{ complaintStatusToText[row.status] }}</span
            >
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              @click="
                router.push({
                  path: '/myShop/order/detail',
                  query: { id: row.orderNo }
                })
              "
              >查看</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="mt-4 justify-end"
        background
        layout="total, prev, pager, next"
        :total="complaintTotal"
        :page-size="complaintFilter.pageSize"
        @current-change="
          p => {
            complaintFilter.page = p;
            getComplaintList();
          }
        "
      />
    </el-dialog>
    <el-dialog v-model="remarkVisible">
      <TradNote
        :id="rowData.orderNo"
        @onSave="handleCompleteOrder"
        @title="备注信息;"
      />
    </el-dialog>
    <DialogCompleteOreder
      v-model:show="state.visibleCompleteOrder"
      :orderId="state.orderId"
      @success="getOrderList"
    />
    <DialogExportOrder
      v-model:show="state.visibleExportOrder"
      :orderId="state.orderId"
      @success="getOrderList"
    />
  </el-card>
</template>

<script setup>
import { onMounted, reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { HomeFilled, Delete, Download } from "@element-plus/icons-vue";
import { request } from "@/utils";

import DialogCompleteOreder from "./components/DialogCompleteOreder.vue";
import DialogExportOrder from "./components/DialogExportOrder.vue";

import { useRouter } from "vue-router";
import TradNote from "./components/TradNote.vue";

const router = useRouter();
const rowData = ref({
  orderNo: ""
});
const state = reactive({
  loading: false,
  tableData: [], // 数据列表
  multipleSelection: [], // 选中项
  total: 0, // 总条数
  currentPage: 1, // 当前页
  pageSize: 10, // 分页大小
  orderNo: "", // 订单号
  orderStatus: -1, // 订单状态
  tradeType: -1, // 交易方式
  shopList: [],
  shopId: -1,
  payType: -1,
  visibleCompleteOrder: false,
  visibleExportOrder: false,
  orderId: undefined,
  // 订单状态筛选项默认值
  options: [
    {
      value: -1,
      label: "全部"
    },
    {
      value: 0,
      label: "待支付"
    },
    {
      value: 1,
      label: "已支付"
    },
    // {
    //   value: 2,
    //   label: "配货完成"
    // },
    {
      value: 3,
      label: "已发货"
    },
    {
      value: 4,
      label: "交易成功"
    },
    {
      value: 5,
      label: "用户关闭"
    },
    {
      value: 6,
      label: "超时关闭"
    },
    {
      value: 7,
      label: "商家关闭"
    }
  ]
});
const tradeTypeList = [
  {
    k: "线下",
    v: 0
  },
  {
    k: "线上",
    v: 1
  }
];
const payTypeList = {
  1: {
    k: "支付宝支付",
    v: 1
  },
  2: {
    k: "微信支付",
    v: 2
  },
  9: {
    k: "其他",
    v: 9
  }
};
const orderStatus = {
  0: "待支付",
  1: "已支付",
  3: "出库成功",
  4: "交易成功",
  5: "用户关闭",
  6: "超时关闭",
  7: "商家关闭"
};
// 初始化获取订单列表
onMounted(() => {
  getOrderList();
  // getShopList();
});

const farmatOrderMap = status => {
  return orderStatus[status] || "未知状态";
};

const getShopList = () => {
  request
    .get("/articleService/serviceProvider/shop/paginate", {
      params: {
        page: 1,
        pageSize: 9999,
        type: -1,
        status: -1
      }
    })
    .then(resp => {
      state.shopList = resp.data.list;
    });
};

// 获取列表方法
const getOrderList = () => {
  state.loading = true;
  request
    .get("/mallService/mechanism/staff/orders", {
      params: {
        page: state.currentPage,
        pageSize: state.pageSize,
        orderNo: state.orderNo,
        orderStatus: state.orderStatus,
        tradeType: state.tradeType,
        shopId: state.shopId,
        payType: state.payType
      }
    })
    .then(res => {
      state.tableData = res.data.list;
      state.total = res.data.total;
    });
};
// 触发过滤项方法
const handleOption = () => {
  state.currentPage = 1;
  getOrderList();
};
// checkbox 选择项
const handleSelectionChange = val => {
  state.multipleSelection = val;
};
// 翻页方法
const changePage = val => {
  state.currentPage = val;
  getOrderList();
};
// 完成订单
const handleCompleteOrder = () => {
  state.orderId = id;
  state.visibleCompleteOrder = true;
  // request
  //   .put("/mallService/mechanism/orders/complete", {
  //     ids: [rowData.value.orderId]
  //   })
  //   .then(resp => {
  //     ElMessage.success(resp.message);
  //     getOrderList();
  //     remarkVisible.value = false;
  //   });
};
// 配货方法
const handleConfig = id => {
  let params;
  // 当个配置
  if (id) {
    params = [id];
  } else {
    if (!state.multipleSelection.length) {
      console.log("state.multipleSelection", state.multipleSelection.length);
      ElMessage.error("请选择项");
      return;
    }
    // 多选配置
    params = state.multipleSelection.map(i => i.orderId);
  }
  request
    .put("/mallService/mechanism/orders/checkDone", {
      ids: params
    })
    .then(() => {
      ElMessage.success("配货成功");
      getOrderList();
    });
};
// 出库方法
const handleSend = id => {
  let params;
  if (id) {
    params = [id];
  } else {
    if (!state.multipleSelection.length) {
      ElMessage.error("请选择项");
      return;
    }
    params = state.multipleSelection.map(i => i.orderId);
  }
  request
    .put("/mallService/mechanism/orders/checkOut", {
      ids: params
    })
    .then(() => {
      ElMessage.success("出库成功");
      getOrderList();
    });
};
// 关闭订单方法
const handleClose = id => {
  let params;
  if (id) {
    params = [id];
  } else {
    if (!state.multipleSelection.length) {
      ElMessage.error("请选择项");
      return;
    }
    params = state.multipleSelection.map(i => i.orderId);
  }
  request
    .put("/mallService/mechanism/orders/close", {
      ids: params
    })
    .then(() => {
      ElMessage.success("关闭成功");
      getOrderList();
    });
};
const remarkVisible = ref(false);
const complaintStatusToText = {
  0: "待商家处理",
  1: "商家已处理",
  2: "待平台处理",
  3: "平台已处理"
};
const complaintVisible = ref(false);
const complaintList = ref([]);
const complaintWaitTotal = ref(0);
const complaintTotal = ref(0);
const complaintFilter = ref({
  page: 1,
  pageSize: 15,
  status: -1,
  isShop: 1
});
const getComplaintWaitTotal = async () => {
  const { data } = await request.get(
    `/mallService/mechanism/complaint/paginate`,
    {
      params: {
        page: 1,
        status: 2,
        pageSize: 0,
        isShop: 1
      }
    }
  );
  complaintWaitTotal.value = data.total;
};
const getComplaintList = async () => {
  const { data } = await request.get(
    `/mallService/mechanism/complaint/paginate`,
    {
      params: complaintFilter.value
    }
  );
  complaintList.value = data.list;
  complaintTotal.value = data.total;
};
getComplaintWaitTotal();
getComplaintList();
</script>
