<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="80px">

      <el-form-item label="订单号" prop="orderCode">
        <el-input
          v-model="queryParams.orderCode"
          clearable
          placeholder="请输入订单号"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收货人" prop="userName">
        <el-input
          v-model="queryParams.userName"
          clearable
          placeholder="请输入收货人"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="电话" prop="userPhone">
        <el-input
          v-model="queryParams.userPhone"
          clearable
          placeholder="请输入收货人电话"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="医生姓名" prop="doctorName">
        <el-input
          v-model="queryParams.doctorName"
          clearable
          placeholder="请输入医生姓名"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="患者姓名" prop="patientName">
        <el-input
          v-model="queryParams.patientName"
          clearable
          placeholder="请输入患者姓名"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="订单类型" prop="orderType">
        <el-select v-model="queryParams.orderType" clearable placeholder="状态" size="small">
          <el-option
            v-for="dict in orderTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="快递单号" prop="deliverySn">
        <el-input
          v-model="queryParams.deliverySn"
          clearable
          placeholder="请输入快递单号"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="下单时间" prop="createTime">
        <el-date-picker v-model="createTime" end-placeholder="结束日期" range-separator="-" size="small"
                        start-placeholder="开始日期" style="width: 220px" type="daterange" value-format="yyyy-MM-dd"
                        @change="changeTime"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="支付时间" prop="payTime">
        <el-date-picker v-model="payTime" end-placeholder="结束日期" range-separator="-" size="small" start-placeholder="开始日期"
                        style="width: 220px" type="daterange" value-format="yyyy-MM-dd"
                        @change="changePayTime"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="处方编码" prop="serialNo">
        <el-input
          v-model="queryParams.serialNo"
          clearable
          placeholder="请输入处方编码"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="溯源码/有效期" prop="verifyCode">
        <el-input
          v-model="queryParams.verifyCode"
          clearable
          placeholder="请输入溯源码/有效期"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生产批次号/序列号" prop="batchNumber">
        <el-input
          v-model="queryParams.batchNumber"
          clearable
          placeholder="请输入生产批次号/序列号"
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">

        <el-button v-if="isExport"
                   :loading="exportLoading"
                   icon="el-icon-download"
                   plain
                   size="mini"
                   type="warning"
                   @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-upload2"
          plain
          size="mini"
          type="info"
          @click="handleImport"
        >导入运单号
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-tabs v-model="actName" type="card" @tab-click="handleClickX">
      <el-tab-pane label="全部订单" name="10"></el-tab-pane>
      <el-tab-pane v-for="(item,index) in orderOptions" :label="item.dictLabel" :name="item.dictValue"></el-tab-pane>
    </el-tabs>
    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55"/>
      <el-table-column align="center" label="药品订单号" prop="orderCode" width="180px"/>
      <el-table-column align="center" label="处方编码" prop="serialNo" width="180px"/>
      <el-table-column label="溯源码/有效期" align="center" prop="verifyCode" width="200px" />
      <el-table-column label="生产批次号/序列号" align="center" prop="batchNumber" width="200px" />
      <el-table-column align="center" label="所属店铺" prop="storeName"/>
      <!--     <el-table-column label="员工" align="center" prop="companyUserName" />-->
      <el-table-column align="center" label="就诊人" prop="patientName"/>
      <el-table-column align="center" label="应收金额" prop="payPrice"/>
      <el-table-column align="center" label="实收金额" prop="payMoney"/>
      <el-table-column align="center" label="支付方式" prop="payType">
        <template slot-scope="scope">
          <dict-tag :options="PayOptions" :value="scope.row.payType"/>
        </template>
      </el-table-column>

      <el-table-column align="center" label="下单时间" prop="createTime" width="180"/>
      <el-table-column align="center" label="支付时间" prop="payTime" width="180"/>
      <el-table-column align="center" label="订单状态" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="orderOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="物流状态" prop="deliveryStatus">
        <template slot-scope="scope">
          <dict-tag :options="deliveryStatusOptions" :value="scope.row.deliveryStatus"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="结算状态" prop="deliveryPayStatus">
        <template slot-scope="scope">
          <dict-tag :options="deliveryPayStatusOptions" :value="scope.row.deliveryPayStatus"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" prop="createTime" width="150px"/>
      <el-table-column align="center" label="修改时间" prop="updateTime" width="150px"/>
      <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作" width="100px">
        <template slot-scope="scope">

          <el-button
            size="mini"
            type="text"
            @click="handledetails(scope.row)"
          >查看
          </el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handlePreviewPrintOrder(scope.row)"
          >预览打印</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <el-drawer
      :title="show.title"
      :visible.sync="show.open"
      :with-header="false" size="75%"
    >
      <storeOrderDetails ref="Details"/>
    </el-drawer>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" append-to-body width="400px">
      <el-upload
        ref="upload"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :auto-upload="false"
        :disabled="upload.isUploading"
        :headers="upload.headers"
        :limit="1"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        accept=".xlsx, .xls"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip text-center">
          <div slot="tip" class="el-upload__tip">
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link :underline="false" style="font-size:12px;vertical-align: baseline;" type="primary"
                   @click="importTemplate"
          >下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 新增：Excel预览打印弹窗 -->
    <el-dialog
      title="订单Excel预览打印"
      :visible.sync="previewExcelOpen"
      width="90%"
      append-to-body
      :close-on-click-modal="false"
    >
      <div v-loading="previewLoading" class="excel-preview-container">
        <!-- Excel预览表格 -->
        <div v-if="previewExcelData.length > 0" class="excel-preview-content">
          <table class="excel-table" border="1" cellpadding="5" cellspacing="0">
            <tbody>
            <tr v-for="(row, rowIndex) in previewExcelData" :key="rowIndex">
              <td v-for="(cell, colIndex) in row" :key="colIndex" :style="{ minWidth: '120px' }">
                {{ cell || '' }}
              </td>
            </tr>
            </tbody>
          </table>
        </div>
        <div v-else-if="!previewLoading" class="empty-tip">暂无预览数据</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewExcelOpen = false">关闭</el-button>
        <el-button type="primary" @click="printExcelContent">打印</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listOrder,
  getOrder,
  delOrder,
  addOrder,
  updateOrder,
  exportOrder,
  importTemplate, downloadOrderExcel
} from '@/api/store/storeOrder'
import storeOrderDetails from '../../components/store/storeOrderDetails.vue'
import { getToken } from '@/utils/auth'
import { listStore } from '@/api/store/storeProduct'

export default {
  name: 'Order',
  components: { storeOrderDetails },
  data() {
    return {
      previewExcelOpen: false, // 预览弹窗是否打开
      previewExcelData: [],    // 解析后的Excel数据
      previewLoading: false,   // 预览加载状态
      isExport: false,
      actName: '10',
      show: {
        title: '订单详情',
        open: false
      },

      importExpress: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/store/storeOrder/importExpress'
      },
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/store/storeOrder/importData'
      },
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderList: [],
      // 弹出层标题
      title: '',
      createTime: null,
      payTime: null,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storeId: null,
        orderCode: null,
        userId: null,
        userName: null,
        userPhone: null,
        userAddress: null,
        cartId: null,
        totalNum: null,
        totalPrice: null,
        payPrice: null,
        payMoney: null,
        isPay: null,
        payTime: null,
        payType: null,
        status: null,
        refundStatus: null,
        refundImg: null,
        refundExplain: null,
        refundTime: null,
        refundReason: null,
        refundMoney: null,
        deliveryCode: null,
        deliveryName: null,
        deliverySn: null,
        isDel: null,
        costPrice: null,
        verifyCode: null,
        shippingType: null,
        isChannel: null,
        isPrescribe: null,
        prescribeId: null,
        finishTime: null,
        patientName: null,
        doctorName: null,
        sTime: null,
        eTime: null,
        paysTime: null,
        payeTime: null,
        deliveryTime: null,
        tuiMoney: null,
        tuiMoneyStatus: null,
        tuiUserId: null,
        orderCreateType: null,
        companyUserName: null,
        companyName: null,
        batchNumber:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      PayOptions: [],
      orderOptions: [],
      payStatusOptions: [],
      refundOptions: [],
      channelOptions: [],
      orderTypeOptions: [],
      tuiOptions: [],
      orOptions: [],
      storeOPtions: [],
      deliveryPayStatusOptions: [],
      deliveryStatusOptions: []
    }
  },
  created() {
    this.isShow()
    this.getstoreList()
    this.getList()
    this.getDicts('sys_store_pay_type').then(response => {
      this.PayOptions = response.data
    })
    this.getDicts('store_order_type').then(response => {
      this.orderTypeOptions = response.data
    })
    this.getDicts('sys_order_status').then(response => {
      this.orderOptions = response.data
    })
    this.getDicts('sys_order_pay').then(response => {
      this.payStatusOptions = response.data
    })
    this.getDicts('sys_refund_status').then(response => {
      this.refundOptions = response.data
    })
    this.getDicts('sys_channel').then(response => {
      this.channelOptions = response.data
    })
    this.getDicts('sys_tui_money_status').then(response => {
      this.tuiOptions = response.data
    })
    this.getDicts('sys_company_or').then(response => {
      this.orOptions = response.data
    })
    this.getDicts('sys_store_delivery_pay_status').then(response => {
      this.deliveryPayStatusOptions = response.data
    })
    this.getDicts('sys_store_order_delivery_status').then(response => {
      this.deliveryStatusOptions = response.data
    })

  },
  methods: {
    handleImportExpress() {
      this.importExpress.title = '导入'
      this.importExpress.open = true
    },
    /** 下载模板操作 */
    importTemplateExpress() {
      importExpressTemplate().then(response => {
        this.download(response.msg)
      })
    },
    // 文件上传中处理
    handleFileUploadProgressExpress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccessExpress(response, file, fileList) {
      this.importExpress.open = false
      this.importExpress.isUploading = false
      this.$refs.importExpress.clearFiles()
      this.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileFormExpress() {
      this.$refs.importExpress.submit()
    },
    isShow() {
      var id = this.$store.state.user.storeId
      if (id != 30 && id != 31 && id != 33) {
        this.isExport = true
      }
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '导入'
      this.upload.open = true
    },

    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg)
      })
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    handledetails(row) {
      this.show.open = true
      setTimeout(() => {
        this.$refs.Details.getOrder(row.id)
      }, 1)
    },
    getstoreList() {
      listStore().then(response => {
        this.storeOPtions = response.rows
      })
    },
    /** 查询订单列表 */
    getList() {
      this.loading = true
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows
        this.total = response.total
        this.loading = false
      })

    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        storeId: null,
        orderCode: null,
        userId: null,
        userName: null,
        userPhone: null,
        userAddress: null,
        cartId: null,
        totalNum: null,
        totalPrice: null,
        payPrice: null,
        payMoney: null,
        isPay: null,
        payTime: null,
        payType: null,
        createTime: null,
        updateTime: null,
        status: null,
        refundStatus: '0',
        refundImg: null,
        refundExplain: null,
        refundTime: null,
        refundReason: null,
        refundMoney: null,
        deliveryCode: null,
        deliveryName: null,
        deliverySn: null,
        remark: null,
        isDel: null,
        costPrice: null,
        verifyCode: null,
        shippingType: null,
        isChannel: null,
        isPrescribe: null,
        prescribeId: null,
        finishTime: null,
        deliveryTime: null,
        tuiMoney: null,
        tuiMoneyStatus: 0,
        tuiUserId: null,
        orderCreateType: null,
        batchNumber:null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    handleClickX(tab, event) {
      if (tab.name == '10') {
        this.queryParams.status = null
      } else {
        this.queryParams.status = tab.name
      }
      this.handleQuery()
    },
    changeTime() {
      if (this.createTime != null) {
        this.queryParams.sTime = this.createTime[0]
        this.queryParams.eTime = this.createTime[1]
      } else {
        this.queryParams.sTime = null
        this.queryParams.eTime = null
      }

    },
    changePayTime() {
      if (this.payTime != null) {
        this.queryParams.sTime = this.payTime[0]
        this.queryParams.eTime = this.payTime[1]
      } else {
        this.queryParams.paysTime = null
        this.queryParams.payeTime = null
      }

    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.createTime = null
      this.queryParams.sTime = null
      this.queryParams.eTime = null
      this.payTime = null
      this.queryParams.paysTime = null
      this.queryParams.payeTime = null
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加订单'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const orderId = row.orderId || this.ids
      getOrder(orderId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改订单'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.orderId != null) {
            updateOrder(this.form).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addOrder(this.form).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids
      this.$confirm('是否确认删除订单编号为"' + orderIds + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return delOrder(orderIds)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出所有订单数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportLoading = true
        return exportOrder(queryParams)
      }).then(response => {
        this.download(response.msg)
        this.exportLoading = false
      }).catch(() => {
      })
    },

    /** 新增：预览并打印订单Excel */
    handlePreviewPrintOrder(row) {
      this.previewLoading = true;
      this.previewExcelData = [];
      downloadOrderExcel(row.id)
        .then(response => {
          if (response instanceof Blob) return response.arrayBuffer();
          throw new Error('响应不是Excel文件格式');
        })
        .then(arrayBuffer => {
          const XLSX = require('xlsx');
          const workbook = XLSX.read(arrayBuffer, { type: 'array' });
          const sheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[sheetName];
          const range = XLSX.utils.decode_range(worksheet['!ref'] || 'A1:A1');
          const excelData = [];

          for (let row = 0; row <= range.e.r; row++) {
            const rowData = [];
            let isRowEmpty = true;
            for (let col = 0; col <= range.e.c; col++) {
              const cell = worksheet[XLSX.utils.encode_cell({ r: row, c: col })];
              const cellValue = cell ? cell.v : '';
              rowData.push(cellValue);
              if (cellValue !== '' && cellValue !== null && cellValue !== undefined) {
                isRowEmpty = false;
              }
            }
            if (!isRowEmpty) {
              if (rowData.some(item => item.includes('销售退款明细单'))) {
                excelData.push(['' +
                '', '' +
                '']);
                excelData.push(rowData);
              } else {
                excelData.push(rowData);
              }
            }
          }

          this.previewExcelData = excelData;
          this.previewExcelOpen = true;
        })
        .catch(error => {
          console.error('预览Excel失败:', error);
          this.$message.error(`预览失败：${error.message || '请重试'}`);
        })
        .finally(() => {
          this.previewLoading = false;
        });
    },

    /** 新增：打印预览的Excel内容 */
    printExcelContent() {
      if (this.previewExcelData.length === 0) {
        this.$message.warning('暂无可打印的数据');
        return;
      }
      // 1. 创建新打印窗口
      const printWindow = window.open('', '_blank');
      if (!printWindow) {
        this.$message.warning('浏览器弹窗被拦截，请允许弹窗后重试');
        return;
      }

      // 2. 构建打印页面的HTML
      printWindow.document.write(`
      <!DOCTYPE html>
      <html>
      <head>
        <meta charset="UTF-8">
        <title>订单详情打印</title>
        <style>
          table { border-collapse: collapse; width: 100%; margin: 20px 0; }
          td { border: 1px solid #000; padding: 8px; min-width: 120px; text-align: center; }
          h3 { text-align: center; }
        </style>
      </head>
      <body>
        <h3>订单详情</h3>
        <table>
          <tbody>
            ${this.previewExcelData.map(row => `
              <tr>
                ${row.map(cell => `<td>${cell || ''}</td>`).join('')}
              </tr>
            `).join('')}
          </tbody>
        </table>
      </body>
      </html>
    `);
      printWindow.document.close();
      printWindow.print();
      printWindow.onafterprint = () => printWindow.close();
    },
  }
}
</script>
<style>
/* 新增：Excel预览样式 */
.excel-preview-container {
  padding: 10px;
  max-height: 600px;
  overflow: auto;

  .excel-table {
    width: 100%;
    border-collapse: collapse;

    td {
      border: 1px solid #e6e6e6;
      padding: 8px;
      text-align: center;
    }
  }

  .empty-tip {
    text-align: center;
    padding: 20px;
    color: #999;
  }
}
</style>

<style>
@media print {
  body * {
    visibility: hidden;
  }
  .print-content, .print-content * {
    visibility: visible;
  }
  .print-content {
    position: absolute;
    top: 0;
    left: 0;
    padding: 20px;
    width: 100%;
  }
}
</style>
