<script setup lang="tsx">
import { reactive, ref, unref,onMounted } from 'vue'
// import { getOrderList, assignSalesman, getOrderDetail } from '@/api/order'
import { getOrderList, getOrderDetail } from '@/api/order'
import { useTable } from '@/hooks/web/useTable'
import { Table, TableColumn } from '@/components/Table'
import { ContentWrap } from '@/components/ContentWrap'
import { FormSchema } from '@/components/Form'
import { Search } from '@/components/Search'
import { searchTime } from '@/utils/searchTime'
import { searchOrder } from '@/api/order/types'
import { ElTabs, ElTabPane, ElButton, ElDrawer } from 'element-plus'
import Detail from './components/Detail.vue'
import Draft from './components/Draft.vue'
import addItem from './components/addItem.vue'
import {
  getStoreList
} from '@/api/erp'
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getOrderList({
      ...searchParams.value,
      page: unref(currentPage) || 1,
      limit: unref(pageSize) || 10,
      step: unref(activeName) || 0
    })
    return {
      list: res.data.list || [],
      total: res.data.count || 0
    }
  }
})
const { dataList, loading, total, currentPage, pageSize } = tableState
const { getList } = tableMethods
const dialogVisible = ref(false)
const dialogTitle = ref('')

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'id',
    label: 'ID',
    align: 'center',
    width: 70
  },
  {
    field: 'real_name',
    label: '用户',
    minWidth: 100,
    slots: {
      default: (data: any) => {
        const row = data.row
        if (row.uid == 0) {
          return (
            <>
              <div>游客</div>
            </>
          )
        } else {
          return (
          <>
            <div>昵称: {row.real_name}</div>
            <div>UID: {row.uid} </div>
            <div>手机号: {row.user_phone}</div>
          </>
        )
        }
        
      }
    }
  },
  {
    field: 'store',
    label: '门店',
    minWidth: 100,
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <div>{row.store.name}</div>
          </>
        )
      }
    }
  },
  {
    field: 'staff',
    label: '收营员',
    minWidth: 100,
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <div>昵称: {row.staff_name}</div>
            <div>UID: {row.staff_id} </div>
          </>
        )
      }
    }
  },
  {
    field: 'order_id',
    label: '订单号',
    minWidth: 150
  },
  {
    field: 'info',
    label: '商品信息',
    minWidth: 200,
    slots: {
      default: (data: any) => {
        const row = data.row
        const info = row.info.map((item: any) => {
          if (item.is_refund == 1) {
            return (
            <>
              <div >{item.product_name} <ElButton type='text'>{item.cart_num * 1} {item.specs_name}</ElButton><ElButton type='text'>(￥{(item.price*1).toFixed(2)})</ElButton><ElButton type='text' style='color: red;'>(已退款￥{item.refund_price*1})</ElButton></div>
            </>
          )
          } else {
            return (
            <>
              <div>{item.product_name} <ElButton type='text'>{item.cart_num * 1} {item.specs_name}</ElButton><ElButton type='text'>(￥{(item.price*1).toFixed(2)})</ElButton></div>
            </>
          )
          }
          
        })
        return (
          <>
            {info}
          </>
        )
        // return (
        //   <>
        //     <div>{row.pay_time ? row.pay_time_chs : ''}</div>
        //   </>
        // )
      }
    }
  },
  {
    field: 'total_price',
    label: '支付金额',
    minWidth: 100
  },
  {
    field: 'payInfo',
    label: '支付时间',
    minWidth: 100,
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <div>{row.pay_time ? row.pay_time_chs : ''}</div>
          </>
        )
      }
    }
  },
  
  {
    field: 'paytype',
    label: '支付类型',
    minWidth: 100,
    slots: {
      default: (data: any) => {
        const row = data.row
        let pay_type = ''
        switch (row.pay_type) {
          case 'qudou':
            pay_type = '趣豆'
            break
          case 'cash':
            pay_type = '现金'
            break
          case 'card':
            pay_type = '会员卡'
            break
          case 'weixin':
            pay_type = '微信'
            break
          case 'alipay':
            pay_type = '支付宝'
            break
          default:
            pay_type = ''
        }
        return (
          <>
            <div>{pay_type}</div>
          </>
        )
      }
    }
  },
  // pay_type
  {
    field: 'add_time',
    label: '时间',
    minWidth: 160
  },
  {
    field: 'mark',
    label: '备注',
    minWidth: 140
  },
  {
    field: 'refund_price',
    label: '退款金额',
    minWidth: 100,
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <div>{row.refund_price * 1 > 0 ? row.refund_price : ''}</div>
          </>
        )
      }
    }
  },
  {
    field: 'refund_status',
    label: '退款状态',
    minWidth: 100,
    slots: {
      default: (data: any) => {
        const row = data.row
        let pay_type = ''// '0 未退款 1 申请中 2 已退款 3 部分退款',
        switch (row.refund_status) {
          case 0:
            pay_type = ''
            break
          case 1:
            pay_type = '申请中'
            break
          case 2:
            pay_type = '已退款'
            break
          case 3:
            pay_type = '部分退款'
            break
          default:
            pay_type = ''
        }
        return (
          <>
            <div>{pay_type}</div>
          </>
        )
      }
    }
  },
  {
    field: 'refund_reason',
    label: '退款原因',
    minWidth: 100
  }
  // {
  //   field: 'action',
  //   label: '操作',
  //   width: 200,
  //   headerAlign: 'center',
  //   align: 'center',
  //   slots: {
  //     default: (data: any) => {
  //       const row = data.row;
  // 	if(row.add_item.length > 0 && row.add_item[0].status == 0) {
  // 		return (
  // 		  <>
  // 		  <ElButton type="primary" link size="small" onClick={() => action('edit', row)}>详情</ElButton>
  // 		  <ElDivider direction="vertical" />
  // 		  <ElButton type="primary" link size="small" onClick={() => action('auth', row)}>审核增项</ElButton>
  // 		  </>
  // 		)
  // 	}else {
  // 		return (
  // 		  <>
  // 		  <ElButton type="primary" link size="small" onClick={() => action('edit', row)}>详情</ElButton>
  // 		  </>
  // 		)
  // 	}

  //     }
  //   }
  // }
])
const storeLoading = ref(false)
const storeOptions = ref<any[]>([])
  const getStore = async (query = '', id = '') => {
  try {
    storeLoading.value = true
    const res = await getStoreList({ page: 1, limit: 1000, name: query, id, store: 1 })
    if (res) {
      storeOptions.value = res.data.data.map((item) => {
        return {
          value: item.id,
          label: item.name
        }
      })
    } else {
      return []
    }
  } catch (error) {
    console.log(error)
  } finally {
    storeLoading.value = false
  }
}
const searchSchema = reactive<FormSchema[]>([
  {
    field: 'uid',
    label: 'UID',
    component: 'Input',
    componentProps: {
      type: 'number',
      placeholder: '请输入用户UID'
    }
  },
  {
    field: 'real_name',
    label: '用户昵称',
    component: 'Input',
    componentProps: {
      placeholder: '请输入用户昵称'
    }
  },
  {
    field: 'store_id',
    label: '门店',
    component: 'Select',
    value: '',
    componentProps: {
      placeholder: '请选择',
      options: storeOptions
    }
  },
  {
    field: 'pay_type',
    label: '支付方式',
    component: 'Select',
    componentProps: {
      placeholder: '请选择支付方式',
      options: [
        {
          label: '微信',
          value: 'weixin'
        },
        {
          label: '支付宝',
          value: 'alipay'
        },
        {
          label: '会员卡',
          value: 'card'
        },
        {
          label: '现金',
          value: 'cash'
        },
        {
          label: '趣豆',
          value: 'qudou'
        }
      ]
    }
  },
  
  // {
  //   field: 'salesperson_id',
  //   label: '业务员',
  //   component: 'Input',
  //   componentProps: {
  //     type: 'number',
  //     placeholder: '请选择业务员'
  //   }
  // },
  {
    field: 'order_id',
    label: '订单号',
    component: 'Input',
    componentProps: {
      placeholder: '请输入订单号'
    }
  },
  searchTime
])
const searchParams = ref<searchOrder>({
  uid: '',
  real_name: '',
  time: '',
  store_id: '',
  salesperson_id: '',
  step: '',
  order_id: ''
})
const setSearchParams = (data: any) => {
  searchParams.value = data
  const search = searchParams.value
  if (data.time) {
    search.time = data.time.join('-')
  } else {
    search.time = ''
  }
  getList()
}
const activeName = ref(0)
const tabsConfig = reactive([
  {
    title: '',
    total: 0,
    step: 0
  }
  // {
  //   title: '设计师订单',
  //   total: 0,
  //   step: 1
  // },
  // {
  //   title: '商品订单',
  //   total: 0,
  //   step: 2
  // },
  // {
  //   title: '安装订单',
  //   total: 0,
  //   step: 3
  // },
  // {
  //   title: '待评价',
  //   total: 0,
  //   step: 4
  // },
  // {
  //   title: '已完成',
  //   total: 0,
  //   step: 5
  // }
])
const activeNames = ref(0)
const currentRow = ref()
const isEdit = ref(false)
const isAuth = ref(false)
const tabsConfigs = reactive([
  {
    title: '基本信息',
    total: 0,
    step: 0
  },
  {
    title: '设计稿',
    total: 0,
    step: 1
  },
  {
    title: '增项',
    total: 0,
    step: 2
  }
])
const checkedSalesperson = (e) => {
  console.log(e, 'x', e.value)
  currentRow.value.salesperson_id = e.value.id
  currentRow.value.salesperson = e.value
  getList()
}
const checkedDesigner = (e) => {
  console.log(e, 'x', e.value)
  currentRow.value.designer_id = e.value.id
  currentRow.value.designer = e.value
  getList()
}
const passAddItem = () => {
  isAuth.value = false
  // currentRow.value.add_item[0].status = 1
  getList()
}
const action = async (type: string, row?: any) => {
  // actionType.value = type
  // if (type == 'add') {
  //   dialogTitle.value = t('exampleDemo.add')
  //   currentRow.value = undefined
  // }

  //   console.log(currentRow, 'currentRow')
  // }
  const res = await getOrderDetail(row.id)
  if (type == 'edit') {
    isEdit.value = true
    dialogTitle.value = '详情'
    currentRow.value = res.data
    dialogVisible.value = true
  } else if (type == 'auth') {
    isAuth.value = true
    activeNames.value = 2
    dialogTitle.value = '详情'
    currentRow.value = res.data
    dialogVisible.value = true
  }
}
// const goAssignSalesman = async (id:number, data: any) => {
// 	await assignSalesman(id,data)
// }
onMounted(() => {
  getStore()
})
</script>

<template>
  <ContentWrap>
    <ElTabs v-model="activeName" @tab-click="getList">
      <ElTabPane
        v-for="(item, index) in tabsConfig"
        :key="index"
        :label="`${item.title}${item.total > 0 ? `(${item.total})` : ''}`"
        :name="index"
      />
    </ElTabs>
    <div class="max-w-1000px">
      <Search isCol :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
    </div>
    <div class="mb-10px"> </div>
    <Table
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :columns="tableColumns"
      default-expand-all
      node-key="id"
      stripe
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
      :pagination="{
        total
      }"
    />
  </ContentWrap>

  <ElDrawer v-model="dialogVisible" direction="rtl" size="50%">
    <!-- // :title="dialogTitle" -->
    <template #header="{ titleId, titleClass }">
      <h4 :id="titleId" :class="titleClass">{{ dialogTitle }}</h4>
      <!-- <el-button type="danger" @click="close">
	        <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
	        Close
	      </el-button> -->
    </template>
    <ElTabs v-model="activeNames">
      <ElTabPane
        v-for="(item, index) in tabsConfigs"
        :key="index"
        :label="`${item.title}${item.total > 0 ? `(${item.total})` : ''}`"
        :name="index"
      />
    </ElTabs>
    <Detail
      v-if="activeNames === 0"
      :current-row="currentRow"
      :isEdit="isEdit"
      @checkedSalesperson="checkedSalesperson"
      @checkedDesigner="checkedDesigner"
    />
    <Draft v-if="activeNames === 1" :current-row="currentRow" />
    <addItem
      v-if="activeNames === 2"
      :current-row="currentRow"
      :isAuth="isAuth"
      @passAddItem="passAddItem"
    />
  </ElDrawer>
</template>
