<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { objectClean } from '@/utils';
import { fetchQueryChannelList, fetchQueryHumanDoctorOrderList, fetchUpdateHumanDoctorOrderStatus, fetchQueryHumanDoctorOrderDetail, fetchQueryHumanDoctorOrderRecord } from '@/service/api';
import { Icon } from '@iconify/vue';
import {PAGINATION_PAGE_SIZES} from '@/const/index'

const orderStatusOptions = [
  { label: '待支付', value: '00' },
  // { label: '支付中', value: '01' },
  { label: '待联系客服', value: '02' },
  { label: '咨询中', value: '03' },
  { label: '订单完成', value: '04' },
  { label: '已关闭', value: '05' }
]

// 应用类型 01:h5 02:公众号 3:微信小程序 04:支付宝-h5 05:支付宝小程序	
const appTypeOptions = [
  { label: 'h5', value: '01' },
  { label: '公众号', value: '02' },
  { label: '微信小程序', value: '03' },
  { label: '支付宝-h5', value: '04' },
  { label: '支付宝小程序', value: '05' },
]

const channelOptions = ref([])

const pagination = ref({
  pageSize: 10,
  itemCount: 0,
  pageNum: 1
});
function handlePageUpdate(page: number) {
  pagination.value.pageNum = page;
  getListData();
}
function handlePageSizeUpdate(pageSize: number) {
  pagination.value.pageNum = 1;
  pagination.value.pageSize = pageSize;
  getListData();
}

function createQueryParams() {
  return {
    orderId: '',
    mobile: '',
    createTime: null,
    startCreateTime: '',
    endCreateTime: '',
    orderStatus: null,
    appType: null,
    channelCode: null
  };
}

/** 检索 */
function handleQuery() {
  getListData();
}
/** 重置检索 */
function handleResetQuery() {
  queryParams.value = { ...createQueryParams() };
  getListData();
}


const listData = ref([]);

const queryParams = ref(createQueryParams());

const loading = ref(false);

async function getListData() {
  loading.value = true;
  const { pageNum, pageSize } = pagination.value;
  const { orderId, mobile, createTime, orderStatus, appType, channelCode } = queryParams.value;
  const params = {
    orderId,
    mobile,
    orderStatus,
    appType,
    channelCode,
    startCreateTime: createTime ? `${createTime[0]} 00:00:00` : '',
    endCreateTime: createTime ? `${createTime[1]} 23:59:59` : '',
    pageNum,
    pageSize
  };
  const { data } = await fetchQueryHumanDoctorOrderList(objectClean(params));
  if (data?.ok) {
    listData.value = data.data.records;
    pagination.value.itemCount = data.data.total;
  }
  loading.value = false;
}

async function getChannelList() {
  const res = await fetchQueryChannelList({
    pageNum: 1,
    pageSize: 100
  })
  console.log(res)
  if(res.data) {
    channelOptions.value = res.data?.data?.records || []
  }
}

function filterOrderStatus(value: string) {
  const item = orderStatusOptions.find((item) => item.value === value);
  return item ? item.label : '';
}
function filterAppType(value: string) {
  const item = appTypeOptions.find((item) => item.value === value);
  return item ? item.label : '';
}
const showDetailModel = ref(false)
const curentRecord = ref<any>([
  {
    content: '问宠医',
    time: ''
  },
  {
    content: '支付费用',
    time: ''
  },
  {
    content: '进入咨询',
    time: ''
  },
  {
    content: '已完成',
    time: ''
  }
])
const showUpdateModal = ref(false)
const currentRow = ref<any>({})
async function handleShowModal(row: any, type: string) {
  currentRow.value = row
  if(type === 'update:status') {
    showUpdateModal.value = true
  } else {
    const params = {
      orderId: row.orderId
    }
    const res = await Promise.all([fetchQueryHumanDoctorOrderDetail(params), fetchQueryHumanDoctorOrderRecord(params)])
    if(res[0].data.ok && res[1].data.ok) {
      currentRow.value = {
        ...res[0].data.data
      }
      // currentStatus
      const step1 = res[1].data.data.find((item: any) => item.currentStatus === '01')
      curentRecord.value[0].time = step1?.createTime || ''
      const step2 = res[1].data.data.find((item: any) => item.currentStatus === '02')
      curentRecord.value[1].time = step2?.createTime || ''
      const step3 = res[1].data.data.find((item: any) => item.currentStatus === '03')
      curentRecord.value[2].time = step3?.createTime || ''
      const step4 = res[1].data.data.find((item: any) => item.currentStatus === '04')
      curentRecord.value[3].time = step4?.createTime || ''

      console.log(currentRow.value, '测试')
      showDetailModel.value = true
    }
  }
}

const updateLoading = ref(false)
const remark = ref('')
const doctorName = ref('')
const medicalRecord = ref('')
async function updateOrderStatus() {
  updateLoading.value = true
  let params = {}
  if(currentRow.value.orderStatus === '02') {
    // 更新为咨询中
    params = {
      orderId: currentRow.value.orderId,
      orderStatus: '03',
      remark: remark.value
    }
  }
  if(currentRow.value.orderStatus === '03') {
    if(doctorName.value.trim() === '') {
       window.$message?.error('接诊医生不能为空');
       updateLoading.value = false
       return
    }
    // 更新为订单完成
    params = {
      orderId: currentRow.value.orderId,
      orderStatus: '04',
      doctorName: doctorName.value,
      medicalRecord: medicalRecord.value
    }
  }
  const res = await fetchUpdateHumanDoctorOrderStatus(params)
  if(res.data.ok) {
    window.$message?.success('更新成功');
    showUpdateModal.value = false
    getListData()
  }
  updateLoading.value = false
}

onMounted(() => {
  getListData();
  getChannelList()
});
</script>
<template>
  <div>
    <n-card class="h-full shadow-sm rounded-8px">
      <n-grid cols="1 s:2 m:3 l:4 xl:5 2xl:6" responsive="screen" x-gap="12" y-gap="12">
          <n-grid-item>
            <p class="mb-6px">订单编号：</p>
            <n-input clearable v-model:value="queryParams.orderId" placeholder="订单编号"></n-input>
          </n-grid-item>
          <n-grid-item>
            <p class="mb-6px">订单状态：</p>
            <n-select v-model:value="queryParams.orderStatus" clearable placeholder="订单状态" :options="orderStatusOptions" />
          </n-grid-item>
          <n-grid-item>
            <p class="mb-6px">下单平台：</p>
            <n-select v-model:value="queryParams.appType" clearable placeholder="下单平台" :options="appTypeOptions" />
          </n-grid-item>
          <n-grid-item>
            <p class="mb-6px">渠道来源：</p>
            <n-select 
              label-field="channelName"
              value-field="channelCode"
              v-model:value="queryParams.channelCode" clearable placeholder="渠道来源" :options="channelOptions" />
          </n-grid-item>
          <n-grid-item>
            <p class="mb-6px">手机号：</p>
            <n-input clearable v-model:value="queryParams.mobile" placeholder="手机号"></n-input>
          </n-grid-item>
          <n-grid-item>
            <p class="mb-6px">创建时间：</p>
            <n-date-picker
              v-model:formatted-value="queryParams.createTime"
              :actions="[]"
              close-on-select
              value-format="yyyy-MM-dd"
              placeholder="创建时间"
              type="daterange"
              start-placeholder="开始"
              end-placeholder="结束"
              clearable
            />
          </n-grid-item>
          <n-grid-item class="flex items-end">
            <n-space>
              <n-button secondary strong type="primary" @click="handleQuery"> 查 询 </n-button>
              <n-button secondary strong @click="handleResetQuery">重 置</n-button>
            </n-space>
          </n-grid-item>
        </n-grid>
    </n-card>

    <n-card class="shadow-sm rounded-8px mt-12px">
      <n-spin :show="loading">
        <vxe-table
          :column-config="{ resizable: true }"
          :seq-config="{ startIndex: (pagination.pageNum - 1) * pagination.pageSize }"
          auto-resize
          :row-config="{ isHover: true }"
          stripe
          border
          :data="listData"
        >
        <vxe-column type="seq" title="序号" width="60"></vxe-column>
        <vxe-column min-width="200" field="orderId" title="订单编号"></vxe-column>
        <vxe-column min-width="120" field="mobile" title="手机号"></vxe-column>
        <vxe-column min-width="120" field="realPrice" title="订单金额">
          <template #default="{row}">
            ￥{{ row.realPrice }}
          </template>
        </vxe-column>
        <vxe-column min-width="120" field="orderStatus" title="订单状态">
          <template #default="{row}">
            <n-tag round :bordered="false" type="warning" v-if="row.orderStatus === '00'">
              {{ filterOrderStatus(row.orderStatus) }}
            </n-tag>
            <n-tag round :bordered="false" type="primary" v-else-if="row.orderStatus === '02'">
              {{ filterOrderStatus(row.orderStatus) }}
            </n-tag>
            <n-tag round :bordered="false" :color="{ color: 'rgba(32, 128, 240, 0.12)', textColor: '#2080f0' }"  v-else-if="row.orderStatus === '03'">
              {{ filterOrderStatus(row.orderStatus) }}
              </n-tag>
            <n-tag round :bordered="false" type="success" v-else-if="row.orderStatus === '04'">
              {{ filterOrderStatus(row.orderStatus) }}
            </n-tag>
            <n-tag round :bordered="false" v-else-if="row.orderStatus === '05'">
              {{ filterOrderStatus(row.orderStatus) }}
            </n-tag>
            <span v-else>{{ filterOrderStatus(row.orderStatus) }}</span>
          </template>
        </vxe-column>
        <vxe-column min-width="200" field="createTime" title="订单创建时间"></vxe-column>
        <vxe-column min-width="200" field="updateTime" title="最近操作时间"></vxe-column>
        <vxe-column min-width="200" field="channelName" title="渠道来源"></vxe-column>
        <vxe-column min-width="200" field="appType" title="下单平台">
          <template #default="{row}">
            <span>{{ filterAppType(row.appType || '') }}</span>
          </template>
        </vxe-column>
        <vxe-column field="title" title="操作" fixed="right" min-width="120">
          <template #default="{ row }">
            <n-space>
              <n-button
                  strong
                  text
                  type="info"
                  @click="handleShowModal(row, 'view')"
                  >详情</n-button
                >
              <n-button
                  v-if="row.orderStatus === '02' || row.orderStatus === '03'"
                  strong
                  text
                  type="info"
                  @click="handleShowModal(row, 'update:status')"
                  >更新状态</n-button
                >
            </n-space>
          </template>
        </vxe-column>
        <template #empty>
          <icon-custom-empty-data class="text-320px text-primary" />
        </template>
      </vxe-table>
      </n-spin>
      <div v-if="pagination.itemCount !== 0" class="w-full flex justify-end mt-4">
        <n-pagination
          v-model:page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :item-count="pagination.itemCount"
          :page-sizes="PAGINATION_PAGE_SIZES"
          :on-update:page="handlePageUpdate"
          :on-update:page-size="handlePageSizeUpdate"
          show-size-picker
        >
        <template #prefix="{ itemCount, startIndex }">
          <div class="text-[#333]">共 <span class="text-primary">{{ pagination.itemCount }}</span> 条</div>
        </template>
      </n-pagination>
      </div>
    </n-card>

    <n-modal v-model:show="showUpdateModal" :mask-closable="false" :bordered="false">
      <n-card title="更新订单状态" class="w-600px rounded-8px shadow-sm">
        <template #header-extra>
          <Icon icon="ic:sharp-close" class="text-size-22px cursor-pointer" @click="showUpdateModal = false" />
        </template>
        <div>
          <n-descriptions label-style="min-width: 120px" size="small" :column="1" bordered label-placement="left">
            <n-descriptions-item label="订单编号">
              {{ currentRow?.orderId }}
            </n-descriptions-item>
            <n-descriptions-item label="手机号">
              {{ currentRow?.mobile }}
            </n-descriptions-item>
            <n-descriptions-item label="当前状态">
              <n-tag round :bordered="false" type="primary" v-if="currentRow?.orderStatus === '02'">
                {{ filterOrderStatus(currentRow?.orderStatus) }}
              </n-tag>
              <n-tag round :bordered="false" :color="{ color: 'rgba(32, 128, 240, 0.12)', textColor: '#2080f0' }"  v-if="currentRow?.orderStatus === '03'">
                咨询中
              </n-tag>
            </n-descriptions-item>
            <n-descriptions-item label="状态更新为">
              <n-tag round :bordered="false" :color="{ color: 'rgba(32, 128, 240, 0.12)', textColor: '#2080f0' }"  v-if="currentRow?.orderStatus === '02'">
                咨询中
              </n-tag>
              <n-tag round :bordered="false" type="success" v-if="currentRow.orderStatus === '03'">
                已完成
              </n-tag>
            </n-descriptions-item>
            <n-descriptions-item label="其他备注" v-if="currentRow.orderStatus === '02'">
              <n-input
                v-model:value="remark"
                maxlength="100"
                placeholder="请输入"
                show-count 
                clearable
                type="textarea"
                size="small"
              />
            </n-descriptions-item>
            <n-descriptions-item label="接诊医生*" v-if="currentRow.orderStatus === '03'">
              <n-input
                v-model:value="doctorName"
                placeholder="请输入"
                clearable
              />
            </n-descriptions-item>
            <n-descriptions-item label="病例情况" v-if="currentRow.orderStatus === '03'">
              <n-input
                v-model:value="medicalRecord"
                maxlength="100"
                placeholder="请输入"
                show-count 
                clearable
                type="textarea"
                size="small"
              />
            </n-descriptions-item>
          </n-descriptions>
        </div>
        <template #footer>
          <div class="w-full flex justify-center">
            <NButton @click="showUpdateModal = false">取消</NButton>
            <NButton :loading="updateLoading" class="ml-4" type="primary" @click="updateOrderStatus">确定</NButton>
          </div>
        </template>
      </n-card>
    </n-modal>

    <n-modal v-model:show="showDetailModel" :mask-closable="false" :bordered="false">
      <n-card title="订单详情" class="w-800px rounded-8px shadow-sm">
        <template #header-extra>
          <Icon icon="ic:sharp-close" class="text-size-22px cursor-pointer" @click="showDetailModel = false" />
        </template>
        <div>
        <n-descriptions label-style="min-width: 120px" size="small" :column="1" bordered label-placement="left">
          <n-descriptions-item label="订单编号">
            {{ currentRow?.orderId }}
          </n-descriptions-item>
          <n-descriptions-item label="手机号">
            {{ currentRow?.mobile }}
          </n-descriptions-item>
          <n-descriptions-item label="订单创建时间">
            {{ currentRow?.createTime }}
          </n-descriptions-item>
          <n-descriptions-item label="订单支付金额">
            ￥ {{ currentRow?.realPrice }}
          </n-descriptions-item>
          <n-descriptions-item label="订单支付时间">
            {{ currentRow?.payEndTime }}
          </n-descriptions-item>
          <n-descriptions-item label="订单流转">
            <n-timeline horizontal>
              <n-timeline-item
                :line-type="item.time ? 'default' : 'dashed'"
                v-for="(item, index) in curentRecord"
                :key="index"
                :type="item.time ? 'success' : 'default'"
                :title="item.content"
                :time="item.time"
              />
            </n-timeline>
          </n-descriptions-item>
          <n-descriptions-item label="接诊医生">
            {{ currentRow?.doctorName || '-' }}
          </n-descriptions-item>
          <n-descriptions-item label="病历情况">
            {{ currentRow?.medicalRecord || '-' }}
          </n-descriptions-item>
          <n-descriptions-item label="渠道来源">
            {{ currentRow?.channelName || '-' }}
          </n-descriptions-item>
          <n-descriptions-item label="下单平台">
            <span>{{ filterAppType(currentRow.appType || '-') }}</span>
          </n-descriptions-item>
          <n-descriptions-item label="其他备注">
            {{ currentRow?.remark || '-' }}
          </n-descriptions-item>
        </n-descriptions>
      </div>
      </n-card>
    </n-modal>
  </div>
</template>
