<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 客户列表区域 -->
      <el-col :span="5" style="border-right: 1px solid #e4e7ed;">
        <div style="font-weight: 900;">客户列表</div>
        <!-- 搜索区域 -->
        <div style="display: flex; align-items: center; gap: 5px; margin-top: 10px;">
          <el-input 
            style="flex: 1;" 
            prefix-icon="el-icon-search" 
            placeholder="输入客户编码搜索"
            v-model="queryParams.customerCode" 
            @change="getCustomerList" 
            clearable
          ></el-input>
          <el-button icon="el-icon-search" @click="toggleQuery"></el-button>
          <el-button type="primary" icon="el-icon-plus" style="margin-left: 0;" @click="handleAdd"></el-button>
        </div>
        <!-- 高级查询区域 -->
        <div v-show="showQuery" style="display: flex; align-items: center; gap: 5px; margin-top: 10px;">
          <el-select 
            style="width: 100px;" 
            v-model="queryParams.industry" 
            placeholder="客户行业" 
            clearable
            @change="getCustomerList"
          >
            <el-option 
              v-for="item in dict.type.customer_industry" 
              :key="item.value" 
              :label="item.label"
              :value="item.value" 
            />
          </el-select>
          <el-select 
            style="width: 100px;" 
            v-model="queryParams.customerLevel" 
            placeholder="客户等级" 
            clearable
            @change="getCustomerList"
          >
            <el-option 
              v-for="item in dict.type.customer_level" 
              :key="item.value" 
              :label="item.label"
              :value="item.value" 
            />
          </el-select>
        </div>
        <!-- 客户列表 -->
        <div>
          <KLPList 
            :listData="customerList" 
            listKey="customerId" 
            :loading="customerLoading" 
            field1="customerCode"
            field4="companyName" 
            @item-click="handleItemClick"
          >
            <template slot="actions" slot-scope="{ item }">
              <el-button type="danger" size="mini" @click="handleDelete(item)" icon="el-icon-delete"></el-button>
            </template>
          </KLPList>
        </div>
      </el-col>

      <!-- 右侧内容区域 -->
      <el-col :span="19">
        <el-tabs v-model="activeTab" type="border-card" v-if="currentCustomer && currentCustomer.customerId">
          <!-- 客户详情标签页 -->
          <el-tab-pane label="客户详情" name="detail">
            <CustomerDetail 
              :customer="currentCustomer" 
              :dict="dict"
            />
          </el-tab-pane>
          <!-- 客户编辑标签页 -->
          <el-tab-pane label="信息编辑" name="edit">
            <CustomerEdit 
              :customer="currentCustomer" 
              :dict="dict"
              :update-loading="updateLoading"
              @detail-change="handleDetailChange"
              @save-change="handleSaveChange"
            />
          </el-tab-pane>
          <!-- 历史订单标签页 -->
          <el-tab-pane label="历史订单" name="transaction">
            <div>
              <CustomerOrder 
                :customer="currentCustomer" 
                :dict="dict"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
        <el-empty v-else style="margin-top: 20px;" description="选择客户查看详情"></el-empty>
      </el-col>
    </el-row>

    <!-- 添加客户对话框 -->
    <el-dialog 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="customerCode">
          <el-input v-model="form.customerCode" placeholder="请输入客户编码" />
        </el-form-item>
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系方式" prop="contactWay">
          <el-input v-model="form.contactWay" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="所属行业" prop="industry">
          <el-select v-model="form.industry" placeholder="请选择所属行业" clearable>
            <el-option 
              v-for="item in dict.type.customer_industry" 
              :key="item.value" 
              :label="item.label"
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户等级" prop="customerLevel">
          <el-select v-model="form.customerLevel" placeholder="请选择客户等级" clearable>
            <el-option 
              v-for="item in dict.type.customer_level" 
              :key="item.value" 
              :label="item.label"
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入客户地址" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="银行信息" prop="transactionRecords">
          <JSONTableInput 
            v-model="form.bankInfo"
            :columns="[{ prop: 'bankName', label: '银行名称' }, { prop: 'bankAccount', label: '银行账号' }]" 
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import KLPList from '@/components/KLPUI/KLPList/index.vue'
import JSONTableInput from '../components/JSONTableInput.vue'
import CustomerDetail from '../components/CustomerInfo.vue'
import CustomerEdit from '../components/CustomerEdit.vue'
import CustomerOrder from '../components/CustomerOrder.vue'

import { listCustomer, addCustomer, updateCustomer, delCustomer } from '@/api/crm/customer'

export default {
  name: 'CustomerPage',
  components: {
    KLPList,
    JSONTableInput,
    CustomerDetail,
    CustomerEdit,
    CustomerOrder
  },
  dicts: ['customer_industry', 'customer_level'],
  data() {
    return {
      customerList: [],
      showQuery: false,
      queryParams: {
        industry: '',
        customerLevel: '',
        customerCode: '',
        pageNum: 1,
        pageSize: 1000
      },
      total: 0,
      activeTab: 'detail',
      customerLoading: false,
      currentCustomer: {},
      open: false,
      form: {},
      buttonLoading: false,
      updateLoading: false,
      debounceTimer: null,
      rules: {
        customerCode: [{ required: true, message: '请输入客户编码', trigger: 'blur' }],
        companyName: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
        contactPerson: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
        contactWay: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
        industry: [{ required: true, message: '请选择所属行业', trigger: 'change' }],
        customerLevel: [{ required: true, message: '请选择客户等级', trigger: 'change' }],
        address: [{ required: true, message: '请输入客户地址', trigger: 'blur' }],
      }
    }
  },
  computed: {
    currentCustomerId() {
      return this.currentCustomer.customerId || undefined
    }
  },
  mounted() {
    this.getCustomerList();
  },
  beforeDestroy() {
    clearTimeout(this.debounceTimer);
  },
  methods: {
    toggleQuery() {
      this.showQuery = !this.showQuery
    },

    debounce(fn, delay) {
      return (...args) => {
        if (this.debounceTimer) clearTimeout(this.debounceTimer);
        this.debounceTimer = setTimeout(() => {
          fn.apply(this, args);
        }, delay);
      };
    },

    async handleSaveChange() {
      if (!this.currentCustomerId || this.updateLoading) return;

      try {
        this.updateLoading = true;
        const params = { ...this.currentCustomer };
        await updateCustomer(params);
        this.$message({
          type: 'success',
          message: '客户信息更新成功'
        });
        this.syncCustomerList(params);
      } catch (error) {
        this.$message({
          type: 'error',
          message: '更新失败：' + (error.msg || '服务器异常')
        });
      } finally {
        this.updateLoading = false;
      }
    },

    handleDetailChange() {
      // 仅作为事件透传，逻辑保留在主页面
    },

    syncCustomerList(updatedCustomer) {
      const index = this.customerList.findIndex(item => item.customerId === updatedCustomer.customerId);
      if (index > -1) {
        this.$set(this.customerList, index, { ...this.customerList[index], ...updatedCustomer });
      }
    },

    getCustomerList() {
      this.customerLoading = true;
      listCustomer(this.queryParams).then(response => {
        this.customerList = response.rows || [];
        this.total = response.total || 0;
        this.customerLoading = false;
      }).catch(() => {
        this.customerLoading = false;
        this.$message.error('获取客户列表失败');
      });
    },

    handleItemClick(item) {
      this.currentCustomer = { ...item };
      this.activeTab = 'detail';
    },

    reset() {
      this.form = {
        customerId: undefined,
        customerCode: undefined,
        companyName: undefined,
        contactPerson: undefined,
        contactWay: undefined,
        industry: undefined,
        customerLevel: undefined,
        address: undefined,
        bankInfo: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined
      };
      if (this.$refs.form) this.$refs.form.resetFields();
    },

    handleAdd() {
      this.reset();
      this.open = true;
    },

    submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.buttonLoading = true;
          try {
            await addCustomer(this.form);
            this.$message({
              message: '客户录入成功',
              type: 'success'
            });
            this.open = false;
            this.getCustomerList();
          } catch (error) {
            this.$message.error('录入失败：' + (error.msg || '服务器异常'));
          } finally {
            this.buttonLoading = false;
          }
        }
      });
    },

    cancel() {
      this.reset();
      this.open = false;
    },

    handleDelete(item) {
      this.$confirm('确定删除该客户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await delCustomer(item.customerId);
        this.$message.success('删除成功');
        this.getCustomerList();
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    }
  },
}
</script>

<style scoped>
.app-container {
  padding: 16px;
  height: 100%;
  box-sizing: border-box;
}

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