<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="所属员工" prop="companyUserName">
            <el-input
              v-model="queryParams.companyUserName"
              placeholder="请输入所属员工昵称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="订单号" prop="orderCode">
            <el-input
            style="width:220px"
              v-model="queryParams.orderCode"
              placeholder="请输入订单号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="收件人" prop="realName">
            <el-input
            style="width:220px"
              v-model="queryParams.realName"
              placeholder="请输入收件人"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="手机号" prop="userPhone">
            <el-input
            style="width:220px"
              v-model="queryParams.userPhone"
              placeholder="请输入收件人手机号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        

      </el-row>


      
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="订单金额" prop="orderAmountRange">
            <el-input
            style="width:100px"
              v-model="queryParams.orderAmountSmall"
              placeholder="请输入订单金额"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
            <span>-</span>
            <el-input
            style="width:100px"
              v-model="queryParams.orderAmountBig"
              placeholder="请输入订单金额"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="订单类型" prop="orderType">
            <el-select style="width:220px"  v-model="queryParams.orderType" placeholder="请选择订单类型" clearable size="small" >
              <el-option
                    v-for="item in orderTypeOptions"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          
        </el-col>
        <el-col :span="6">
          
        </el-col>

      </el-row>

      <el-row :gutter="20"> 
        <el-col :span="6">
          <el-form-item label="创建时间" prop="createTimeRange">
            <el-date-picker
            style="width:220px"
              clearable size="small"
              v-model="createTimeRange"
              type="daterange"
              value-format="yyyy-MM-dd"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="审核时间" prop="auditTimeRange">
            <el-date-picker
            style="width:220px"
              clearable size="small"
              v-model="auditTimeRange"
              type="daterange"
              value-format="yyyy-MM-dd"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button type="cyan" 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-col>
      </el-row>

    </el-form>

    <!-- 使用 el-row 布局将 tabs 和 批量操作按钮放在同一行 -->
    <el-row :gutter="10" style="margin-bottom: 10px;">
      <el-col :span="16">
        <el-tabs type="card" v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="全部" name="00"></el-tab-pane>
          <el-tab-pane label="待审批" name="0"></el-tab-pane>
          <el-tab-pane label="审批拒绝" name="1"></el-tab-pane>
          <!-- <el-tab-pane label="待总后台审核" name="2"></el-tab-pane>
          <el-tab-pane label="总后台审核拒绝" name="3"></el-tab-pane> -->
          <el-tab-pane label="审核通过" name="4"></el-tab-pane>
        </el-tabs>
      </el-col>
      <el-col :span="8" style="text-align: right;">
        <div style="margin-top: 5px;">
          <el-button 
            type="primary" 
            icon="el-icon-check" 
            size="mini" 
            :disabled="selectedRows.length === 0"
            @click="handleBatchAudit"
            v-hasPermi="['store:storeOrderAudit:audit']"
          >
            批量审核
          </el-button>
          <span style="margin-left: 10px; color: #999;">
            已选择 {{ selectedRows.length }} 项
          </span>
        </div>
      </el-col>
    </el-row>

    <el-table height="500" 
    border 
    v-loading="loading" 
    :data="storeOrderAuditList" 
    :key="tableKey"
    class="scrollable-table"
    @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" ></el-table-column>
      <el-table-column label="订单号" align="center" prop="orderCode" width="180"  />
      <el-table-column label="所属公司" align="center" prop="companyName" />
      <el-table-column label="所属员工" align="center" prop="companyUserName" />
      <el-table-column label="审核状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag prop="status" v-for="item in statusOptions"
                  :type="item.type"
                  v-if="scope.row.auditStatus === item.dictValue">
            {{item.dictLabel}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="订单类型" align="center" prop="orderType" width="100" >
          <template slot-scope="scope">
              <el-tag prop="status" v-for="(item, index) in orderTypeOptions"    v-if="scope.row.orderType==item.dictValue">{{item.dictLabel}}</el-tag>
          </template>
      </el-table-column>
      <el-table-column label="收件人" align="center" prop="realName" />
      <el-table-column label="送货地址" align="center" prop="userAddress" show-overflow-tooltip/>
      <el-table-column label="实收金额" align="center" prop="payPrice">
        <template slot-scope="scope">
          {{ scope.row.payPrice ? parseFloat(scope.row.payPrice).toFixed(2) : '0.00' }}
        </template>
      </el-table-column>
      <el-table-column label="订单金额" align="center" prop="totalPrice">
        <template slot-scope="scope">
          {{ scope.row.totalPrice ? parseFloat(scope.row.totalPrice).toFixed(2) : '0.00' }}
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" prop="userPhone"  width="120"/>
      <el-table-column label="审核时间" align="center" prop="companyAuditTime"  width="160"/>
      <el-table-column label="审核人" align="center" prop="companyAuditUserName" />
      <!-- <el-table-column label="总后台审核时间" align="center" prop="adminAuditTime" />
      <el-table-column label="总后台审核人" align="center" prop="adminAuditUserName" /> -->
      <el-table-column label="被拒原因" align="center" prop="reason" show-overflow-tooltip />
      <!-- <el-table-column label="提交时间" align="center" prop="createTime" /> -->
      <el-table-column label="创建时间" align="center" prop="orderCreateTime" width="160"/>
      <el-table-column label="操作" fixed="right" align="center" width="80" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-popover
            v-if="scope.row.auditStatus === 0"
            placement="right"
            trigger="click"
            :ref="'popover_' + scope.row.id">
            <el-button size="mini" type="success" @click="handlePass(scope.row)">通过</el-button>
            <el-button size="mini" type="danger" @click="handleAudit(scope.row)">拒绝</el-button>
            <el-button
              slot="reference"
              size="mini"
              type="text"
              v-hasPermi="['store:storeOrderAudit:audit']"
            >审核订单</el-button>
          </el-popover>
        </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="show.title" :visible.sync="show.open" width="500px" append-to-body>
      <el-form ref="auditForm" :model="auditForm" :rules="auditRules" label-width="80px">
        <el-form-item label="拒绝原因" prop="reviewContent">
          <el-input
            type="textarea"
            v-model="auditForm.reviewContent"
            placeholder="请输入拒绝原因"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleReject">确定</el-button>
        <el-button @click="cancelAudit">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加批量审核确认对话框 -->
    <el-dialog 
      title="批量审核确认" 
      :visible.sync="batchAuditDialogVisible" 
      width="500px" 
      append-to-body
    >
      <p>确定要审核通过选中的 {{ selectedRows.length }} 个订单吗？</p>
      <div slot="footer" class="dialog-footer">
        <el-button @click="batchAuditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmBatchAudit"
        v-hasPermi="['store:storeOrderAudit:auditBatch']">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCompanyList } from "@/api/company/company";
import {list, audit,auditBatch} from "@/api/hisStore/storeOrderAudit";

export default {
  name: "StoreOrderAudit",
  data() {
    const statusOptions = [
      {
        dictLabel: "待审批",
        dictValue: 0,
        type: ''
      },
      {
        dictLabel: "审批拒绝",
        dictValue: 1,
        type: 'danger'
      },
      {
        dictLabel: "审核通过",
        dictValue: 4,
        type: 'success'
      }
    ]

    return {
      
      tableKey: 0,
      showSearch: true,
      companys: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyUserName: null,
        auditStatus: null,
        realName:null,
        userPhone: null,
        orderAmountSmall: null,
        orderAmountBig: null,
        beginTime:null,// 审单日期
        endTime:null,
        orderType: null,
        auditBeginTime:null,
        auditEndTime:null,
      },
      selectedRows: [], // 添加这行来存储选中的行
       batchAuditDialogVisible: false, // 批量审核对话框显示控制
      createTimeRange:[],
      auditTimeRange:[], // 审核时间
      orderTypeOptions:[], // 订单类型
      activeName: '00',
      loading: false,
      storeOrderAuditList: [],
      statusOptions: statusOptions,
      show: {
        open: false,
        title: "审核订单"
      },
      auditForm: {
        auditId: null,
        reviewType: null,
        reviewContent: ''
      },
      auditRules: {
        reviewContent: [
          { required: true, message: "请输入拒绝原因", trigger: "blur" }
        ]
      },
      currentRowId: null,
    }
  },
  created() {
    this.getDicts("store_order_type").then((response) => {
      this.orderTypeOptions = response.data;
    });
    this.getCompanyOptions()
    this.handleQuery()
  },
  activated() {
    this.tableKey = Date.now()
  },
  methods: {
    // 确认批量审核
    confirmBatchAudit() {
      // 这里需要调用批量审核接口，假设有一个批量审核的API
      
        const ids = this.selectedRows.map(item => item.id).join(",");
        console.log("批量审核订单IDs:", ids);
  
      // 示例：调用批量审核API
      auditBatch({ids}).then(response => {
        this.$message.success("批量审核完成");
        this.batchAuditDialogVisible = false;
        this.getList(); // 刷新列表
      }).catch(error => {
        this.$message.error("批量审核失败");
      });
      
      // 由于没有提供批量审核API，这里只是演示逻辑
      console.log("批量审核订单IDs:", auditIds);
      this.batchAuditDialogVisible = false;
      this.getList(); // 实际使用时需要刷新列表
    },
     // 批量审核处理
    handleBatchAudit() {
      if (this.selectedRows.length === 0) {
        this.$message.warning("请至少选择一条数据");
        return;
      }
      this.batchAuditDialogVisible = true;
    },
    // 多选
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },
    getCompanyOptions() {
      getCompanyList().then(response => {
        this.companys = response.data
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      // 手动重置时间范围
      this.createTimeRange = [];
      this.queryParams.beginTime = null;
      this.queryParams.endTime = null;
      this.auditTimeRange = [];
      this.queryParams.auditBeginTime = null;
      this.queryParams.auditEndTime = null;


      
      // 手动重置订单金额范围
      this.queryParams.orderAmountSmall = null;
      this.queryParams.orderAmountBig = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    getList() {
      this.loading = true
      console.log("+++++++++++++++++"+this.createTimeRange)
      console.log("+++++++++++++++++"+this.auditTimeRange)
      if(this.createTimeRange!=null&&this.createTimeRange.length==2){
        this.queryParams.beginTime=this.createTimeRange[0]
        this.queryParams.endTime=this.createTimeRange[1]
      }
      if(this.auditTimeRange!=null&&this.auditTimeRange.length==2){
        this.queryParams.auditBeginTime=this.auditTimeRange[0]
        this.queryParams.auditEndTime=this.auditTimeRange[1]
      }
      list(this.queryParams).then(response => {
        const {rows, total} = response
        this.storeOrderAuditList = rows
        this.total = total
        this.loading = false
      })
    },
    handleClick(tab) {
      this.queryParams.auditStatus = tab.name === '00' ? null : tab.name
      this.handleQuery()
    },
    handleAudit(row) {
      this.currentRowId = row.id
      this.auditForm.auditId = row.id;
      this.auditForm.reviewType = 0;
      this.show.open = true;
    },
    handlePass(row) {
      this.currentRowId = row.id
      this.auditForm.auditId = row.id;
      this.auditForm.reviewType = 1;
      this.submitAudit();
    },
    handleReject() {
      this.$refs["auditForm"].validate(valid => {
        if (valid) {
          this.submitAudit();
        }
      });
    },
    submitAudit() {
      audit(this.auditForm).then(response => {
        const {msg} = response
        this.msgSuccess(msg);
        this.show.open = false;
        this.$refs['popover_' + this.currentRowId].doClose();
        this.getList();
        this.resetAuditForm();
      });
    },
    cancelAudit() {
      this.show.open = false;
      this.resetAuditForm();
    },
    resetAuditForm() {
      this.auditForm = {
        auditId: null,
        reviewType: null,
        reviewContent: ''
      };
      this.$refs["auditForm"]?.resetFields();
    }
  }
}
</script>

<style scoped>
.scrollable-table {
  display: block;
  width: 100%;
}

.scrollable-table ::v-deep .el-table__body-wrapper {
  overflow-x: auto;
  overflow-y: auto;
}

.scrollable-table ::v-deep .el-table__header-wrapper {
  overflow-x: auto;
  overflow-y: hidden;
}
</style>
