<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="核销码" prop="verifyCode">
        <el-input
          v-model="queryParams.verifyCode"
          placeholder="核销码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- 出库状态筛选 -->
      <el-form-item label="出库状态" prop="outboundStatus">
        <el-select v-model="queryParams.outboundStatus" placeholder="请选择出库状态" clearable size="small">
          <el-option label="未出库" value="0" />
          <el-option label="已出库" value="1" />
        </el-select>
      </el-form-item>

      <!-- 核销状态筛选 -->
      <el-form-item label="核销状态" prop="verifyStatus">
        <el-select v-model="queryParams.verifyStatus" placeholder="请选择核销状态" clearable size="small">
          <el-option label="未核销" value="0" />
          <el-option label="已核销" value="1" />
        </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="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <!-- 新增：批量核销按钮 -->
      <el-col :span="1.8">
        <el-button
          type="info"
          plain
          icon="el-icon-check-circle"
          size="mini"
          :disabled="multiple || hasWriteOffAll"
          @click="handleBatchWriteOff"
        >批量核销</el-button>
      </el-col>
      <el-col :span="1.8">
        <el-button
          icon="el-icon-s-order"
          size="mini"
          type="warning"
          @click="openDeliveryNote"
        >批量导入溯源码
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="scrmList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="核销码" align="center" prop="verifyCode" />
      <el-table-column label="关联商品ID" align="center" prop="productId" />
      <el-table-column
        label="出库状态"
        align="center"
        prop="outboundStatus"
        :formatter="formatOutboundStatus"
      />
      <el-table-column
        label="核销状态"
        align="center"
        prop="verifyStatus"
        :formatter="formatVerifyStatus"
      />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <!-- 新增：单个核销按钮 -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            :disabled="scope.row.verifyStatus === 1"
            @click="handleSingleWriteOff(scope.row)"
          >核销</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="verifyCode">
          <el-input v-model="form.verifyCode" placeholder="核销码" />
        </el-form-item>
        <el-form-item label="出库状态" prop="outboundStatus">
          <el-radio-group v-model="form.outboundStatus">
            <el-radio :label="0">未出库</el-radio>
            <el-radio :label="1">已出库</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 核销状态 -->
        <el-form-item label="核销状态" prop="verifyStatus">
          <el-radio-group v-model="form.verifyStatus">
            <el-radio :label="0">未核销</el-radio>
            <el-radio :label="1">已核销</el-radio>
          </el-radio-group>
        </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-dialog
      :before-close="handleClose"
      :visible.sync="verifyNoteOpen"
      center
      title="批量导入溯源码"
      width="35%"
      :append-to-body="true"
    >
      <span slot="footer" class="dialog-footer">

        <el-upload ref="upload" :action="getUploadUrl()" :auto-upload="false" :disabled="verifyUpload.isUploading"
                   :headers="verifyUpload.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">
          <el-link style="font-size:12px" type="info" @click="importVerifyNoteTemplate">下载模板</el-link>
        </div>
        <div slot="tip" class="el-upload__tip" style="color:red">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
        <el-divider></el-divider>
        <el-button @click="verifyNoteOpen = false">取 消</el-button>
        <el-button type="primary" @click="submitDeliveryNote">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listScrm, getScrm, delScrm, addScrm, updateScrm, exportScrm ,importVerifyNoteTemplate,writeOff} from "@/api/store/verify";
import { getToken } from '@/utils/auth'

export default {
  name: "Scrm",
  props: {
    productId: {
      type: [Number, String],
      default: null,
      required: false
    }
  },
  data() {
    return {
      importMsgOpen: false,
      importMsg: '',
      verifyUpload: {
        open: false,
        title: '',
        isUploading: false,
        updateSupport: 0,
        headers: {Authorization: 'Bearer ' + getToken()},
        url: process.env.VUE_APP_BASE_API + '/shop/scrm/importExpress',
      },
      verifyNoteOpen: false,
      loading: true,
      exportLoading: false,
      ids: [],
      single: true,
      multiple: true,
      hasWriteOffAll: false,
      showSearch: true,
      total: 0,
      scrmList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        verifyCode: null,
        productId: null,
        outboundStatus: null,
        verifyStatus: null,
        status: null,
        isDel: null,
      },
      form: {},
      rules: {
        verifyCode: [
          { required: true, message: "用户自定义核销码不能为空", trigger: "blur" }
        ],
        productId: [
          { required: true, message: "关联商品ID不能为空", trigger: "blur" }
        ],
        outboundStatus: [
          { required: true, message: "出库状态不能为空", trigger: "blur" }
        ],
        verifyStatus: [
          { required: true, message: "核销状态不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "数据状态不能为空", trigger: "blur" }
        ],
        isDel: [
          { required: true, message: "是否删除不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ]
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    fullReset() {
      this.reset();
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        verifyCode: null,
        productId: null,
        outboundStatus: null,
        verifyStatus: null,
        status: null,
        isDel: null,
      };
      this.scrmList = [];
      this.total = 0;
      this.ids = [];
      this.single = true;
      this.multiple = true;
      this.hasWriteOffAll = false;
      if (this.$refs.form) {
        this.$refs.form.clearValidate();
      }
    },
    // 出库状态翻译
    formatOutboundStatus(row) {
      return row.outboundStatus === 0 ? "未出库" : "已出库";
    },
    // 核销状态翻译
    formatVerifyStatus(row) {
      return row.verifyStatus === 0 ? "未核销" : "已核销";
    },
    // 是否删除翻译
    formatIsDel(row) {
      return row.isDel === 0 ? "未删除" : "已删除";
    },
    /** 查询核销码列表 */
    getList() {
      this.loading = true;
      this.queryParams.productId = this.productId;
      console.log("打印pp----------------->", this.productId);
      listScrm(this.queryParams).then(response => {
        this.scrmList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        verifyCode: null,
        productId: this.productId,
        outboundStatus: 0,
        verifyStatus: 0,
        status: 1,
        isDel: 0
      };
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据 - 新增：校验选中行的核销状态
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;

      // 校验选中的行是否全部已核销
      this.hasWriteOffAll = selection.every(item => item.verifyStatus === 1);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加核销码";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getScrm(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改核销码";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateScrm(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addScrm(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除核销码编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delScrm(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有核销码数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportScrm(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    },
    openDeliveryNote() {
      this.verifyNoteOpen = true
      this.getAppList();
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {
        })
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.verifyUpload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.verifyUpload.open = false;
      this.verifyUpload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.importMsgOpen = true;
      this.importMsg = response.msg;
      console.log("打印请求-----------》",response.msg);
      if(response.code == 200) {
        this.$message.success(response.msg || '全部数据导入成功');
      }
      this.getList();
    },
    //发货单模板下载
    importVerifyNoteTemplate() {
      importVerifyNoteTemplate().then((response) => {
        this.download(response.msg);
      });
    },
    // 提交发货单
    submitDeliveryNote() {
      const uploadFiles = this.$refs.upload.uploadFiles;
      if (uploadFiles.length === 0) {
        this.$message.error('请选择要上传的文件');
        return;
      }
      this.$refs.upload.submit();
    },
    getUploadUrl() {
      if (!this.productId) {
        this.$message.warning('请先选择商品ID');
        return '';
      }
      return `${this.verifyUpload.url}?productId=${this.productId}`;
    },

    /** 单个核销操作 */
    handleSingleWriteOff(row) {
      this.$confirm(
        `是否确认核销溯源码【${row.verifyCode}】?`,
        "核销确认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "info"
        }
      ).then(() => {
        return writeOff({ids:[row.id]});
      }).then(response => {
        if (response.code === 200) {
          this.msgSuccess("核销成功！");
          this.getList(); // 刷新列表
        }
      })
    },

    /** 批量核销操作 */
    handleBatchWriteOff() {
      this.$confirm(
        `是否确认核销选中的${this.ids.length}条溯源码数据?`,
        "批量核销确认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "info"
        }
      ).then(() => {
        // 调用核销接口
        return writeOff({ids:this.ids});
      }).then(response => {
        if (response.code === 200) {
          this.msgSuccess(`批量核销成功！共核销${this.ids.length}条数据`);
          this.getList();
          this.ids = [];
          this.hasWriteOffAll = false;
        }
      })
    }
  }
};
</script>
