<template>
  <div class="app-container">
    <!-- 查询 + 按钮 -->
    <el-card>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="88px">
        <el-form-item label="客户名称" prop="customerName">
          <el-input
            v-model="queryParams.customerName"
            placeholder="请输入客户名称"
            clearable
            style="width: 240px;"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
          <!-- 按钮权限：sale:clientele:add -->
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['sale:clientele:add']">添加</el-button>
          <!-- 按钮权限：sale:clientele:remove -->
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleBatchDelete" v-hasPermi="['sale:clientele:remove']">批量删除</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <br />

    <!-- 表格 -->
    <el-card>
      <el-table
        ref="table"
        border
        stripe
        v-loading="loading"
        :data="list"
        @selection-change="handleSelectionChange"
        style="width: 100%;"
      >
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <el-table-column label="客户编号" prop="customerNum" min-width="120" />
        <el-table-column label="客户名称" prop="customerName" min-width="140" />
        <el-table-column label="客户地址" prop="customerAddress" min-width="160" />
        <el-table-column label="客户等级" prop="customerLevel" min-width="100">
          <template slot-scope="scope">
            <span>{{ getCustomerLevelLabel(scope.row.customerLevel) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="联络人" prop="contactPerson" min-width="100" />
        <el-table-column label="联系电话" prop="contactPhone" min-width="120" />
        <el-table-column label="应收客户" prop="receivableCustomer" min-width="120" />
        <el-table-column label="收款客户" prop="payeeCustomer" min-width="120" />
        <el-table-column label="送货客户" prop="deliveryCustomer" min-width="120" />
        <el-table-column label="信用控制" prop="creditControl" min-width="100">
          <template slot-scope="scope">
            <el-tag :type="getCreditControlTagType(scope.row.creditControl)">
              {{ getCreditControlLabel(scope.row.creditControl) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="开户银行" prop="bankName" min-width="140" />
        <el-table-column label="银行账号" prop="bankAccount" min-width="160" />
        <el-table-column label="开票类型" prop="invoiceType" min-width="100">
          <template slot-scope="scope">
            <span>{{ getInvoiceTypeLabel(scope.row.invoiceType) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="客户渠道" prop="customerChannel" min-width="100" />
        <el-table-column label="检疫统计类型" prop="quarantineStatType" min-width="120" />
        <el-table-column label="品牌" prop="brand" min-width="100" />
        <el-table-column label="盖章颜色" prop="stampColor" min-width="100" />
        <el-table-column label="状态" prop="status" min-width="90">
          <template slot-scope="scope">
            <el-tag v-if="String(scope.row.status) === '1' || String(scope.row.status) === '启用'" type="success">启用</el-tag>
            <el-tag v-else-if="String(scope.row.status) === '0' || String(scope.row.status) === '停用'" type="danger">停用</el-tag>
            <el-tag v-else>{{ scope.row.status == null ? "-" : scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="生产经营许可证" prop="businessPermit" min-width="160" />
        <el-table-column label="营业执照" prop="businessLicense" min-width="140" />
        <el-table-column label="税号" prop="taxNumber" min-width="140" />
        <el-table-column label="备注" prop="remark" min-width="160" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="180" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
            <!-- 按钮权限：sale:clientele:edit -->
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" style="margin-right: 8px" v-hasPermi="['sale:clientele:edit']">编辑</el-button>
            <!-- 按钮权限：sale:clientele:remove -->
            <el-popconfirm :title="'确定要删除这条数据吗？'" @confirm="handleDelete(scope.row)" v-hasPermi="['sale:clientele:remove']">
              <el-button size="mini" type="text" slot="reference" icon="el-icon-delete">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

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

    <!-- 新增/编辑/查看 弹框 -->
    <el-dialog :title="title" :visible.sync="open" width="1100px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" :disabled="isView" label-width="110px">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="客户编号" prop="customerNum">
              <el-input v-model="form.customerNum" placeholder="请输入客户编号" clearable :disabled="isEdit" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="form.customerName" placeholder="请输入客户名称" clearable @input="syncCustomerName" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- textarea 单独占一行（字段排序：客户地址排在客户名称后） -->
        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="客户地址" prop="customerAddress">
              <el-input type="textarea" v-model="form.customerAddress" placeholder="请输入客户地址" :rows="2" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="客户等级" prop="customerLevel">
              <el-select v-model="form.customerLevel" placeholder="请选择客户等级" clearable style="width: 100%;">
                <el-option v-for="opt in customerLevelOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联络人" prop="contactPerson">
              <el-input v-model="form.contactPerson" placeholder="请输入联络人" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="应收客户" prop="receivableCustomer">
              <el-input v-model="form.receivableCustomer" placeholder="自动同步客户名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收款客户" prop="payeeCustomer">
              <el-input v-model="form.payeeCustomer" placeholder="自动同步客户名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="送货客户" prop="deliveryCustomer">
              <el-input v-model="form.deliveryCustomer" placeholder="自动同步客户名称" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="信用控制" prop="creditControl">
              <el-select v-model="form.creditControl" placeholder="请选择信用控制" clearable style="width: 100%;">
                <el-option v-for="opt in creditControlOptions" :key="opt.value" :value="opt.value" :label="opt.label"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开户银行" prop="bankName">
              <el-input v-model="form.bankName" placeholder="请输入开户银行" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="银行账号" prop="bankAccount">
              <el-input v-model="form.bankAccount" placeholder="请输入银行账号" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="开票类型" prop="invoiceType">
              <el-select v-model="form.invoiceType" placeholder="请选择开票类型" clearable style="width: 100%;">
                <el-option v-for="opt in invoiceTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户渠道" prop="customerChannel">
              <el-input v-model="form.customerChannel" placeholder="请输入客户渠道" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="检疫统计类型" prop="quarantineStatType">
              <el-input v-model="form.quarantineStatType" placeholder="请输入检疫统计类型" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="form.brand" placeholder="请输入品牌" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="盖章颜色" prop="stampColor">
              <el-input v-model="form.stampColor" placeholder="请输入盖章颜色" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" clearable style="width: 100%;">
                <el-option v-for="opt in statusOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="生产经营许可证" prop="businessPermit">
              <el-input v-model="form.businessPermit" placeholder="请输入生产经营许可证" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="营业执照" prop="businessLicense">
              <el-input v-model="form.businessLicense" placeholder="请输入营业执照" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="税号" prop="taxNumber">
              <el-input v-model="form.taxNumber" placeholder="请输入税号" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- textarea 单独占一行（字段排序：备注排在最后） -->
        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" :rows="2" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancel">取 消</el-button>
        <el-button size="small" type="primary" v-if="!isView" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getClientelePage, getClienteleById, addClientele, editClientele, deleteClientele } from "@/api/sale/clientele";
export default {
  name: "SaleClientele",
  data() {
    return {
      /** 表格加载状态 */
      loading: false,
      /** 总条数（分页） */
      total: 0,
      /** 列表数据 */
      list: [],
      /** 批量删除按钮禁用控制：未选中任何行时为 true */
      multiple: true,
      /** 选中的行 */
      selection: [],
      /** 查询参数（包含 pageNum/pageSize） */
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerName: null,
      },
      /** 弹框标题 */
      title: "",
      /** 弹框开关 */
      open: false,
      /** 是否查看模式（只读） */
      isView: false,
      /** 是否编辑模式（禁用客户编号） */
      isEdit: false,
      /** 表单数据 */
      form: {},
      /** 表单校验规则 */
      rules: {
        customerNum: [{ required: true, message: "请输入客户编号", trigger: "blur" }],
        customerName: [{ required: true, message: "请输入客户名称", trigger: "blur" }],
      },
      /** 客户等级选项（默认 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 },
      ],
      /**
       * 开票类型选项（默认项 value=0）
       * 同上，避免 label 为 "" 时下拉框显示成数字 0。
       */
      invoiceTypeOptions: [
        { label: "-", value: 0 },
        { label: "普票", value: 1 },
        { label: "增票", value: 2 },
      ],
      /** 状态选项（默认 启用） */
      statusOptions: [
        { label: "启用", value: 1 },
        { label: "停用", value: 0 },
      ],
    };
  },
  created() {
    /** 初始化加载列表 */
    this.getList();
  },
  methods: {
    /** 客户等级 value -> label（用于列表展示） */
    getCustomerLevelLabel(val) {
      const v = val == null ? "" : String(val);
      const opt = (this.customerLevelOptions || []).find((x) => x && String(x.value) === v);
      if (opt) return opt.label;
      return val == null ? "-" : val;
    },
    /** 信用控制 value -> label（用于列表展示） */
    getCreditControlLabel(val) {
      const v = val == null ? "" : String(val);
      const opt = (this.creditControlOptions || []).find((x) => x && String(x.value) === v);
      if (opt) return opt.label;
      return val == null ? "-" : val;
    },
    /** 信用控制 tag 类型（用于列表展示） */
    getCreditControlTagType(val) {
      const label = this.getCreditControlLabel(val);
      if (label === "启用" || label === "是") return "success";
      if (label === "不启用" || label === "否") return "info";
      return "info";
    },
    /** 开票类型 value -> label（用于列表展示） */
    getInvoiceTypeLabel(val) {
      const v = val == null ? "" : String(val);
      const opt = (this.invoiceTypeOptions || []).find((x) => x && String(x.value) === v);
      // 允许空字符串作为“空开票类型”
      if (opt) return opt.label;
      return val == null ? "-" : val;
    },
    /** 获取客户档案列表（分页），TODO：对接真实接口 */
    getList() {
      getClientelePage(this.queryParams).then(res => {
        this.list = res.data.records;
        this.total = res.data.total;
        this.loading = false;
      })
    },
    /** 查询：重置页码并刷新列表 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 表格勾选变化：更新 selection 和批量删除按钮状态 */
    handleSelectionChange(val) {
      this.selection = val || [];
      this.multiple = this.selection.length === 0;
    },
    /** 点击添加：预留新增逻辑（弹框/路由） */
    handleAdd() {
      /** 打开新增弹框 */
      this.reset();
      this.isView = false;
      this.isEdit = false;
      this.title = "新增客户";
      this.open = true;
    },
    /** 批量删除：预留批量删除逻辑 */
    handleBatchDelete() {
      let params = {
        ids: this.selection.map(item => item.id).join(',')
      }
      deleteClientele(params).then(res => {
        this.getList();
        this.$message.success("删除成功");
      })
    },
    /** 查看：预留查看详情逻辑 */
    handleView(row) {
      /** 打开查看弹框（只读） */
      this.reset();
      let params = {
        id: row.id
      }
      getClienteleById(params).then(res => {
        this.form = res.data;
        this.isView = true;
        this.isEdit = false;
        this.title = "查看客户";
        this.open = true;
      })
    },
    /** 编辑：预留编辑逻辑 */
    handleUpdate(row) {
      /** 打开编辑弹框 */
      this.reset();
      let params = {
        id: row.id
      }
      getClienteleById(params).then(res => {
        this.form = res.data;
        this.isView = false;
        this.isEdit = true;
        this.title = "编辑客户";
        this.open = true;
      })
    },
    /** 删除单条：预留删除逻辑 */
    handleDelete(row) {
      let params = {
        ids: row.id
      }
      deleteClientele(params).then(res => {
        this.getList();
        this.$message.success("删除成功");
      })
    },
    /** 重置弹框表单并设置默认值 */
    reset() {
      this.form = {
        customerNum: null,
        customerName: null,
        customerAddress: null,
        customerLevel: 1,
        contactPerson: null,
        contactPhone: null,
        receivableCustomer: null,
        payeeCustomer: null,
        deliveryCustomer: null,
        creditControl: 0,
        bankName: null,
        bankAccount: null,
        invoiceType: "",
        customerChannel: null,
        quarantineStatType: null,
        brand: null,
        stampColor: null,
        status: 1,
        businessPermit: null,
        businessLicense: null,
        taxNumber: null,
        remark: null,
      };
      /** 清理表单校验 */
      this.$nextTick(() => {
        if (this.$refs.form) this.$refs.form.clearValidate();
      });
    },
    /** 关闭弹框 */
    cancel() {
      this.open = false;
      this.isEdit = false;
      this.reset();
    },
    /** 客户名称变化时：同步应收/收款/送货客户为客户名称 */
    syncCustomerName() {
      const name = this.form.customerName;
      this.form.receivableCustomer = name;
      this.form.payeeCustomer = name;
      this.form.deliveryCustomer = name;
    },
    /** 提交新增/编辑表单（校验通过后预留接口） */
    submitForm() {
      if (!this.$refs.form) return;
      this.$refs.form.validate((valid) => {
        if (!valid) return;
        // TODO: 对接新增/编辑接口
        if (this.isEdit) {
          editClientele(this.form).then(res => {
            this.$message.success("编辑成功");
            this.open = false;
            this.getList();
          })
        } else {
          addClientele(this.form).then(res => {
            this.$message.success("新增成功");
            this.open = false;
            this.getList();
          })
        }
      });
    },
  },
};
</script>
