<script setup>
/**
 * name：
 * user：sa0ChunLuyu
 * date：2022年12月25日 20:50:25
 */
import {
  UserOrderCancelAction,
  UserOrderRefundAction,
  UserOrderListAction,
  HospitalSelectListAction,
  $response, HospitalInfoAction,
} from '~/api'
import $router from '~/router'
import {h} from "vue";
import {NTag, NSpace} from 'naive-ui'
import {onBeforeRouteUpdate} from "vue-router";

const hospital_info = ref(false)
const HospitalInfo = async () => {
  const response = await HospitalInfoAction()
  $response(response, () => {
    hospital_info.value = response.data.info
    UserOrderList()
  })
}

const default_page_options = {
  page: 1,
  start_time: null,
  end_time: null,
  time: 1,
  search: '',
  status: 0,
}
const page_options = ref(JSON.parse(JSON.stringify(default_page_options)))
onBeforeRouteUpdate((to) => {
  routerChange(to.query)
})
const routerChange = (query) => {
  page_options.value = {
    start_time: query.start_time || default_page_options.start_time,
    end_time: query.end_time || default_page_options.end_time,
    time: Number(query.time || default_page_options.time),
    search: query.search || default_page_options.search,
    status: Number(query.status || default_page_options.status),
    page: Number(query.page || default_page_options.page),
  }
  user_order_active.value = []
  if (!hospital_info.value) {
    HospitalInfo()
  } else {
    UserOrderList()
  }
}

onMounted(() => {
  routerChange($router.currentRoute.value.query)
})

const user_order_active = ref([])
const user_order_list = ref([])
const user_order_list_last_page = ref(0)
const UserOrderList = async () => {
  const response = await UserOrderListAction({
    ...page_options.value,
    hospital: hospital_info.value.id
  })
  $response(response, () => {
    user_order_list.value = response.data.data.map((item) => {
      item.buy_info = JSON.parse(item.buy_info)
      return item
    })
    user_order_list_last_page.value = response.data.last_page
  })
}
const pay_arr = ['暂未指定', '微信', '会员卡', '免费']
const pay_color_arr = ['default', 'success', 'error', 'info']
const status_arr = ['待支付', '已支付', '已取消', '已完成', '已退款', '已到检', '仅退款']
const status_color_arr = ['default', 'success', 'default', 'info', 'error']
const user_order_columns = [{
  type: 'selection',
  multiple: false
}, {
  title: '体检人信息',
  key: 'name',
  render(row) {
    let children = [
      h('div', null, {
        default: () => {
          return [
            h(
              NSpace,
              {align: 'center', justify: 'space-between'},
              {
                default: () => {
                  return [
                    h('div', null, [
                      h('b', '姓名: '),
                      row.name,
                    ]),
                    h(NSpace, {
                      align: 'center'
                    }, {
                      default: () => {
                        return [
                          h('b', '性别:'),
                          h(
                            NTag,
                            {
                              size: 'small',
                              type: Number(row.sex) === 1 ? 'info' : 'error'
                            },
                            {
                              default: () => {
                                return Number(row.sex) === 1 ? '男' : '女'
                              }
                            }
                          ),
                        ]
                      }
                    }),
                  ]
                }
              }
            )
          ]
        }
      }),
      h('div', null, [
        h('b', '手机号: '),
        h('span', row.phone),
      ]),
      h('div', null, [
        h('b', '证件号: '),
        h('span', row.id_number),
      ]),
    ]
    if (row.type === 2) {
      children.push(h('div', null, [
        h('b', '单位名称: '),
        h('span', null, row.buy_info.group.group_name),
      ]))
    }
    return children
  }
}, {
  title: '检测信息',
  key: 'type',
  render(row) {
    let name = '-'
    if (row.combo !== '0') {
      name = row.buy_info.combo.name
    } else {
      if (Number(row.type) === 2) {
        name = row.buy_info.group.combo_name
      }
    }
    return [
      h('div', null, [
        h('b', '检测类型: '),
        h(
          NTag,
          {
            size: 'small',
            type: Number(row.type) === 1 ? 'success' : 'error'
          },
          {
            default: () => {
              return Number(row.type) === 1 ? '个检' : '团检'
            }
          }
        ),
      ]),
      h('div', null, [
        h('b', '套餐名称: '),
        h('span', null, name),
      ]),
      h('div', {class: ['line_wrapper']}, [
        h('b', '自选项目: '),
        h('div', {class: ['items_content_wrapper']}, !!row.buy_info.items.length ? row.buy_info.items.map((item) => {
          return item.name
        }).join('、') : '-'),
      ]),
    ]
  }
}, {
  title: '支付信息',
  key: 'status',
  render(row) {
    let price = row.price
    if (row.price !== row.true_price) {
      price = price + '（' + row.true_price + '）'
    }
    let children = [
      h('div', null, [
        h('b', '订单编号: '),
        h('span', row.show),
      ]),
      h('div', null, [
        h('b', '创建时间: '),
        h('span', row.created_at),
      ]),
      h(
        NSpace,
        {align: 'center'},
        {
          default: () => {
            return [
              h('b', '支付方式: '),
              h(
                NTag,
                {
                  size: 'small',
                  type: pay_color_arr[row.pay_type]
                },
                {
                  default: () => {
                    return pay_arr[row.pay_type]
                  }
                }
              ),
            ]
          }
        }
      ),
      h('div', null, [
        h('b', '支付金额: '),
        h('span', price),
      ]),
      h(
        NSpace,
        {align: 'center'},
        {
          default: () => {
            return [
              h('b', '支付状态: '),
              h(
                NTag,
                {
                  size: 'small',
                  type: ((!!row.refund_time && row.status === 2) || (!row.appointment_number && row.status === 2))
                    ? 'error'
                    : status_color_arr[row.status - 1]
                },
                {
                  default: () => {
                    if (!!row.refund_time && row.status === 2) return '仅退款'
                    if (!row.appointment_number && row.status === 2) return '仅退订'
                    return status_arr[row.status - 1]
                  }
                }
              ),
            ]
          }
        }
      ),
    ]
    if (row.status !== 1 && row.status !== 3) {
      children.push(h('div', null, [
        h('b', '支付时间: '),
        h('span', row.pay_time),
      ]))
    }
    if (!!row.transaction) {
      children.push(h('div', null, [
        h('b', '支付编号: '),
        h('span', row.transaction),
      ]))
    }
    if (!!row.refund_time) {
      children.push(h('div', null, [
        h('b', '退款时间: '),
        h('span', row.refund_time),
      ]))
    }
    return children
  }
}, {
  title: '体检信息',
  key: 'appointment',
  render(row) {
    let children = [
      h('div', null, [
        h('b', '预约时间: '),
        h('span', row.appointment_time),
      ]),
      h('div', null, [
        h('b', '预约编号: '),
        h('span', !!row.appointment_number ? row.appointment_number : '-'),
      ]),
      h('div', null, [
        h('b', '到检状态: '),
        h(
          NTag,
          {
            size: 'small',
            type: row.check_status === 2 ? 'success' : 'error'
          },
          {
            default: () => {
              return row.check_status === 2 ? '已到检' : '未到检'
            }
          }
        ),
      ]),
    ]
    if (row.check_status === 2) {
      children.push(h('div', null, [
        h('b', '到检时间: '),
        h('span', row.check_time),
      ]))
    }
    if (!!row.exam_number) {
      children.push(h('div', null, [
        h('b', '体检编号: '),
        h('span', row.exam_number),
      ]))
    }
    children.push(h('div', null, [
      h('b', '介绍人: '),
      h('span', row.referral ? row.referral : '-'),
    ]))
    return children
  }
}]

const pagePush = () => {
  $router.push({
    query: page_options.value
  })
}

const searchClick = () => {
  updatePage(1)
}
const updatePage = (page) => {
  page_options.value.page = page
  pagePush()
}
const clearSearchClick = () => {
  $router.push({
    query: JSON.parse(JSON.stringify({
      ...default_page_options
    }))
  })
}
const refund_show = ref(false)
const refund_type = ref(1)
const RefundShow = (type) => {
  if (user_order_active.value.length === 0) return window.$message().error('请选择一个订单')
  refund_type.value = type
  refund_show.value = true
}
const UserOrderRefund = async () => {
  const response = await UserOrderRefundAction({
    id: user_order_active.value[0],
    type: refund_type.value
  })
  $response(response, () => {
    window.$message().success('操作成功')
    refund_show.value = false
    UserOrderList()
  })
}
const cancel_show = ref(false)
const cancel_type = ref(1)
const CancelShow = (type) => {
  if (user_order_active.value.length === 0) return window.$message().error('请选择一个订单')
  cancel_type.value = type
  cancel_show.value = true
}
const UserOrderCancel = async () => {
  const response = await UserOrderCancelAction({
    id: user_order_active.value[0],
    type: cancel_type.value
  })
  $response(response, () => {
    window.$message().success('操作成功')
    cancel_show.value = false
    UserOrderList()
  })
}
</script>
<template>
  <div>
    <n-modal v-model:show="cancel_show" preset="card" :style="{width: '400px'}"
             :title="`取消${cancel_show === 2 ? '订单' : '预约'}确认`" :auto-focus="false"
             :bordered="false">
      <div>
        <n-space justify="center">
          <n-button @click="UserOrderCancel()" type="info">确定</n-button>
          <n-button @click="cancel_show = false">取消</n-button>
        </n-space>
      </div>
    </n-modal>
    <n-modal v-model:show="refund_show" preset="card" :style="{width: '400px'}"
             :title="`退款${refund_type === 2 ? '&取消预约' : ''}确认`" :auto-focus="false"
             :bordered="false">
      <div>
        <n-space justify="center">
          <n-button @click="UserOrderRefund()" type="info">确定</n-button>
          <n-button @click="refund_show = false">取消</n-button>
        </n-space>
      </div>
    </n-modal>

    <n-card title="订单管理">
      <div>
        <n-space align="center">
          <n-tag>
            <div class="form_tag_wrapper">时间类型</div>
          </n-tag>
          <n-select class="form_input_wrapper" v-model:value="page_options.time"
                    :options="[
                      {value:1,label:'创建时间'},
                      {value:2,label:'支付时间'},
                      {value:3,label:'预约时间'},
                    ]"/>
          <n-tag>
            <div class="form_tag_wrapper">开始时间</div>
          </n-tag>
          <n-date-picker v-model:formatted-value="page_options.start_time" type="datetime"/>
          <n-tag>
            <div class="form_tag_wrapper">结束时间</div>
          </n-tag>
          <n-date-picker v-model:formatted-value="page_options.end_time" type="datetime"/>
        </n-space>
        <n-space mt-2 align="center">
          <n-tag>
            <div class="form_tag_wrapper">搜索</div>
          </n-tag>
          <n-input class="form_input_wrapper" v-model:value="page_options.search" placeholder="身份证、手机号、订单号"/>
          <n-tag>
            <div class="form_tag_wrapper">状态</div>
          </n-tag>
          <n-radio-group v-model:value="page_options.status" name="status_radio">
            <n-space>
              <n-radio :value="0">全部</n-radio>
              <n-radio v-for="(i,k) in status_arr" :key="k" :value="k+1">{{ i }}</n-radio>
            </n-space>
          </n-radio-group>
          <n-button @click="searchClick()" type="info">搜索</n-button>
          <n-button @click="clearSearchClick()" type="warning">清空</n-button>
        </n-space>
        <n-space mt-2>
          <n-button v-if="false" @click="RefundShow(1)" type="error">退款</n-button>
          <n-button v-if="false" @click="CancelShow(1)" type="warning">取消预约</n-button>
          <n-button @click="RefundShow(2)" type="error">退款&取消预约</n-button>
          <n-button @click="CancelShow(2)" type="warning">取消订单</n-button>
        </n-space>
        <n-data-table mt-2 striped v-model:checked-row-keys="user_order_active"
                      :columns="user_order_columns"
                      :row-key="row=>row.id" :data="user_order_list"/>
        <n-pagination v-if="user_order_list_last_page > 1" @update:page="updatePage" mt-2
                      v-model:page="page_options.page"
                      :page-count="user_order_list_last_page"/>
      </div>
    </n-card>
  </div>
</template>
<style>
.line_wrapper {
  display: flex;
}

.items_content_wrapper {
  width: 200px;
}
</style>
<style scoped>
.op0 {
  opacity: 0;
}

.date_box_wrapper {
  background: #ffffff;
  margin-top: 2px;
  cursor: pointer;
  border-radius: 6px;
}

.month_wrapper {
  display: flex;
}

.month_box_title_wrapper {
  height: 40px;
  line-height: 40px;
  font-size: 20px;
  background: #00000005;
}

.month_box_wrapper {
  background: #00000010;
  border: 1px #00000010 solid;
  text-align: center;
  border-radius: 6px;
  overflow: hidden;
}

.form_checkbox_wrapper {
  width: 300px;
}

.create {
  background: #4b9d5f60;
}
</style>
<route>
{"meta":{"title":"订单管理"}}
</route>

