<template>
  <div class="shop-customer-container app-container">
    <div class="filter-container">
      <div class="search-filters">
        <el-input
          v-model="searchForm.shopName"
          placeholder="按店铺名称搜索"
          clearable
          @clear="handleSearch"
          @keyup.enter.native="handleSearch"
          class="filter-item"
          size="small"
        ></el-input>
        <el-input
          v-model="searchForm.customerName"
          placeholder="按客户名称搜索"
          clearable
          @clear="handleSearch"
          @keyup.enter.native="handleSearch"
          class="filter-item"
          size="small"
        ></el-input>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="handleSearch"
          size="small"
          style="margin-right: 0"
        ></el-button>
        <el-button
          icon="el-icon-refresh"
          @click="resetSearch"
          size="small"
          style="margin-left: 0"
        ></el-button>

        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd"
          size="small"
          style="margin-left: auto"
          >新增关联</el-button
        >
        <el-divider direction="vertical"></el-divider>
        <el-upload
          ref="upload"
          :action="uploadUrl"
          :before-upload="beforeUpload"
          :on-success="onUploadSuccess"
          :on-error="onUploadError"
          :show-file-list="false"
          accept=".xlsx,.xls"
          size="small"
        >
          <el-button type="success" plain icon="el-icon-upload2" size="small"
            >导入Excel</el-button
          >
        </el-upload>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          @click="handleExport"
          :disabled="!relationList.length"
          size="small"
          >导出Excel</el-button
        >
        <el-divider direction="vertical"></el-divider>
        <el-button
          type="danger"
          icon="el-icon-delete"
          @click="handleBatchDelete"
          :disabled="!selectedRows.length"
          plain
          size="small"
          >批量删除</el-button
        >
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="relationList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      row-key="id"
      size="small"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="id"
        label="ID"
        width="80"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="shopName"
        label="店铺名称"
        min-width="220"
        show-overflow-tooltip
        sortable
      >
        <template slot-scope="scope">
          <i
            class="el-icon-s-shop"
            style="margin-right: 5px; color: #409eff"
          ></i>
          <span>{{ scope.row.shopName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="customerName"
        label="客户名称"
        min-width="220"
        show-overflow-tooltip
        sortable
      >
        <template slot-scope="scope">
          <i
            class="el-icon-user-solid"
            style="margin-right: 5px; color: #67c23a"
          ></i>
          <span>{{ scope.row.customerName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="createdAt"
        label="创建时间"
        width="180"
        align="center"
        sortable
      >
        <template slot-scope="scope">
          <i class="el-icon-time" style="margin-right: 5px"></i>
          <span>{{ formatDateTime(scope.row.createdAt) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160" fixed="right" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handleEdit(scope.row)"
            plain
            >编辑</el-button
          >
          <el-popconfirm
            title="确定删除此关联吗？"
            @confirm="handleDelete(scope.row)"
            style="margin-left: 10px"
          >
            <el-button slot="reference" type="danger" size="mini" plain
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
      custom-class="relation-dialog"
    >
      <el-form
        ref="relationForm"
        :model="relationForm"
        :rules="relationRules"
        label-width="100px"
        label-position="top"
      >
        <el-form-item label="店铺名称" prop="shopName">
          <el-input
            v-model="relationForm.shopName"
            placeholder="请输入店铺名称"
            :disabled="isEdit"
            clearable
          ></el-input>
          <div class="form-tips" v-if="isEdit">
            <i class="el-icon-info"></i>
            关联关系创建后不可修改，如需调整请删除后重新创建。
          </div>
        </el-form-item>
        <el-form-item label="客户名称" prop="customerName">
          <el-input
            v-model="relationForm.customerName"
            placeholder="请输入客户名称"
            :disabled="isEdit"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>

      <div
        v-if="dialogTitle === '新增店铺客户关联'"
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { formatDateTime } from "@/utils/filters";
import {
  getShopCustomerList,
  deleteShopCustomer,
  batchDeleteShopCustomer,
  exportShopCustomer,
  ShopCustomerAdd,
  ShopCustomerUpdate,
} from "@/api/sales-analysis";

export default {
  name: "ShopCustomer",
  data() {
    return {
      loading: false,
      submitting: false,
      relationList: [],
      selectedRows: [],
      searchForm: {
        shopName: "",
        customerName: "",
      },
      pagination: {
        page: 1,
        pageSize: 50,
        total: 0,
      },
      dialogVisible: false,
      isEdit: false,
      relationForm: {
        id: null,
        shopName: "",
        customerName: "",
      },
      relationRules: {
        shopName: [
          { required: true, message: "请输入店铺名称", trigger: "blur" },
          {
            min: 1,
            max: 100,
            message: "店铺名称长度在 1 到 100 个字符",
            trigger: "blur",
          },
        ],
        customerName: [
          { required: true, message: "请输入客户名称", trigger: "blur" },
          {
            min: 1,
            max: 100,
            message: "客户名称长度在 1 到 100 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {
    dialogTitle() {
      return this.isEdit ? "编辑店铺客户关联" : "新增店铺客户关联";
    },
    uploadUrl() {
      return process.env.VUE_APP_BASE_API + "/shop-customer/import";
    },
  },
  created() {
    this.fetchRelationList();
  },
  methods: {
    formatDateTime,

    // 获取关联列表
    async fetchRelationList() {
      try {
        this.loading = true;
        const params = {
          page: this.pagination.page,
          pageSize: this.pagination.pageSize,
          shopName: this.searchForm.shopName,
          customerName: this.searchForm.customerName,
        };

        const response = await getShopCustomerList(params);

        if (response.code === 200) {
          this.relationList = response.data.list || [];
          this.pagination.total = response.data.pagination.total;
        } else {
          this.$message.error(response.message || "获取关联列表失败");
        }
      } catch (error) {
        console.error("获取关联列表失败:", error);
        this.$message.error("获取关联列表失败");
      } finally {
        this.loading = false;
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.page = 1;
      this.fetchRelationList();
    },

    // 重置搜索
    resetSearch() {
      this.searchForm.shopName = "";
      this.searchForm.customerName = "";
      this.handleSearch();
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.page = 1;
      this.fetchRelationList();
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.pagination.page = val;
      this.fetchRelationList();
    },

    // 表格选择改变
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },

    // 新增关联
    handleAdd() {
      this.isEdit = false;
      this.relationForm = {
        id: null,
        shopName: "",
        customerName: "",
      };
      this.dialogVisible = true;
    },

    // 编辑关联
    handleEdit(row) {
      this.isEdit = true;
      this.relationForm = {
        id: row.id,
        shopName: row.shopName,
        customerName: row.customerName,
      };
      this.dialogVisible = true;
    },

    // 删除关联
    handleDelete(row) {
      this.$confirm(
        `确定要删除店铺"${row.shopName}"与客户"${row.customerName}"的关联吗？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          try {
            const response = await deleteShopCustomer(row.id);

            if (response.code === 200) {
              this.$message.success("删除成功");
              this.fetchRelationList();
            } else {
              this.$message.error(response.message || "删除失败");
            }
          } catch (error) {
            console.error("删除失败:", error);
            this.$message.error("删除失败");
          }
        })
        .catch(() => {});
    },

    // 批量删除
    handleBatchDelete() {
      if (!this.selectedRows.length) {
        this.$message.warning("请选择要删除的数据");
        return;
      }

      const ids = this.selectedRows.map((row) => row.id).join(",");

      this.$confirm(
        `确定要删除选中的${this.selectedRows.length}条关联吗？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          try {
            const response = await batchDeleteShopCustomer(ids);

            if (response.code === 200) {
              this.$message.success("批量删除成功");
              this.fetchRelationList();
            } else {
              this.$message.error(response.message || "批量删除失败");
            }
          } catch (error) {
            console.error("批量删除失败:", error);
            this.$message.error("批量删除失败");
          }
        })
        .catch(() => {});
    },

    // 导出Excel
    async handleExport() {
      const response = await exportShopCustomer();
      const blob = new Blob([response], {
        type: "application/vnd.ms-excel",
      });
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `shop-customer-${new Date().toLocaleDateString()}.xlsx`;
      a.click();
    },

    // 上传前验证
    beforeUpload(file) {
      const isExcel = /\.(xlsx|xls)$/.test(file.name.toLowerCase());
      if (!isExcel) {
        this.$message.error("只能上传Excel文件！");
        return false;
      }

      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error("上传文件大小不能超过10MB！");
        return false;
      }

      return true;
    },

    // 上传成功
    onUploadSuccess(response) {
      if (response.code === 200) {
        const data = response.data || {};
        let message = response.message || "导入成功";

        // 如果有错误详情，显示详细信息
        if (data.errors > 0) {
          message += `\n${data.errors}条数据有问题已跳过`;
          if (data.errorDetails && data.errorDetails.length > 0) {
            this.$alert(
              `导入完成！\n\n统计信息：\n- 总共处理：${
                data.total
              }条\n- 成功导入：${data.imported}条\n- 跳过错误：${
                data.errors
              }条\n\n错误详情（前10条）：\n${data.errorDetails
                .slice(0, 10)
                .join("\n")}`,
              "导入结果",
              {
                confirmButtonText: "确定",
                type: "warning",
              }
            );
          } else {
            this.$message.warning(message);
          }
        } else {
          this.$message.success(message);
        }

        this.fetchRelationList();
      } else {
        this.$message.error(response.message || "导入失败");
      }
    },

    // 上传失败
    onUploadError(error) {
      console.error("上传失败:", error);
      this.$message.error("文件上传失败");
    },

    // 提交表单
    async handleSubmit() {
      try {
        await this.$refs.relationForm.validate();

        this.submitting = true;

        const response = this.isEdit
          ? await ShopCustomerUpdate(this.relationForm.id, this.relationForm)
          : await ShopCustomerAdd(this.relationForm);

        if (response.code === 200) {
          this.$message.success(this.isEdit ? "编辑成功" : "新增成功");
          this.dialogVisible = false;
          this.fetchRelationList();
        } else {
          this.$message.error(response.message || "操作失败");
        }
      } catch (error) {
        if (error.message !== "validation failed") {
          console.error("提交失败:", error);
          this.$message.error("操作失败");
        }
      } finally {
        this.submitting = false;
      }
    },

    // 对话框关闭
    handleDialogClose() {
      this.$refs.relationForm.resetFields();
    },
  },
};
</script>

<style scoped>
.shop-customer-container {
  min-height: calc(100vh - 50px);
}

.page-header-container {
  display: flex;
  align-items: center;
  background: #fff;
  padding: 15px 20px;
  border-radius: 6px;
  margin-bottom: 20px;
  border: 1px solid #e6ebf5;
}

.header-icon {
  font-size: 28px;
  margin-right: 15px;
  color: #e6a23c;
}

.header-text h1 {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.header-text p {
  font-size: 13px;
  color: #909399;
  margin-top: 4px;
}

.content-body {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.action-panel,
.data-table-panel {
  border-radius: 6px;
  border: 1px solid #e6ebf5;
  box-shadow: none;
}

.action-panel .el-card__body {
  padding: 15px 20px;
}
.data-table-panel .el-card__body {
  padding: 20px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.search-filters {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.search-filters .el-input {
  width: 200px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.el-table {
  border-radius: 4px;
}

.pagination-container {
  padding-top: 20px;
  text-align: right;
}

.el-dialog__wrapper >>> .relation-dialog {
  border-radius: 8px;
}

.form-tips {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 5px;
}
.form-tips i {
  margin-right: 4px;
}

.dialog-footer {
  text-align: right;
}
</style>
