<template>
  <div>
    <Search :search="search" :reset="resetQuery">
      <template v-slot:body>
        <el-form-item label="订单号" prop="trade_no">
          <el-input v-model="query.trade_no" placeholder="请输入订单号" clearable />
        </el-form-item>
        <el-form-item label="用户ID" prop="uid">
          <el-input v-model="query.uid" placeholder="请输入用户ID" clearable />
        </el-form-item>
        <el-form-item label="充值类型" prop="order_type">
          <el-select v-model="query.order_type" filterable clearable placeholder="选择充值类型">
            <el-option v-for="item in channelOrderTypeList" :key="item.value" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="query.status" filterable clearable placeholder="选择订单状态">
            <el-option v-for="item in channelOrderStatusList " :key="item.value" :label="item.name" :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- :remote-method="remoteMethod($event, 'channelPromotions')"不支持这种写法自定义参数 -->
        <el-form-item label="推广名称" prop="promotion_id">
          <el-select v-model="query.promotion_id" filterable remote clearable
            :remote-method="(query) => { remoteMethod(query, 'channelPromotions') }" placeholder="全部推广名称">
            <el-option v-for="item in channelPromotions" :key="item.promotion_id" :label="item.name"
              :value="item.promotion_id" />
          </el-select>
        </el-form-item>
        <el-form-item label="小程序" v-if="!query.promotion_id" prop="miniprogram_id">
          <el-select v-model="query.miniprogram_id" filterable remote
            :remote-method="(query) => { remoteMethod(query, 'channelMiniprogram') }" clearable placeholder="选择小程序">
            <el-option v-for="item in channelMiniprogram" :key="item.miniprogram_id" :label="item.name"
              :value="item.miniprogram_id" />
          </el-select>
        </el-form-item>
        <el-form-item label="优化师" v-if="!query.promotion_id && !rolesIdentify.includes('optimizer')" prop="user_id">
          <el-select v-model="query.user_id" filterable remote clearable
            :remote-method="(query) => { remoteMethod(query, 'channelPromotionsUsers') }" placeholder="选择优化师">
            <el-option v-for="item in promotionsUsersList" :key="item.user_id" :label="item.name" :value="item.user_id" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="支付时间">
          <el-date-picker unlink-panels clearable @change="payTimeChange" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
            v-model="query.payTime" type="daterange" :shortcuts="shortcuts" range-separator="To" start-placeholder="开始时间"
            end-placeholder="结束时间" />
        </el-form-item> -->
        <el-form-item label="订单时间">
          <el-date-picker unlink-panels clearable @change="orderTimeChange" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
            v-model="query.orderTime" type="daterange" :shortcuts="shortcuts" range-separator="To"
            start-placeholder="开始时间" end-placeholder="结束时间" />
        </el-form-item>
        <el-form-item label="支付名称" prop="pay_merchant_name" v-if="rolesIdentify.includes('administrator')">
          <el-input v-model="query.pay_merchant_name" placeholder="请输入支付名称" clearable />
        </el-form-item>
        <el-form-item label="收款主体" prop="payee_name" v-if="rolesIdentify.includes('administrator')">
          <el-input v-model="query.payee_name" placeholder="请输入收款主体" clearable />
        </el-form-item>
        <el-form-item label="支付商户号" prop="pay_appid" v-if="rolesIdentify.includes('administrator')">
          <el-input v-model="query.pay_appid" placeholder="请输入支付商户号" clearable />
        </el-form-item>
      </template>
      <template v-slot:extra_button>
        <exportExcel v-if="rolesIdentify.includes('administrator')" api="channel/order_list" sheet_name="订单列表"
          :title_obj="titlePtObj" :extro_params="{ is_export: true, ...query }">
        </exportExcel>
        <exportExcel v-else api="channel/order_list" sheet_name="订单列表" :title_obj="titleObj"
          :extro_params="{ is_export: true, ...query }">
        </exportExcel>
      </template>
    </Search>
    <div class="table-default">
      <el-table :data="tableData" class="mt-3" v-loading="loading">
        <el-table-column prop="company_name" label="商户名称" min-width="200px"
          v-if="!(rolesIdentify.includes('optimizer') || rolesIdentify.includes('company'))">
          <template #default="scope">
            <div>{{ scope.row.company_name }}</div>
            <div>ID:{{ scope.row.puser_id }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="优化师" show-overflow-tooltip min-width="200px"
          v-if="!rolesIdentify.includes('optimizer')">
        </el-table-column>
        <el-table-column prop="play_name" show-overflow-tooltip label="小程序" min-width="200px">
        </el-table-column>
        <el-table-column prop="uid" label="用户ID" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="trade_no" label="订单号" show-overflow-tooltip min-width="200px">
        </el-table-column>
        <el-table-column prop="created_at" label="订单时间" show-overflow-tooltip min-width="200px" />
        <el-table-column prop="ranse_created_at" label="染色注册时间" show-overflow-tooltip min-width="200px" />
        <el-table-column prop="total_count" label="累计充值成功次数" show-overflow-tooltip min-width="150px">
        </el-table-column>
        <el-table-column prop="price" label="充值金额" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="promotion_title" label="推广名称" show-overflow-tooltip min-width="200px">
        </el-table-column>
        <el-table-column prop="tip_text" label="充值类型" show-overflow-tooltip min-width="150px">
        </el-table-column>
        <el-table-column prop="pay_name" label="支付方式" show-overflow-tooltip min-width="150px">
        </el-table-column>
        <el-table-column prop="pay_merchant_name" label="支付名称" show-overflow-tooltip min-width="150px"
          v-if="rolesIdentify.includes('administrator')">
        </el-table-column>
        <el-table-column prop="payee_name" label="收款主体" show-overflow-tooltip min-width="150px"
          v-if="rolesIdentify.includes('administrator')">
        </el-table-column>
        <el-table-column prop="pay_appid" label="支付商户号" show-overflow-tooltip min-width="150px"
          v-if="rolesIdentify.includes('administrator')">
        </el-table-column>
        <el-table-column prop="status_txt" label="订单状态" show-overflow-tooltip min-width="150px">
          <template #default="scope">
            <div class="wrapper">
              <span class="text-lg font-bold content">
                <el-text class="mx-1" :type="colorType(scope.row)">{{ scope.row.status_txt }}</el-text>
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right">
          <template #default="scope">
            <el-button v-action="'channel.orders.userDetails'" link type="primary" size="small"
              @click="openType('userDetailVisible', scope.row)">用户详情</el-button>
            <br />
            <el-button v-if="scope.row.can_apply" link type="primary" size="small"
              v-action="'orderRefund.RefundOrder.applyRefund'"
              @click="openType('applyVisible', scope.row)">发起退款</el-button>
            <br />
          </template>
        </el-table-column>
      </el-table>
      <Paginate />
    </div>
    <Dialog v-model="userDetailVisible" width="50%" title="用户详情" :alignCenter="true" destroy-on-close>
      <userDetail @close="closeType('applyVisible')" :primary="userDetailData"></userDetail>
    </Dialog>
    <Dialog v-model="applyVisible" width="50%" title="申请退款" destroy-on-close>
      <create @close="closeType('applyVisible')" :primary="applyData"></create>
    </Dialog>
  </div>
</template>

<script lang="ts" setup>
import { shortcuts } from '@/utils/shortcuts'
import { useRouter, useRoute } from 'vue-router'
import { InfoFilled } from '@element-plus/icons-vue';
import { useGetList } from '@/hook/curd/useGetList';
import { titleObj, titlePtObj } from "./excelTitle"
import userDetail from './userDetail/index.vue'
import create from './form/create.vue'
import {
  channelOrderList,
  channelMiniprogramUseList,
  channelPromotionsOptions,
  channelPromotionsUsers,
  channelOrderStatus,
  channelOrderType,
} from '@/api/orders/index'
import moment from 'moment';
const start_date = moment().startOf('month').format('YYYY-MM-DD')
const end_date = moment().endOf('month').format('YYYY-MM-DD')

const api = 'channel/order_list';
const router = useRouter()
const route = useRoute()
const { data, query, search, reset, loading } = useGetList(api);
const userDetailVisible = ref(false)
const applyVisible = ref(false)
const userDetailData = ref({})
const applyData = ref({})
const current = ref({})
const promotionsUsersList = ref([])
const channelMiniprogram = ref([])
const channelPromotions = ref([])
const channelOrderStatusList = ref([])
const channelOrderTypeList = ref([])
const rolesIdentify = inject('rolesIdentify')

const colorType = (data: object) => {
  const type = data.status
  switch (type) {
    case 'PAID':
      return 'success'
    case 'REFUND':
      return 'default'
    case 'UNPAID':
      return 'danger'
  }
}

const payTimeChange = (e: object) => {
  console.log(e, query.value.payTime, 'timeChangetimeChangetimeChange');
  if (query.value.payTime) {
    const timeArr = toRaw(e);
    query.value.pay_end_at_start = timeArr[0]
    query.value.pay_end_at_end = timeArr[1]
  } else {
    delete query.value.pay_end_at_start
    delete query.value.pay_end_at_end
  }
}
const orderTimeChange = (e: object) => {
  console.log(e, 'timeChangetimeChangetimeChange');
  if (query.value.orderTime) {
    const timeArr = toRaw(e);
    query.value.created_at_start = timeArr[0]
    query.value.created_at_end = timeArr[1]
  } else {
    delete query.value.created_at_start
    delete query.value.created_at_end
  }
}

const remoteMethod = (query: string, type: string,) => {
  console.log(query, 'queryquery', type);
  switch (type) {
    case 'channelPromotionsUsers':
      initRemoteOption('channelPromotionsUsers', { name: query })
      break;
    case 'channelMiniprogram':
      initRemoteOption('channelMiniprogram', { name: query })
      break;
    case 'channelPromotions':
      initRemoteOption('channelPromotions', { name: query })
      break;
  }
}

const initRemoteOption = (type: string, params?: object) => {
  switch (type) {
    case 'channelPromotionsUsers':
      channelPromotionsUsers({ limit: 30, ...params }).then(res => {
        promotionsUsersList.value = res.data
      })
      break;
    case 'channelMiniprogram':
      channelMiniprogramUseList({ limit: 30, ...params }).then(res => {
        channelMiniprogram.value = res.data
      })
      break;
    case 'channelPromotions':
      channelPromotionsOptions({ limit: 30, ...params }).then(res => {
        channelPromotions.value = res.data
      })
      break;
  }
}

const init = () => {
  channelOrderStatus().then(res => {
    console.log(res);
    channelOrderStatusList.value = res.data
  })
  channelOrderType().then(res => {
    console.log(res);
    channelOrderTypeList.value = res.data
  })
}

const resetQuery = () => {
  reset()
}
const openType = (type: string, data: object) => {
  current.value = data;
  switch (type) {
    case 'userDetailVisible':
      userDetailVisible.value = true
      userDetailData.value = data
      break;
    case 'applyVisible':
      applyVisible.value = true
      applyData.value = data
      break;
  }
}

const closeType = (type: string) => {
  switch (type) {
    case 'userDetailVisible':
      userDetailVisible.value = false
      break;
    case 'applyVisible':
      applyVisible.value = false
      break;
  }
  search()
}
const tableData = computed(() => data.value?.data);

onMounted(() => {
  console.log(rolesIdentify, 'rolesIdentifyrolesIdentify');
  initRemoteOption('channelPromotionsUsers')
  initRemoteOption('channelMiniprogram')
  initRemoteOption('channelPromotions')
  init()
  // query.value.payTime = [start_date, end_date];
  // query.value.pay_end_at_start = start_date
  // query.value.pay_end_at_end = end_date
  // query.value.orderTime = [start_date, end_date];
  // query.value.created_at_start = start_date
  // query.value.created_at_end = end_date
  search();
});
</script>

<style scoped lang="scss">
.table-default {
  .set-warpper {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }

  .wrapper {
    margin: 8px;

    .label {
      margin-right: 6px;
    }

    .content {
      font-size: 15px;
    }
  }
}</style>
