<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="订单编号">
                <a-input v-model="queryParam.id" placeholder="请输入"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="申请打包的物流单号">
                <a-input v-model="queryParam.tracking_no" placeholder="请输入"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="国际物流单号">
                <a-input v-model="queryParam.new_tracking_no" placeholder="请输入"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="唛头">
                <a-input v-model="queryParam.member_id" placeholder="请输入"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="订单状态">
                <!-- 5拆包中 10 未付款  20待发货  29已发货  30已完成 -->
                <a-select v-model="queryParam.status" placeholder="请选择" default-value="0">
                  <a-select-option value="0">全部</a-select-option>
                  <a-select-option value="5">拆包中</a-select-option>
                  <a-select-option value="10">未付款</a-select-option>
                  <a-select-option value="20">待发货</a-select-option>
                  <a-select-option value="29">已发货</a-select-option>
                  <a-select-option value="30">已完成</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="!advanced && 8 || 24" :sm="24">
              <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => { this.queryParam = {}; this.$refs.table.refresh(true) }">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <!-- <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd">入库</a-button>
      </div> -->

      <s-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns"
        :data="loadData"
        showPagination="auto"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="status" slot-scope="text">
          <a-badge :status="text | statusTypeFilter" :text="text | statusFilter" />
        </span>
        <span slot="description" slot-scope="text">
          <ellipsis :length="4" tooltip>{{ text }}</ellipsis>
        </span>
        <span slot="package" slot-scope="text, record">
          <template>
            <!-- 假设 text 是你传递的对象或数组 -->
            <div v-for="(item, index) in record.package" :key="index">
              {{ item.tracking_no }} （{{ item.item_names }}）
            </div>
          </template>
        </span>
        <span slot="address" slot-scope="text, record">
          <template>
            <!-- 假设 text 是你传递的对象或数组 -->
            <div v-if="record.address">收件人： {{ record.address.receiver_name }}</div>
            <div v-if="record.address">手机号： {{ record.address.receiver_phone }}</div>
            <div v-if="record.address">国家： {{ record.address.receiver_country }}</div>
            <div v-if="record.address">城市： {{ record.address.receiver_city }}</div>
            <div v-if="record.address">详情地址： {{ record.address.receive_address }}</div>
            <div v-if="record.address">邮编： {{ record.address.receiver_zip_code }}</div>
          </template>
        </span>

        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleSub(record)">详情</a>
            <a-divider v-if="record && (record.order_status === 5 || record.order_status === 20 || record.order_status === 29)" type="vertical" />
            <a @click="handleEdit(record)" v-if="record && (record.order_status === 5 || record.order_status === 20 || record.order_status === 29)">
              {{ record.order_status === 5 ? '打包完成' : (record.order_status === 20 ? '已发货':(record.order_status === 29 ? '完成':'')) }}</a>
          </template>
        </span>
      </s-table>
      <!-- 发货 -->
      <delivery-form
        ref="deliveryModal"
        :visible="visibleDelivery"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
        @ok="deliveryOk"
      />
      <!-- 订单详情 -->
      <detail-form
        ref="detailModal"
        :visible="visibleDetail"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
      />
      <!-- 包裹入库 -->
      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleOk"
      />
      <step-by-step-modal ref="modal" @ok="handleOk"/>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import { getOrderList, packageWarehousing, delivery, complete, packComplete } from '@/api/manage'

import StepByStepModal from './modules/StepByStepModal'
import CreateForm from './modules/CreateForm'
import deliveryForm from './modules/deliveryForm'
import detailForm from './modules/detailForm'

const columns = [
  {
    title: '订单id',
    dataIndex: 'id'
  },
  {
    title: '订单号',
    dataIndex: 'order_sn'
  },
  {
    title: '物流',
    dataIndex: 'line.name'
  },
  {
    title: '用户打包备注',
    dataIndex: 'pack_remark'
  },
  {
    title: '唛头',
    dataIndex: 'member_id'
  },
  {
    title: '名称',
    dataIndex: 'pack_item_name'
  },
  {
    title: '申请包裹列表',
    dataIndex: 'package',
    scopedSlots: { customRender: 'package' }
  },
  {
    title: '收件人信息',
    dataIndex: 'address',
    scopedSlots: { customRender: 'address' }
  },
 // {
//    title: '订单金额',
 //   dataIndex: 'order_amount'
    // scopedSlots: { customRender: 'description' }
//  },
  // {
  //   title: '服务调用次数',
  //   dataIndex: 'callNo',
  //   sorter: true,
  //   needTotal: true,
  //   customRender: (text) => text + ' 次'
  // },
  // {
  //   title: '订单状态',
  //   dataIndex: 'status',
  //   scopedSlots: { customRender: 'status' }
  // },
  {
    title: '订单状态',
    dataIndex: 'order_status_text'
  },
  {
    title: '支付状态',
    dataIndex: 'pay_status_text'
  },
  {
    title: '申请打包时间',
    dataIndex: 'create_time',
    sorter: true
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' }
  }
]
// 5拆包中 10 未付款  20待发货  29已发货  30已完成
const statusMap = {
  0: {
    status: 'default',
    text: '拆包中'
  },
  1: {
    status: 'processing',
    text: '待发货'
  },
  2: {
    status: 'success',
    text: '已完成'
  },
  3: {
    status: 'error',
    text: '未付款'
  }
}

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    StepByStepModal,
    deliveryForm,
    detailForm
  },
  data () {
    try {
      console.log('TableList - initializing data')
      this.columns = columns
      return {
        visibleDetail: false,
        // create model
        visibleDelivery: false,
        visible: false,
        confirmLoading: false,
        mdl: null,
        // 高级搜索 展开/关闭
        advanced: false,
        // 查询参数
        queryParam: {},
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          console.log('TableList - loadData called with params:', parameter)
          const requestParameters = Object.assign({}, parameter, this.queryParam)
          // Transform parameter names
          const transformedParams = {
            ...requestParameters,
            page: requestParameters.pageNo,
            page_size: requestParameters.pageSize,
            order_status: requestParameters.status ? requestParameters.status : '',
            order_sn: requestParameters.id
          }
          // Remove original parameters
          delete transformedParams.pageNo
          delete transformedParams.pageSize
          console.log('TableList - loadData request parameters:', transformedParams)
          return getOrderList(transformedParams)
            .then(res => {
              console.log('TableList - loadData response:', res)
              if (!res || !res.data || !res.data.list) {
                console.error('TableList - loadData invalid response:', res)
                return {
                  data: [],
                  pageSize: parameter.pageSize,
                  pageNo: parameter.pageNo,
                  totalCount: 0
                }
              }
              return {
                data: res.data.list,
                pageSize: parameter.pageSize,
                pageNo: parameter.pageNo,
                totalCount: res.data.count || res.data.list.length
              }
            })
            .catch(error => {
              console.error('TableList - loadData error:', error)
              return {
                data: [],
                pageSize: parameter.pageSize,
                pageNo: parameter.pageNo,
                totalCount: 0
              }
            })
        }
      }
    } catch (error) {
      console.error('TableList - data initialization error:', error)
      return {}
    }
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    }
  },
  computed: {
  },
  methods: {
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    handleEdit (record) {
      this.visibleDelivery = true
      this.mdl = { ...record }
    },
    deliveryOk () {
      const form = this.$refs.deliveryModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        console.log('TableList - loadData response:', values)
        if (!errors) {
          values.order_sn = this.mdl.order_sn
          if (this.mdl.order_status === 20) {
            delivery(values)
            .then(res => {
              if (res) {
                form.resetFields()
              console.log('res', res)
              // this.$message.info('已发货')
              this.visibleDelivery = false
              this.$refs.table.refresh()
              }
            })
            .catch(error => {
              this.$message.error(error.message)
              console.error('TableList - loadData error:', error)
            }).finally(() => {
              this.mdl = null
              this.confirmLoading = false
            })
          } else if (this.mdl.order_status === 29) {
            complete(values)
            .then(res => {
              if (res) {
                form.resetFields()
              console.log('res', res)
              // this.$message.info('已发货')
              this.visibleDelivery = false
              this.$refs.table.refresh()
              }
            })
            .catch(error => {
              this.$message.error(error.message)
              console.error('TableList - loadData error:', error)
            }).finally(() => {
              this.mdl = null
              this.confirmLoading = false
            })
          } else if (this.mdl.order_status === 5) {
            packComplete(values)
            .then(res => {
              if (res) {
                form.resetFields()
              console.log('res', res)
              // this.$message.info('已发货')
              this.visibleDelivery = false
              this.$refs.table.refresh()
              }
            })
            .catch(error => {
              this.$message.error(error.message)
              console.error('TableList - loadData error:', error)
            }).finally(() => {
              this.mdl = null
              this.confirmLoading = false
            })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('TableList - loadData response:', values)
          values.tracking_no_list = values.tracking_no_list
					.split('\n')
					.map(line => line.trim())
					.filter(line => line !== '')

          packageWarehousing(values)
            .then(res => {
              if (res) {
                console.log('TableList - loadData response:', res)
              form.resetFields()
              // this.$message.info('入库成功')
              this.confirmLoading = false
              this.visible = false
              this.$refs.table.refresh()
              }
            })
            .catch(error => {
              console.error('TableList - loadData error:', error)
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false
      this.visibleDelivery = false
      this.visibleDetail = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
      this.mdl = null
    },
    handleSub (record) {
      this.visibleDetail = true
      this.mdl = { ...record }
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.queryParam = {
        date: moment(new Date())
      }
    }
  }
}
</script>
