<template>
  <!-- 数据订单 -->
  <div class="pa-3 white">
    <m-filter :option="filter" @search="handleSearch" />
    <table-list
      class="mt-3"
      :loading="loading"
      :headers="headers"
      :items="items"
      :total="total"
      :page-info="pageInfo"
      :is-tools="true"
      :disable-sort="true"
      :can-delete="false"
      :show-select="false"
      @add="handleAdd"
      @pageHandleChange="pageHandleChange"
    >
      <template #status="{ item }">
        <v-chip :color="getStatusColor(item.status)" small>{{ item.status_label }}</v-chip>
      </template>
      <template #can_connect="{ item }">
        <v-icon v-if="item.can_connect === true" color="success" small>mdi-check-circle</v-icon>
        <v-icon v-else-if="item.can_connect === false" color="error" small>mdi-close-circle</v-icon>
        <span v-else>-</span>
      </template>
      <template #created_at="{ item }">
        <span>{{ formatDateTime(item.created_at) }}</span>
      </template>
      <template #actions="{ item }">
        <v-btn text color="primary" @click="handleDetail(item)">详情</v-btn>
        <v-btn
          v-if="canEdit(item.status)"
          text
          color="primary"
          @click="handleAdd(item)"
        >
          编辑
        </v-btn>
        <v-btn v-if="canDelete(item.status)" text color="error" @click="handleDelete(item)">删除</v-btn>
      </template>
    </table-list>

    <!-- 创建、编辑订单对话框 -->
    <edit-dialog
      :visible.sync="createDialog.show"
      :title="createDialog.itemData.id ? '编辑数据订单' : '创建数据订单'"
      :footer="true"
      @submit="handleCreateSuccess"
      @close="handleCloseCreateDialog"
    >
      <OrderForm v-if="createDialog.show" ref="editFormRef" :item-data="createDialog.itemData" />
    </edit-dialog>

    <!-- 订单详情对话框 -->
    <edit-dialog
      :visible.sync="detailDialog.show"
      title="订单详情"
      :footer="false"
      @close="detailDialog.show = false"
    >
      <OrderDetailDialog
        v-if="detailDialog.show"
        :order-id="detailDialog.orderId"
        @refresh="init"
        @reject="handleRejectFromDetail"
        @close="detailDialog.show = false"
      />
    </edit-dialog>

    <!-- 驳回订单对话框 -->
    <reject-order-dialog
      :visible.sync="rejectDialog.show"
      :order-id="rejectDialog.orderId"
      @success="handleRejectSuccess"
    />
  </div>
</template>

<script>
import EditDialog from '@/components/Dialog'
import MFilter from '@/components/Filter'
import TableList from '@/components/List/table'
import OrderForm from './components/OrderForm'
import OrderDetailDialog from './components/OrderDetailDialog'
import RejectOrderDialog from './components/RejectOrderDialog'
import { api } from '@/api/dataOrder'
import { formatDate } from '@/utils/date'

export default {
  name: 'dataOrder',
  components: {
    MFilter,
    TableList,
    OrderForm,
    OrderDetailDialog,
    RejectOrderDialog,
    EditDialog
  },
  data () {
    return {
      api,
      loading: false,
      filter: {
        list: [
          { type: 'textField', value: '', label: '关键词', key: 'search', placeholder: '搜索订单标题或描述' },
          {
            type: 'select',
            value: null,
            label: '状态',
            key: 'status',
            items: [
              { label: '全部', value: null },
              { label: '待处理', value: 'pending' },
              { label: '分析中', value: 'analyzing' },
              { label: '待审批', value: 'pending_approval' },
              { label: '加工中', value: 'processing' },
              { label: '数据产品就绪', value: 'onboard' },
              { label: '已完成', value: 'completed' },
              { label: '已驳回', value: 'rejected' },
              { label: '待补充', value: 'need_supplement' },
              { label: '待人工处理', value: 'manual_review' }
            ],
            itemText: 'label',
            itemValue: 'value'
          }
        ]
      },
      headers: [
        { text: '订单编号', value: 'order_no' },
        { text: '标题', value: 'title' },
        { text: '状态', value: 'status' },
        { text: '可连通', value: 'can_connect' },
        { text: '创建人', value: 'created_by' },
        { text: '创建时间', value: 'created_at' },
        { text: '操作', value: 'actions' }
      ],
      items: [],
      total: 0,
      pageInfo: {
        size: 20,
        current: 1
      },
      query: {},
      createDialog: {
        show: false,
        itemData: {}
      },
      detailDialog: {
        show: false,
        orderId: null
      },
      rejectDialog: {
        show: false,
        orderId: null
      }
    }
  },
  created () {
    this.init()
  },
  methods: {
    async init () {
      this.loading = true
      try {
        const params = {
          page: this.pageInfo.current,
          page_size: this.pageInfo.size,
          ...this.query
        }
        // 移除空值
        Object.keys(params).forEach(key => {
          if (params[key] === '' || params[key] === null || params[key] === undefined) {
            delete params[key]
          }
        })
        const { data } = await api.getOrders(params)
        this.total = data.pagination.total
        this.items = data.list
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.loading = false
      }
    },
    handleSearch (obj) {
      Object.assign(this.query, obj)
      this.pageInfo.current = 1
      this.init()
    },
    pageHandleChange (index) {
      this.pageInfo.current = index
      this.init()
    },
    // 订单详情
    handleDetail (item) {
      this.detailDialog.orderId = item.id
      this.detailDialog.show = true
    },
    // 分析订单
    async handleAnalyze (item) {
      try {
        const { data } = await api.analyzeOrder(item.id)
        if (data.can_connect) {
          this.$snackbar.success('分析完成，实体可连通！')
        } else {
          this.$snackbar.warning('分析完成，部分实体无法连通')
        }
        this.detailDialog.show = false
        this.init()
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    // 审批订单
    // async handleApprove (item) {
    //   try {
    //     await api.approveOrder(item.id)
    //     this.$snackbar.success('审批通过')
    //     this.detailDialog.show = false
    //     this.init()
    //   } catch (error) {
    //     if (error !== 'cancel') {
    //       this.$snackbar.error(error)
    //     }
    //   }
    // },
    // 驳回订单
    handleReject (item) {
      this.rejectDialog.orderId = item.id
      this.rejectDialog.show = true
    },
    handleRejectSuccess () {
      this.init()
      this.detailDialog.show = false
    },
    // 删除订单
    async handleDelete (item) {
      try {
        await this.$confirm('删除确认', `确定要删除订单 "${item.title}" 吗？此操作不可恢复。`)
        await api.deleteOrder(item.id)
        this.$snackbar.success('删除成功')
        this.init()
      } catch (error) {
        if (error !== 'cancel') {
          this.$snackbar.error(error)
        }
      }
    },
    // 创建、编辑订单
    async handleCreateSuccess () {
      const params = this.$refs.editFormRef.getValue()
      if (!params) {
        this.$snackbar.warning('请填写完整订单信息')
        return
      }
      try {
        if (this.createDialog.itemData.id) {
          await api.updateOrder(this.createDialog.itemData.id, params)
          this.$snackbar.success('订单更新成功')
        } else {
          await api.createOrder(params)
          this.$snackbar.success('订单创建成功')
        }
        this.handleCloseCreateDialog()
        this.init()
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    handleCloseCreateDialog () {
      this.createDialog.show = false
      this.createDialog.itemData = {}
    },
    // 分析订单
    // handleAnalyzeFromDetail (orderId) {
    //   const item = this.items.find(i => i.id === orderId)
    //   if (item) {
    //     this.handleAnalyze(item)
    //   }
    // },
    // 审批订单
    // handleApproveFromDetail (orderId) {
    //   const item = this.items.find(i => i.id === orderId)
    //   if (item) {
    //     this.handleApprove(item)
    //   }
    // },
    // 驳回订单
    handleRejectFromDetail (orderId) {
      const item = this.items.find(i => i.id === orderId)
      if (item) {
        this.handleReject(item)
      }
    },
    // 完成订单
    // handleCompleteFromDetail (orderId) {
    //   const item = this.items.find(i => i.id === orderId)
    //   if (item) {
    //     this.handleComplete(item)
    //   }
    // },
    handleAdd (item = {}) {
      this.createDialog.show = true
      this.createDialog.itemData = item
    },
    // 完成订单
    // async handleComplete (item) {
    //   try {
    //     await api.completeOrder(item.id)
    //     this.$snackbar.success('订单已完成')
    //     this.init()
    //   } catch (error) {
    //     if (error !== 'cancel') {
    //       this.$snackbar.error(error)
    //     }
    //   }
    // },
    getStatusColor (status) {
      const colors = {
        pending: 'info',
        analyzing: 'warning',
        pending_approval: 'primary',
        processing: 'primary',
        onboard: 'success',
        completed: 'success',
        rejected: 'error',
        need_supplement: 'warning',
        manual_review: 'warning'
      }
      return colors[status] || 'info'
    },
    // 状态判断函数
    canEdit (status) {
      return ['pending', 'manual_review', 'need_supplement'].includes(status)
    },
    canDelete (status) {
      return ['pending', 'completed', 'rejected'].includes(status)
    },
    formatDateTime (dateStr) {
      return formatDate(dateStr)
    }
  }
}
</script>
