<template>
  <div class="app-container">
    <el-row :gutter="12" class="maintenance-layout">
      <!-- 左侧：树状结构 -->
      <el-col :span="4" class="maintenance-left">
        <el-card shadow="never" class="maintenance-tree-card">
          <el-tree
            :data="treeData"
            :props="treeProps"
            node-key="key"
            highlight-current
            default-expand-all
            :expand-on-click-node="false"
            height="calc(100vh - 210px)"
            @node-click="handleTreeNodeClick"
          />
        </el-card>
      </el-col>

      <!-- 右侧：内容预留（后续接维护列表/详情/表格等） -->
      <el-col :span="20" class="maintenance-right">
        <el-card shadow="never" class="maintenance-right-card">
          <!-- 顶部按钮组 -->
          <div class="right-actions">
            <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAdd">新增</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" :disabled="!currentRow" @click="handleRemove">移除</el-button>
            <el-button size="mini" icon="el-icon-edit" :disabled="!currentRow" @click="handleAdjust">调整</el-button>
          </div>

          <!-- 底部表格 -->
          <el-table
            ref="customerTable"
            :data="customerList"
            border
            stripe
            class="right-table"
            highlight-current-row
            @current-change="handleCurrentChange"
          >
            <el-table-column label="客户编号" align="center" prop="customerNum" min-width="120" />
            <el-table-column label="客户名称" align="center" prop="customerName" min-width="150" />
            <el-table-column label="客户等级" align="center" prop="customerLevel" min-width="110">
              <template slot-scope="scope">
                <span>{{ getCustomerLevelLabel(scope.row.customerLevel) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="应收客户" align="center" prop="receivableCustomer" min-width="130" />
            <el-table-column label="收款客户" align="center" prop="payeeCustomer" min-width="130" />
            <el-table-column label="信用控制" align="center" prop="creditControl" min-width="120">
              <template slot-scope="scope">
                <span>{{ getCreditControlLabel(scope.row.creditControl) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="客户渠道" align="center" prop="customerChannel" min-width="120" />
            <el-table-column label="备注" align="center" prop="remark" min-width="160" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增弹框：市场 + 客户（客户接口暂无时用模拟数据/预留接口逻辑） -->
    <el-dialog title="新增" :visible.sync="addDialogOpen" width="600px" append-to-body>
      <el-form
        ref="addForm"
        :model="addForm"
        :rules="addRules"
        label-width="100px"
        size="small"
      >
        <el-form-item label="市场" prop="marketNum">
          <el-select v-model="addForm.marketNum" placeholder="请选择市场" style="width: 100%" filterable>
            <el-option
              v-for="item in marketOptions"
              :key="item.marketNum"
              :label="item.marketName"
              :value="item.marketNum"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="客户" prop="customerNum">
          <el-select v-model="addForm.customerNum" placeholder="请选择客户" style="width: 100%" filterable>
            <el-option
              v-for="item in addCustomerOptions"
              :key="item.customerNum"
              :label="item.customerName"
              :value="item.customerNum"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="addDialogOpen = false">取 消</el-button>
        <el-button size="small" type="primary" @click="submitAddForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 调整弹框：当前市场/客户/新市场（当前市场&客户禁用） -->
    <el-dialog title="调整" :visible.sync="adjustDialogOpen" width="650px" append-to-body>
      <el-form
        ref="adjustForm"
        :model="adjustForm"
        :rules="adjustRules"
        label-width="100px"
        size="small"
      >
        <el-form-item label="当前市场" prop="currentMarketNum">
          <el-select v-model="adjustForm.currentMarketNum" style="width: 100%" disabled filterable>
            <el-option
              v-for="item in marketOptions"
              :key="item.marketNum"
              :label="item.marketName"
              :value="item.marketNum"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="客户" prop="customerNo">
          <el-input v-model="adjustForm.customerName" placeholder="客户" disabled />
        </el-form-item>

        <el-form-item label="新市场" prop="newMarketNum">
          <el-select v-model="adjustForm.newMarketNum" placeholder="请选择新市场" style="width: 100%" filterable>
            <el-option
              v-for="item in marketOptions"
              :key="item.marketNum"
              :label="item.marketName"
              :value="item.marketNum"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="adjustDialogOpen = false">取 消</el-button>
        <el-button size="small" type="primary" @click="submitAdjustForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getBazaarList } from "@/api/baseInfo/bazaar";
import { getMaintenancePage, addMaintenance, editMaintenance, deleteMaintenance, getMaintenanceTree } from "@/api/sale/maintenance";
import { getClienteleList } from "@/api/sale/clientele";

export default {
  name: "Maintenance",
  data() {
    return {
      /** 左侧树数据（默认空：由接口方法初始化） */
      treeData: [],

      /** el-tree props 映射：children/label字段名 */
      treeProps: {
        children: "children",
        label: "label",
      },

      /** 当前选中树节点 key */
      currentTreeKey: null,

      /** 当前选中树节点 label */
      currentTreeLabel: "",

      /** 预留：后续查询参数（示例：marketNum 来自树节点） */
      queryParams: {
        marketNum: null,
        pageNum: 1,
        pageSize: 10,
      },

      /** 当前市场下：维护列表（客户列表） */
      customerList: [],

      /** 表格当前高亮行（单选） */
      currentRow: null,

      /** 所有客户（预留：当前没有接口时，用模拟数据兜底） */
      allCustomerList: [],

      /**
       * 模拟：市场 -> 已绑定客户编号列表
       * 规则：新增弹框里的“客户”只展示“当前市场未绑定”的客户
       */
      boundCustomerNosByMarketNum: {
        sc001: ["C001", "C002"],
        sc002: ["C003"],
      },

      /** 新增弹框开关 */
      addDialogOpen: false,

      /** 新增表单 */
      addForm: {
        marketNum: null,
        customerNo: null,
      },

      /** 新增表单校验规则 */
      addRules: {
        marketNum: [{ required: true, message: "请选择市场", trigger: "change" }],
        customerNum: [{ required: true, message: "请选择客户", trigger: "change" }],
      },

      /** 市场下拉选项（来自市场管理：marketNum / marketName） */
      marketOptions: [],

      /** 新增弹框里：当前市场未绑定的客户选项 */
      addCustomerOptions: [],

      /** 调整弹框开关 */
      adjustDialogOpen: false,

      /** 调整表单（当前市场/客户/新市场） */
      adjustForm: {
        currentMarketNum: null,
        customerNo: null,
        customerName: "",
        newMarketNum: null,
      },

      /** 调整表单校验规则 */
      adjustRules: {
        newMarketNum: [{ required: true, message: "请选择新市场", trigger: "change" }],
      },
       /** 客户等级选项（默认 1级） */
      customerLevelOptions: [
        { label: "1级", value: 1 },
        { label: "2级", value: 2},
        { label: "3级", value: 3 },
        { label: "4级", value: 4 },
        { label: "5级", value: 5 },
      ],
      /**
       * 信用控制选项（默认项 value=0）
       * 注意：label 不能用 "" —— Element UI 的 el-option 在 label 为假值时会用 value 作为展示，会误显示 0。
       */
      creditControlOptions: [
        { label: "-", value: 0 },
        { label: "启用", value: 1 },
        { label: "不启用", value: 2 },
      ],
    };
  },
  created() {
    this.fetchMarketOptions();
    this.getClientele();
    /** 初始化：拉取左侧树形数据（预留接口） */
    this.fetchMaintenanceTreeData();
  },
  methods: {
    /**
     * 客户等级 value -> label（用于列表展示）
     * 兼容：后端返回数字/字符串，或已经是“1级”这类文案。
     */
    getCustomerLevelLabel(val) {
      if (val == null || val === "") return "-"
      const raw = String(val)
      // 已经是文案时直接返回
      if (raw.includes("级")) return raw
      const hit = (this.customerLevelOptions || []).find((item) => item && String(item.value) === raw)
      return hit ? hit.label : raw
    },
    /**
     * 信用控制 value -> label（用于列表展示）
     * 兼容：后端返回数字/字符串，或已经是“启用/不启用”文案。
     */
    getCreditControlLabel(val) {
      if (val == null || val === "") return "-"
      const raw = String(val)
      // 已经是文案时直接返回
      if (raw === "启用" || raw === "不启用") return raw
      const hit = (this.creditControlOptions || []).find((item) => item && String(item.value) === raw)
      return hit ? hit.label : raw
    },
    /**
     * 预留：获取左侧树形数据接口方法
     * - TODO：接入真实接口，把返回的“线路/层级 -> 市场”转换成 el-tree 所需结构
     * - 当前：先用模拟数据兜底，保证页面可用
     */
    fetchMaintenanceTreeData() {
     // getMaintenanceTree({}).then(res => {
      //   this.treeData = res.data;
      // });
      /** 模拟数据：第一线 -> 市场A(sc001)；第二线 -> 市场B(sc002) */
      const simulatedTreeData = [
        {
          key: "line1",
          label: "第一线",
          disabled: true,
          children: [
            { key: "marketA", label: "市场A", marketNum: "sc001" },
          ],
        },
        {
          key: "line2",
          label: "第二线",
          disabled: true,
          children: [
            { key: "marketB", label: "市场B", marketNum: "sc002" },
          ],
        },
      ];

      this.treeData = simulatedTreeData;
    },
    /**
     * 左侧树点击：高亮当前节点，并更新预留查询参数
     * @param {Object} data 被点击的节点数据
     */
    handleTreeNodeClick(data) {
      /** 第一层节点不允许选择：直接忽略 */
      if (data && data.disabled) return;
      this.currentTreeKey = data && data.key ? data.key : null;
      this.currentTreeLabel = data && data.label ? data.label : "";

      // 预留接口字段映射：后续接真实接口时，把 marketNum/line 等映射到查询条件
      this.queryParams.marketNum = data && data.marketNum ? data.marketNum : null;

      /** 模拟：切换市场后，刷新右侧维护列表 */
      this.loadCustomerListByMarketNum(this.queryParams.marketNum);

      /** 切换市场后清空高亮 */
      this.currentRow = null;
      if (this.$refs.customerTable) this.$refs.customerTable.setCurrentRow(null);
    },

    /**
     * 预留：获取“市场下拉选项”接口（当前从市场管理 bazaar page 获取兜底）
     */
    fetchMarketOptions() {
      getBazaarList({}).then((res) => {
        this.marketOptions = res.data;
      });
    },

    /**
     * 模拟/预留：根据市场编号加载维护客户列表
     * @param {string|null} marketNum 当前选择市场
     */
    loadCustomerListByMarketNum(marketNum) {
        let params = {
            marketNum: marketNum,
            pageNum: 1,
            pageSize: 10,
        }
        getMaintenancePage(params).then(res => {
            this.customerList = res.data.records;
        });
    },
    /** 获取客户列表   */
    getClientele() {
        getClienteleList({}).then(res => {
            this.allCustomerList = res.data;
        });
    },

    /**
     * 新增弹框：刷新“未绑定任何市场的客户”下拉选项
     * 规则：需要找到“当前没有绑定到市场的客户”
     */
    updateAddCustomerOptions() {
      const boundSet = new Set();
      Object.keys(this.boundCustomerNosByMarketNum || {}).forEach((k) => {
        (this.boundCustomerNosByMarketNum[k] || []).forEach((no) => boundSet.add(String(no)));
      });

      this.addCustomerOptions = (this.allCustomerList || []).filter((c) => !boundSet.has(String(c.customerNo)));

      /** 若当前已选客户不在可选范围，则清空 */
      if (this.addForm.customerNo && !this.addCustomerOptions.some((c) => c.customerNo === this.addForm.customerNo)) {
        this.addForm.customerNo = null;
      }
    },

    /**
     * 新增按钮：打开弹框（市场 + 客户）
     */
    handleAdd() {

      /** 新增时不带入当前选中的市场值 */
      this.addForm.marketNum = null;
      this.addForm.customerNo = null;

      /** 刷新可选客户：只展示“未绑定任何市场”的客户 */
      this.updateAddCustomerOptions();

      this.addDialogOpen = true;
    },

    /**
     * 移除按钮：删除当前选中行
     */
    handleRemove() {
      if (!this.currentRow) {
        this.$message.warning("请先选择一条数据");
        return;
      }

      /** 获取提示信息：当前市场/客户 */
      const marketNum = this.queryParams.marketNum != null ? String(this.queryParams.marketNum) : "";
      const marketName = this.getMarketNameByNum(marketNum) || (this.currentTreeLabel || "");
      const customerNum  = this.currentRow.customerNum != null ? String(this.currentRow.customerNum) : "";
      const customerName = this.currentRow.customerName || "";

      this.$confirm(
        `确定移除当前客户【${customerName}(${customerNum })】与市场【${marketName}(${marketNum})】的绑定关系吗？`,
        "提示",
        { type: "warning" }
      )
        .then(() => {
          console.log(this.currentRow);
          /** TODO：接入移除接口（应携带：marketNum + customerNo） */
          let params = {
            ids: this.currentRow.id,
          }
          deleteMaintenance(params).then(res => {
            this.$message.success("移除成功");
            this.loadCustomerListByMarketNum(this.currentRow.marketNum);
            this.currentRow = null;
            if (this.$refs.customerTable) this.$refs.customerTable.setCurrentRow(null);
          });
        })
        .catch(() => {});
    },

    /**
     * 根据 marketNum 获取市场名称
     * @param {string} marketNum 市场编号
     * @return {string} marketName
     */
    getMarketNameByNum(marketNum) {
      const num = marketNum != null ? String(marketNum) : "";
      const hit = (this.marketOptions || []).find((m) => String(m.marketNum) === num);
      return hit ? hit.marketName : "";
    },

    /**
     * 新增弹框提交
     */
    submitAddForm() {
      this.$refs.addForm.validate((valid) => {
        if (!valid) return;
      
        let params = {
          marketNum: this.addForm.marketNum,
          customerNums: this.addForm.customerNum,
        }
        /** TODO：接入新增维护接口（应携带：marketNum + customerNo） */
        addMaintenance(params).then(res => {
            this.$message.success("新增成功");
            this.addDialogOpen = false;
            this.loadCustomerListByMarketNum(this.addForm.marketNum);
        });
      });
    },

    /**
     * 调整按钮：预留接口（例如批量调整信用控制/客户渠道等）
     */
    handleAdjust() {
      if (!this.currentRow) {
        this.$message.warning("请先选择一条数据");
        return;
      }
      if (!this.queryParams.marketNum) {
        this.$message.warning("请先选择一个市场");
        return;
      }

      /** 初始化调整表单：当前市场/客户固定，新市场待选 */
      this.adjustForm = {
        currentMarketNum: this.queryParams.marketNum,
        customerNo: this.currentRow.customerNo,
        customerName: this.currentRow.customerName,
        newMarketNum: null,
      };
      this.adjustDialogOpen = true;
    },

    /**
     * 表格当前行变化（单选高亮）
     * @param {Object|null} currentRow 当前行
     */
    handleCurrentChange(currentRow) {
      this.currentRow = currentRow || null;
    },

    /**
     * 调整弹框提交：把当前客户从“当前市场”调整到“新市场”
     */
    submitAdjustForm() {
      this.$refs.adjustForm.validate((valid) => {
        if (!valid) return;

        const currentMarketKey = this.adjustForm.currentMarketNum != null ? String(this.adjustForm.currentMarketNum) : null;
        const newMarketKey = this.adjustForm.newMarketNum != null ? String(this.adjustForm.newMarketNum) : null;
        const customerNo = this.adjustForm.customerNo;
        if (!currentMarketKey || !newMarketKey || !customerNo) return;

        if (currentMarketKey === newMarketKey) {
          this.$message.warning("新市场不能与当前市场相同");
          return;
        }

        /** TODO：接入真实调整接口（应携带：customerNo + currentMarketNum + newMarketNum） */
        const currentBound = this.boundCustomerNosByMarketNum[currentMarketKey] || [];
        this.boundCustomerNosByMarketNum[currentMarketKey] = currentBound.filter((no) => no !== customerNo);

        const nextBound = this.boundCustomerNosByMarketNum[newMarketKey] || [];
        if (!nextBound.includes(customerNo)) nextBound.push(customerNo);
        this.boundCustomerNosByMarketNum[newMarketKey] = nextBound;

        /** 同步客户绑定字段（模拟）：调整后写入新 marketNum */
        const idx = (this.allCustomerList || []).findIndex((c) => String(c.customerNo) === String(customerNo));
        if (idx >= 0) this.$set(this.allCustomerList[idx], "marketNum", newMarketKey);

        /** 刷新右侧列表并关闭弹框 */
        this.loadCustomerListByMarketNum(currentMarketKey);
        this.adjustDialogOpen = false;
        this.$message.success("调整成功（模拟）");
      });
    },
  },
};
</script>

<style scoped lang="scss">
.maintenance-layout {
  height: 100%;
  display: flex;
}

.maintenance-left,
.maintenance-right {
  height: 100%;
}

.maintenance-tree-card,
.maintenance-right-card {
  height: 100%;
}

.right-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

/* 右侧标题副标题：靠右展示 */
.right-subtitle {
  font-size: 13px;
  color: #606266;
  font-weight: 400;
  margin-left: 12px;
}

.right-actions {
  display: flex;
  gap: 10px;
  padding: 0 0 10px 0;
}

/** 让右侧表格在 el-card 内纵向撑满 */
::v-deep .maintenance-right-card > .el-card__body {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 0;
  padding: 12px;
}

.right-table {
  flex: 1 1 0;
  min-height: 800px;
}

/** 单选高亮：浅蓝色背景 */
::v-deep .right-table .el-table__body tr.current-row > td {
  background-color: #d9ecff !important;
}
</style>