<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderCodes">
        <div class="tag-input-container">
          <!-- 标签显示区域 -->
          <div class="tags-wrapper" @click="focusInput">
            <!-- 已添加的订单号标签 -->
            <el-tag
              v-for="(code, index) in queryParams.orderCodes"
              :key="index"
              closable
              size="small"
              @close="removeOrderCode(index)"
              class="order-tag"
              :class="{ 'tag-error': false }"
            >
              {{ code }}
            </el-tag>

            <!-- 输入框 -->
            <el-input
              ref="tagInput"
              v-model="currentInput"
              v-show="inputVisible || queryParams.orderCodes.length === 0"
              :placeholder="queryParams.orderCodes.length === 0 ? '请输入订单号，按回车或逗号分隔' : '继续输入...'"
              size="small"
              class="tag-input"
              @keydown.native="handleKeyDown"
              @keyup.native="handleKeyUp"
              @blur="handleInputConfirm"
              @focus="inputVisible = true"
              clearable
            />

            <!-- 添加按钮（当没有输入时显示） -->
            <el-button
              v-if="!inputVisible && queryParams.orderCodes.length > 0"
              class="button-new-tag"
              size="small"
              @click="showInput"
              icon="el-icon-plus"
              type="text"
            >
              添加订单号
            </el-button>
          </div>

          <!-- 输入提示 -->
          <div class="input-tips">
            <span class="tip-text">
              支持：回车、逗号、空格分隔 |
              已添加 {{ queryParams.orderCodes.length }} 个订单号
              <span v-if="maxOrderCodes > 0"> (最多{{ maxOrderCodes }}个)</span>
            </span>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户电话" prop="userPhone">
        <el-input
          v-model="queryParams.userPhone"
          placeholder="请输入用户电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :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"
          placeholder="请输入快递单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

       <el-form-item label="提交时间" prop="createTime">
                 <el-date-picker v-model="createTime" size="small" style="width: 220px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" @change="change"></el-date-picker>
              </el-form-item>
      <el-form-item label="销售公司" prop="companyId">
        <el-select v-model="queryParams.companyId" placeholder="销售公司"  size="small" @change="getAllUserlist(queryParams.companyId)" clearable>
          <el-option
            v-for="dict in qwCompanyList"
            :key="dict.companyId"
            :label="dict.companyName"
            :value="dict.companyId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="销售账号" prop="userId">
        <el-select v-model="queryParams.companyUserId" placeholder="销售账号"  size="small" clearable>
          <el-option
            v-for="dict in companyUserNameList"
            :key="dict.userId"
            :label="dict.userName"
            :value="dict.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="企微微信" prop="companyUserName">
        <el-select v-model="queryParams.qwUserId" placeholder="企微微信"  size="small" clearable>
          <el-option
            v-for="dict in qwUserList"
            :key="dict.id"
            :label="dict.qwUserName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <!-- 这里就是之前添加的ERP账号下拉框 -->
      <el-form-item label="ERP" prop="loginAccount">
        <el-select v-model="queryParams.loginAccount" placeholder="ERP账号" size="small" clearable>
          <el-option
            v-for="account in erpAccountList"
            :key="account"
            :label="account"
            :value="account"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @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
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['his:integralOrder:export']"
        >导出</el-button>
      </el-col>
      
      <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImportStatus"
          >导入订单状态</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-tooltip content="默认erp推送手机号" placement="top">
          <el-button
            type="warning"
            plain
            icon="el-icon-phone"
            size="mini"
            @click="handleErpPhone"
          >推送手机号码</el-button>
        </el-tooltip>
      </el-col>
<el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['his:integralOrder:exportDeliver']"
          v-show="actName === '6'||actName === '1'"
        >导入发货</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-s-operation"
          size="mini"
          @click="handleDataSort"
          v-show="actName === '6'"
        >数据分拣</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleCreateErp"
          v-show="actName === '6'"
        >创建ERP</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-tabs type="card" v-model="actName" @tab-click="handleClickX">
      <el-tab-pane label="全部订单" name="10"></el-tab-pane>
      <el-tab-pane v-for="(item,index) in statusOptions" :label="item.dictLabel" :name="item.dictValue"></el-tab-pane>
    </el-tabs>
    <el-table v-loading="loading" border :data="integralOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ERP账号" align="center" prop="loginAccount" />
      <el-table-column label="ERP电话" align="center" prop="erpPhone" />
      <el-table-column label="订单编号" align="center" prop="orderCode" />
      <el-table-column label="商品名称" align="center" width="200">
        <template slot-scope="scope">
          <div style="display: flex; align-items: center; justify-content: center;">
            <span>{{ scope.row.goodsName }}</span>
            <el-image
              v-if="scope.row.goodsImage"
              :src="scope.row.goodsImage"
              style="width: 40px; height: 40px; margin-left: 8px;"
              fit="cover"
              :preview-src-list="[scope.row.goodsImage]"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="用户名称" align="center" prop="userName" />
      <el-table-column label="用户电话" align="center" prop="userPhone" />
      <el-table-column label="用户地址" align="center" prop="userAddress" show-overflow-tooltip />
      <el-table-column label="支付积分" align="center" prop="integral" />
      <el-table-column label="支付金额" align="center" prop="payMoney" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="快递公司编号" align="center" prop="deliveryCode" />
      <el-table-column label="快递名称" align="center" prop="deliveryName" />
      <el-table-column label="快递单号" align="center" prop="deliverySn" />
      <el-table-column label="发货时间" align="center" prop="deliveryTime" width="180"/>
      <el-table-column label="提交时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="销售公司ID" align="center" prop="companyId" width="180"/>
      <el-table-column label="销售ID" align="center" prop="companyUserId" width="180"/>
      <el-table-column label="企业微信ID" align="center" prop="qwUserId" width="180"/>
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button
             size="mini"
             type="text"
             @click="handledetails(scope.row)"
             >详情
          </el-button>
          <el-button
              size="mini"
              type="text"
              @click="cancelOrder(scope.row.orderCode)"
              v-if="scope.row.status === '1'"
            >取消订单
            </el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改积分商品订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单编号" prop="orderCode">
          <el-input v-model="form.orderCode" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="用户id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户id" />
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="用户电话" prop="userPhone">
          <el-input v-model="form.userPhone" placeholder="请输入用户电话" />
        </el-form-item>
        <el-form-item label="用户地址" prop="userAddress">
          <el-input v-model="form.userAddress" placeholder="请输入用户地址" />
        </el-form-item>
        <el-form-item label="商品信息" prop="itemJson">
          <el-input v-model="form.itemJson" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="支付积分" prop="integral">
          <el-input v-model="form.integral" placeholder="请输入支付积分" />
        </el-form-item>
        <el-form-item label="1：待发货；2：待收货；3：已完成" prop="status">
          <el-select v-model="form.status" placeholder="请选择1：待发货；2：待收货；3：已完成">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="快递公司编号" prop="deliveryCode">
          <el-input v-model="form.deliveryCode" placeholder="请输入快递公司编号" />
        </el-form-item>
        <el-form-item label="快递名称" prop="deliveryName">
          <el-input v-model="form.deliveryName" placeholder="请输入快递名称" />
        </el-form-item>
        <el-form-item label="快递单号" prop="deliverySn">
          <el-input v-model="form.deliverySn" placeholder="请输入快递单号" />
        </el-form-item>
        <el-form-item label="发货时间" prop="deliveryTime">
          <el-date-picker clearable size="small"
            v-model="form.deliveryTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择发货时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-drawer
    	:with-header="false"
            size="75%"
             :title="show.title" :visible.sync="show.open">
         <integralOrderDetails  ref="Details" />
       </el-drawer>
   <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
         <el-upload
           ref="upload"
           :limit="1"
           accept=".xlsx, .xls"
           :headers="upload.headers"
           :action="upload.url + '?updateSupport=' + upload.updateSupport"
           :disabled="upload.isUploading"
           :on-progress="handleFileUploadProgress"
           :on-success="handleFileSuccess"
           :auto-upload="false"
           drag
         >
           <i class="el-icon-upload"></i>
           <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
           <div class="el-upload__tip text-center" slot="tip">
             <div class="el-upload__tip" slot="tip">
             </div>
             <span>仅允许导入xls、xlsx格式文件。</span>
             <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @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>
     <!-- 数据分拣弹窗 -->
    <el-dialog :title="erpAccountDialog.title" :visible.sync="erpAccountDialog.open" width="600px" append-to-body>
      <div v-loading="erpAccountDialog.loading">
        <el-form :model="erpAccountForm" label-width="100px">
          <el-form-item label="ERP账户" required>
            <el-select 
              v-model="erpAccountForm.selectedAccount" 
              placeholder="请选择ERP账户" 
              style="width: 100%"
              filterable
            >
              <el-option
                v-for="account in erpAccountList"
                :key="account"
                :label="account"
                :value="account"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="推送手机号">
            <el-select 
              v-model="erpAccountForm.selectedPhones" 
              multiple 
              placeholder="请选择推送手机号，不填默认订单用户电话"
              style="width: 100%"
              filterable
            >
              <el-option
                v-for="phone in phoneList"
                :key="phone.phone"
                :label="phone.phone"
                :value="phone.phone"
              />
            </el-select>
          </el-form-item>
        </el-form>
        
        <!-- 订单统计信息 -->
        <div class="order-summary" v-if="orderSummary">
          <el-divider content-position="left">订单统计</el-divider>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="summary-item">
                <span class="label">选中订单数：</span>
                <span class="value">{{ orderSummary.selectedCount }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="summary-item">
                <span class="label">总金额：</span>
                <span class="value">¥{{ orderSummary.totalAmount }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="summary-item">
                <span class="label">查询条件订单：</span>
                <span class="value">{{ orderSummary.queryCount }}</span>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelErpAccountDialog">取 消</el-button>
        <el-button 
          type="primary" 
          @click="confirmCreateErpOrder"
          :disabled="!erpAccountForm.selectedAccount"
          :loading="erpAccountDialog.submitting"
        >确认</el-button>
      </div>
    </el-dialog>
    <!-- 推送手机号码管理弹窗 -->
    <el-dialog :title="erpPhone.title" :visible.sync="erpPhone.open" width="600px" append-to-body>
      <div style="margin-bottom: 20px;">
        <el-button type="primary" size="small" @click="handleAddPhone">新增手机号</el-button>
      </div>
      <el-table :data="phoneList" border style="width: 100%">
        <el-table-column prop="phone" label="手机号" align="center">
          <template slot-scope="scope">
            <el-input 
              v-if="scope.row.editing" 
              v-model="scope.row.phone" 
              placeholder="请输入手机号"
              @blur="validatePhone(scope.row)"
              @keyup.enter.native="handleSavePhone(scope.$index)"
            />
            <span v-else>{{ scope.row.phone }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="300">
          <template slot-scope="scope">
            <el-button 
              v-if="scope.row.editing" 
              type="success" 
              size="mini" 
              @click="handleSavePhone(scope.$index)"
            >保存</el-button>
            <el-button 
              v-if="scope.row.editing" 
              type="info" 
              size="mini" 
              @click="handleCancelEdit(scope.$index)"
            >取消</el-button>
            <el-button 
              v-if="!scope.row.editing" 
              type="primary" 
              size="mini" 
              @click="handleEditPhone(scope.$index)"
            >修改</el-button>
            <el-button 
              type="danger" 
              size="mini" 
              @click="handleDeletePhone(scope.$index)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSavePhoneList">确 定</el-button>
        <el-button @click="handleCancelPhoneDialog">取 消</el-button>
      </div>
    </el-dialog>

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

<script>
import {importTemplate,batchSetErpOrder,batchCreateErpOrder,listIntegralOrder,getIntegralTemplate, getIntegralOrder, delIntegralOrder, addIntegralOrder, updateIntegralOrder, exportIntegralOrder,cancelOrder } from "@/api/his/integralOrder";
import integralOrderDetails from '../../components/his/integralOrderDetails.vue';
import { getToken } from "@/utils/auth";
import {getCompanyList} from "@/api/company/company";
import {getAllUserlist} from "@/api/company/companyUser";
import {getQwUserInfo} from "@/api/qw/qwUser";
import {getErpAccount } from "@/api/his/storeOrder";
import {queryErpPhone, saveErpPhone} from "@/api/his/storeOrder";

export default {
  name: "IntegralOrder",
  components: { integralOrderDetails },
  data() {
    return {
      show:{
              open:false,
            },
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/his/integralOrder/importData"
      },
      // 遮罩层
      loading: true,
      actName:"10",
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 积分商品订单表格数据
      integralOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 1：待发货；2：待收货；3：已完成字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderCode: null,
        orderCodes: [], // 添加订单号数组
        userName: null,
        userPhone: null,
        integral: null,
        status: null,
        deliverySn: null,
        createTime: null,
        sTime:null,
        eTime:null,
        companyUserId:null,
        qwUserId:null,
        companyId:null,
        loginAccount: null  // 添加ERP账号筛选字段
      },
      // 最大订单号数量限制
      maxOrderCodes: {
        type: Number,
        default: 50
      },
      // 输入框是否可见
      inputVisible: false,
      // 当前输入值
      currentInput: '',
       createTime:null,
      qwCompanyList:[],
      companyUserNameList:[],
      qwUserList:[],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "用户id不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "1：待发货；2：待收货；3：已完成不能为空", trigger: "change" }
        ],
      },
      dataSortOpen: false, // 数据分拣弹窗显示控制
      erpAccountDialog: {
        open: false,
        loading: false,
        submitting: false,
        title: "数据分拣"
      },
      erpAccountForm: {
        selectedAccount: null,
        selectedPhones: [] // 添加推送手机号字段
      },
      erpAccountList: [],
      orderSummary: {
        selectedCount: 0,
        totalAmount: 0,
        queryCount: 0
      },
      erpPhone: {
      open: false,
        title: "设置推送手机号"
      },
      phoneList: [], // 手机号列表
      originalPhoneList: [], // 原始手机号列表，用于取消时恢复
      uploadStatus: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/his/integralOrder/importOrderStatusData"
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_integral_order_status").then(response => {
      this.statusOptions = response.data;
    });


    //获取企业
    getCompanyList().then(response => {
      this.qwCompanyList = response.data;
    });
    this.loadErpAccountData();
  },
  methods: {
    handleImportStatus() {
        this.uploadStatus.title = "导入";
        this.uploadStatus.open = true;
       },
    handleFileUploadProgressOrder(event, file, fileList) {
          this.uploadStatus.isUploading = true;
        },
    // 文件上传成功处理
         handleFileSuccessOrder(response, file, fileList) {
          this.uploadStatus.open = false;
          this.uploadStatus.isUploading = false;
          this.$refs.uploadStatus.clearFiles();
          this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
          this.getList();
        },
    importUpdateOrderTemplate(){
        getIntegralTemplate().then(response => {
          this.download(response.msg);
        });
      },
     //取消订单
     cancelOrder(orderCode){
      this.$confirm('确定取消此订单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log("orderCode",orderCode)
        cancelOrder(orderCode).then(()=>{
          this.$message({
            type: 'success',
            message: '取消成功!'
          });
          this.getList();
        })
      }).catch(() => {
      });
    },
    change(){
          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;
          }

        },
    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.getDetails(row.orderId);
        }, 1);
    },
    /** 查询积分商品订单列表 */
    getList() {
      this.loading = true;
      
      // 直接传递订单编号数组给后端
      listIntegralOrder(this.queryParams).then(response => {
        // 解析itemJson字段，提取goodsName和图片
        const processedData = response.rows.map(item => {
          let goodsName = '';
          let goodsImage = '';
          try {
            if (item.itemJson) {
              const itemData = JSON.parse(item.itemJson);
              // 如果itemJson是数组格式，取第一个商品的名称和图片
              if (Array.isArray(itemData) && itemData.length > 0) {
                goodsName = itemData[0].goodsName || '';
                // 提取图片，优先使用imgUrl，如果没有则使用images的第一张
                if (itemData[0].imgUrl) {
                  goodsImage = itemData[0].imgUrl;
                } else if (itemData[0].images && itemData[0].images.split(',').length > 0) {
                  goodsImage = itemData[0].images.split(',')[0];
                }
              }
              // 如果itemJson是对象格式，直接取goodsName和图片
              else if (itemData.goodsName) {
                goodsName = itemData.goodsName;
                // 提取图片，优先使用imgUrl，如果没有则使用images的第一张
                if (itemData.imgUrl) {
                  goodsImage = itemData.imgUrl;
                } else if (itemData.images && itemData.images.split(',').length > 0) {
                  goodsImage = itemData.images.split(',')[0];
                }
              }
            }
          } catch (error) {
            console.error('解析itemJson失败:', error);
            goodsName = '';
            goodsImage = '';
          }
          
          return {
            ...item,
            goodsName: goodsName,
            goodsImage: goodsImage
          };
        });
        
        this.integralOrderList = processedData;
        this.total = response.total;
        this.loading = false;
      }).catch(error => {
        console.error('查询订单列表失败:', error);
        this.loading = false;
        this.$message.error('查询订单列表失败');
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        orderCode: null,
        userId: null,
        userName: null,
        userPhone: null,
        userAddress: null,
        itemJson: null,
        integral: null,
        status: null,
        deliveryCode: null,
        deliveryName: null,
        deliverySn: null,
        deliveryTime: null,
        createTime: null,
        remark: null,
        sTime:null,
        eTime:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.createTime=null;
      this.queryParams.sTime=null;
      this.queryParams.eTime=null;
      this.queryParams.qwUserId=null;
      this.queryParams.companyId=null;
      this.queryParams.companyUserId=null;
      
      // 清除订单号标签
      this.queryParams.orderCodes = [];
      this.currentInput = '';
      this.inputVisible = false;
      
      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
      getIntegralOrder(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) {
            updateIntegralOrder(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addIntegralOrder(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleClickX(tab, event) {
     if(tab.name=="10"){
       this.queryParams.status=null;
     }else{
       this.queryParams.status=tab.name;
     }
      this.handleQuery();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$confirm('是否确认删除积分商品订单编号为"' + orderIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delIntegralOrder(orderIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有积分商品订单数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportIntegralOrder(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    //选择企业后触发
    getAllUserlist(companyId){
      if(companyId){
        getAllUserlist({companyId}).then(response => {
          this.companyUserNameList=response.data;
        });
        //企业微信
        getQwUserInfo({companyId}).then(response => {
          this.qwUserList=response.data;
        })
      }
    },
    // 数据分拣按钮点击事件
    handleDataSort() {
      this.erpAccountDialog.open = true;
      this.erpAccountDialog.title = "数据分拣";
      this.getErpPhoneList(); // 加载手机号列表
      this.updateOrderSummary();
    },
    
    // 加载ERP账户数据
    async loadErpAccountData() {
      try {
        const response = await getErpAccount();
        this.erpAccountList = response.data;
      } catch (error) {
        console.error('加载ERP账户失败:', error);
      }
    },
    
    // 更新订单统计
    updateOrderSummary() {
      // 如果没有选择任何数据，则使用查询出来的所有数据
      if (this.ids.length === 0) {
        this.orderSummary.selectedCount = this.total;
        this.orderSummary.queryCount = this.total;
      } else {
        // 如果选择了数据，则使用选中的数据
        this.orderSummary.selectedCount = this.ids.length;
        this.orderSummary.queryCount = this.total;
      }
      
      // 计算总金额（这里需要根据实际数据结构调整）
      this.calculateTotalAmount();
    },
    // 计算总金额
    calculateTotalAmount() {
      let totalAmount = 0;
      
      if (this.ids.length === 0) {
        // 使用所有查询数据计算金额
        this.integralOrderList.forEach(order => {
          totalAmount += parseFloat(order.payMoney || 0);
        });
      } else {
        // 使用选中的数据计算金额
        const selectedOrders = this.integralOrderList.filter(order => 
          this.ids.includes(order.orderId)
        );
        selectedOrders.forEach(order => {
          totalAmount += parseFloat(order.payMoney || 0);
        });
      }
      
      this.orderSummary.totalAmount = totalAmount.toFixed(2);
    },
    
    // 取消ERP账户对话框
    cancelErpAccountDialog() {
      this.erpAccountDialog.open = false;
      this.erpAccountForm.selectedAccount = null;
    },
    
    // 确认创建ERP订单
    async confirmCreateErpOrder() {
      // 收集选中的orderId
      let selectedOrderIds = [];
      
      if (this.ids.length === 0) {
        // 如果没有选择任何数据，使用查询出来的所有数据的orderId
        selectedOrderIds = this.integralOrderList.map(order => order.orderId);
      } else {
        // 如果选择了数据，使用选中的orderId
        selectedOrderIds = this.ids;
      }
      
      // 收集ERP账户和手机号
      const selectedErpAccount = this.erpAccountForm.selectedAccount;
      const selectedPhones = this.erpAccountForm.selectedPhones;
      
      // 准备请求参数
      const params = {
        orderIds: selectedOrderIds,
        loginAccount: selectedErpAccount,
        erpPhones: selectedPhones // 添加手机号参数
      };
      try {
        this.erpAccountDialog.submitting = true;
        
        // 根据弹窗标题判断是数据分拣还是创建ERP
        if (this.erpAccountDialog.title === "数据分拣") {
          // 调用数据分拣接口
          const response = await batchSetErpOrder(params);
          this.$message.success('数据分拣成功');
        } else if (this.erpAccountDialog.title === "创建ERP") {
          // 调用创建ERP接口
          const response = await batchCreateErpOrder(params);
          // console.log("参数：",params)
          this.$message.success('创建ERP成功');
        }
        
        // 关闭弹窗
        this.cancelErpAccountDialog();
        
        // 刷新列表
        this.getList();
        
      } catch (error) {
        console.error('操作失败:', error);
        this.$message.error('操作失败');
      } finally {
        this.erpAccountDialog.submitting = false;
      }
    },
    handleCreateErp() {
      this.erpAccountDialog.open = true;
      this.erpAccountDialog.title = "创建ERP";
      this.getErpPhoneList(); // 加载手机号列表
      this.updateOrderSummary();
    },
    // 获取ERP手机号列表
    getErpPhoneList() {
      queryErpPhone().then(response => {
        if (response.data && response.data != null && response.data.length > 0) {
          const phones = response.data.filter(phone => phone.trim());
          this.phoneList = phones.map(phone => ({
            phone: phone.trim(),
            editing: false,
            originalPhone: phone.trim()
          }));
        } else {
          this.phoneList = [];
        }
      });
    },
    // 取消ERP账户对话框
    cancelErpAccountDialog() {
      this.erpAccountDialog.open = false;
      this.erpAccountForm.selectedAccount = null;
      this.erpAccountForm.selectedPhones = []; // 清空手机号选择
    },
    // 推送手机号码管理
    handleErpPhone() {
      this.getErpPhoneList();
      this.erpPhone.open = true;
    },
    // 新增手机号
    handleAddPhone() {
      this.phoneList.push({
        phone: '',
        editing: true,
        originalPhone: '',
        isNew: true
      });
    },

    // 编辑手机号
    handleEditPhone(index) {
      this.$set(this.phoneList[index], 'editing', true);
      this.$set(this.phoneList[index], 'originalPhone', this.phoneList[index].phone);
    },

    // 保存手机号
    handleSavePhone(index) {
      const phone = this.phoneList[index].phone.trim();
      if (!phone) {
        this.$message.error('手机号不能为空');
        return;
      }
      if (!this.validatePhoneFormat(phone)) {
        this.$message.error('请输入正确的手机号格式');
        return;
      }
      // 检查是否重复
      const duplicateIndex = this.phoneList.findIndex((item, idx) => 
        idx !== index && item.phone === phone
      );
      if (duplicateIndex !== -1) {
        this.$message.error('手机号已存在');
        return;
      }
      this.$set(this.phoneList[index], 'editing', false);
      this.$set(this.phoneList[index], 'isNew', false);
    },

    // 取消编辑
    handleCancelEdit(index) {
      if (this.phoneList[index].isNew) {
        // 如果是新增的，直接删除
        this.phoneList.splice(index, 1);
      } else {
        // 如果是编辑的，恢复原值
        this.$set(this.phoneList[index], 'phone', this.phoneList[index].originalPhone);
        this.$set(this.phoneList[index], 'editing', false);
      }
    },

    // 删除手机号
    handleDeletePhone(index) {
      this.$confirm('确认删除该手机号?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.phoneList.splice(index, 1);
        this.$message.success('删除成功');
      });
    },

    // 验证手机号格式
    validatePhoneFormat(phone) {
      const phoneRegex = /^1[3-9]\d{9}$/;
      return phoneRegex.test(phone);
    },

    // 验证手机号
    validatePhone(row) {
      if (row.phone && !this.validatePhoneFormat(row.phone)) {
        this.$message.error('请输入正确的手机号格式');
      }
    },

    // 保存手机号列表
    handleSavePhoneList() {
      // 检查是否有正在编辑的项
      const editingItem = this.phoneList.find(item => item.editing);
      if (editingItem) {
        this.$message.error('请先保存正在编辑的手机号');
        return;
      }
      
      // 检查是否有空的手机号
      const emptyPhone = this.phoneList.find(item => !item.phone.trim());
      if (emptyPhone) {
        this.$message.error('存在空的手机号，请删除或填写完整');
        return;
      }
      
      // 构造手机号列表
      const phoneList = this.phoneList.map(item => item.phone);
      
      // 调用保存接口
      saveErpPhone(phoneList).then(response => {
        if (response.code === 200) {
          this.$message.success('保存成功');
          this.erpPhone.open = false;
        } else {
          this.$message.error(response.msg || '保存失败');
        }
      }).catch(() => {
        this.$message.error('保存失败');
      });
    },

    // 取消手机号对话框
    handleCancelPhoneDialog() {
      this.erpPhone.open = false;
      this.getErpPhoneList(); // 重新加载原始数据
    },
    submitOrderStatusFileForm(){
      this.$refs.uploadStatus.submit();
    },
    // 处理键盘按下事件
    handleKeyDown(event) {
      const { key, target } = event
      
      // 处理退格键删除标签
      if (key === 'Backspace' && !target.value && this.queryParams.orderCodes.length > 0) {
        event.preventDefault()
        this.removeOrderCode(this.queryParams.orderCodes.length - 1)
      }
      
      // 处理分隔符
      if ([',', '，', ' ', 'Enter'].includes(key)) {
        event.preventDefault()
        this.handleInputConfirm()
      }
    },

    // 处理键盘抬起事件（实时分割输入）
    handleKeyUp(event) {
      const value = event.target.value
      
      // 检查是否包含分隔符
      if (/[,，\s]/.test(value)) {
        this.handleInputConfirm()
      }
    },

    // 确认输入
    handleInputConfirm() {
      const inputValue = this.currentInput.trim()
      
      if (inputValue) {
        // 分割多个订单号
        const codes = inputValue.split(/[,，\s]+/).filter(code => code.trim())
        
        codes.forEach(code => {
          this.addOrderCode(code.trim())
        })
      }
      
      this.currentInput = ''
    },

    // 添加订单号
    addOrderCode(code) {
      if (!code) return
      
      // 检查数量限制
      if (this.maxOrderCodes > 0 && this.queryParams.orderCodes.length >= this.maxOrderCodes) {
        this.$message.warning(`最多只能添加 ${this.maxOrderCodes} 个订单号`)
        return
      }
      
      // 检查重复
      if (this.queryParams.orderCodes.includes(code)) {
        this.$message.warning(`订单号 "${code}" 已存在`)
        return
      }
      
      // 添加到列表
      this.queryParams.orderCodes.push(code)
    },

    // 删除订单号
    removeOrderCode(index) {
      this.queryParams.orderCodes.splice(index, 1)
    },

    // 显示输入框
    showInput() {
      this.inputVisible = true
      this.$nextTick(() => {
        this.$refs.tagInput.focus()
      })
    },
    // 聚焦输入框
    focusInput() {
      if (!this.inputVisible) {
        this.showInput()
      }
    },
  }
};
</script>

<style scoped>
.tag-input-container {
  min-width: 445px;
}

.tags-wrapper {
  min-height: 32px;
  padding: 4px 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: text;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 4px;
  transition: border-color 0.2s;
}

.tags-wrapper:hover {
  border-color: #c0c4cc;
}

.tags-wrapper:focus-within {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.order-tag {
  margin: 2px;
  flex-shrink: 0;
}

.tag-error {
  background-color: #fef0f0;
  border-color: #fbc4c4;
  color: #f56c6c;
}

.tag-input {
  border: none;
  outline: none;
  flex: 1;
  min-width: 120px;
}

.tag-input >>> .el-input__inner {
  border: none;
  padding: 0;
  height: 24px;
  line-height: 24px;
}

.button-new-tag {
  height: 24px;
  line-height: 22px;
  padding: 0 8px;
  margin: 2px;
}

.input-tips {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
}

.tip-text {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>
