<template>
  <el-drawer
    v-model="visible"
    title="修改客户关怀"
    direction="rtl"
    size="80%"
    @close="handleClose"
    destroy-on-close
    class="custom-drawer"
  >
    <div class="drawer-body" v-loading="loading">
      <el-form ref="careRef" :model="form" :rules="rules" label-width="100px" label-position="right">
        <div class="dialog-section no-border">
          <div class="section-title">个人资料</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="客户名称：" prop="customerName">
                <el-select 
                  v-model="form.customerName" 
                  placeholder="请选择" 
                  style="width: 100%" 
                  filterable 
                  clearable
                  @change="handleCustomerChange"
                >
                  <el-option v-for="item in customerOptions" :key="item.value" :label="item.label" :value="item.label" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="行业：" prop="profession">
                <el-select v-model="form.profession" placeholder="请选择" style="width: 100%" clearable>
                  <el-option v-for="item in industryOptions" :key="item.id" :label="item.industryCategoryName" :value="item.industryCategoryName" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="部门：" prop="department">
                <el-tree-select
                  v-model="form.department"
                  :data="deptOptions"
                  :props="{ value: 'label', label: 'label', children: 'children' }"
                  value-key="id"
                  placeholder="请选择"
                  check-strictly
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="业务员：" prop="salesman">
                <el-select v-model="form.salesman" placeholder="请选择" style="width: 100%" clearable>
                  <el-option v-for="item in staffOptions" :key="item.staffId" :label="(item.staffCode ? '(' + item.staffCode + ') ' : '') + item.staffName" :value="item.staffName" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系人：" prop="contactPerson">
                <el-select 
                  v-model="form.contactPerson" 
                  placeholder="请选择" 
                  style="width: 100%" 
                  filterable 
                  clearable 
                  remote 
                  :remote-method="remoteSearchContacts" 
                  :loading="contactSearchLoading" 
                  @focus="onContactFocus" 
                  @change="handleContactChange"
                >
                  <el-option v-for="item in contactOptions" :key="item.id" :label="item.label" :value="item.label" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机：" prop="phone">
                <el-input v-model="form.phone" placeholder="请输入手机" maxlength="11" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="固定电话：" prop="telephone">
                <el-input v-model="form.telephone" placeholder="请输入固定电话" maxlength="20" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="关怀类型：" prop="concernType">
                <el-select v-model="form.concernType" placeholder="请选择" style="width: 100%">
                  <el-option v-for="item in careTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="金额：" prop="amount">
                <el-input-number
                  v-model="form.amount"
                  :precision="2"
                  :step="0.01"
                  :min="0"
                  :controls="false"
                  placeholder="请输入金额"
                  class="amount-input"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="需求时间：" prop="requirementDate">
                <el-date-picker v-model="form.requirementDate" type="datetime" placeholder="请选择" style="width: 100%" value-format="YYYY-MM-DD HH:mm:ss" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="附件：" prop="fileNo">
                <fileUpload v-model="form.fileNo" :limit="5" :fileSize="10" :isShowTip="false" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="dialog-section no-border no-margin">
          <el-form-item label="礼品描述：" prop="giftDesc">
            <el-input v-model="form.giftDesc" type="textarea" :rows="4" placeholder="请输入内容" maxlength="500" show-word-limit />
          </el-form-item>
          <el-form-item label="关怀理由：" prop="concernArgument">
            <el-input v-model="form.concernArgument" type="textarea" :rows="4" placeholder="请输入内容" maxlength="500" show-word-limit />
          </el-form-item>
        </div>
      </el-form>
    </div>
    <template #footer>
      <div class="drawer-footer">
        <el-button type="primary" @click="submitForm">确认</el-button>
        <el-button @click="handleClose">取消</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup name="CustomerCareEdit">
import { ref, reactive, onMounted, getCurrentInstance, toRefs } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { getCare, updateCare } from "@/api/customer/crmCare";
import { listCustomerInfo, getCustomerInfo } from "@/api/customer/customerInfo/";
import { listContact } from "@/api/customer/crmContact";
import { listIndustryCategory } from "@/api/customer/industryCategory";
import { listComStaff } from "@/api/system/comStaff/index";
import { deptTreeSelect } from "@/api/system/user/index";

const proxy = getCurrentInstance().proxy;
const { care_type: careTypeOptions } = toRefs(reactive(proxy.useDict("care_type")));
const router = useRouter();
const route = useRoute();

const visible = ref(false);
const loading = ref(false);
const selectLoading = ref(false);
const contactSearchLoading = ref(false);
const customerOptions = ref([]);
const contactOptions = ref([]);
const industryOptions = ref([]);
const staffOptions = ref([]);
const deptOptions = ref([]);

const form = reactive({
  id: undefined,
  customerId: undefined,
  customerName: '',
  profession: '',
  department: '',
  salesman: '',
  contactPerson: '',
  phone: '',
  telephone: '',
  concernType: '',
  amount: undefined,
  requirementDate: undefined,
  fileNo: '',
  giftDesc: '',
  concernArgument: '',
  auditStatus: 0
});

const rules = reactive({
  customerName: [{ required: true, message: "客户名称不能为空", trigger: "change" }],
  profession: [{ required: true, message: "行业不能为空", trigger: "change" }],
  department: [{ required: true, message: "部门不能为空", trigger: "change" }],
  salesman: [{ required: true, message: "业务员不能为空", trigger: "change" }],
  contactPerson: [{ required: true, message: "联系人不能为空", trigger: "change" }],
  phone: [
    { required: true, message: "手机不能为空", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的11位手机号码", trigger: "blur" }
  ],
  telephone: [
    { required: true, message: "固定电话不能为空", trigger: "blur" },
    { pattern: /^([0-9-]{7,20})$/, message: "请输入正确的固定电话号码", trigger: "blur" }
  ],
  concernType: [{ required: true, message: "关怀类型不能为空", trigger: "change" }],
  amount: [{ required: true, message: "金额不能为空", trigger: "blur" }],
  giftDesc: [
    { required: true, message: "礼品描述不能为空", trigger: "blur" },
    { max: 500, message: "描述不能超过500个字符", trigger: "blur" }
  ],
  concernArgument: [
    { required: true, message: "关怀理由不能为空", trigger: "blur" },
    { max: 500, message: "理由不能超过500个字符", trigger: "blur" }
  ]
});

/** 获取详情 */
function getDetail() {
  const id = route.query.id;
  if (id) {
    loading.value = true;
    getCare(id).then(response => {
      Object.assign(form, response.data);
      // 预填充当前选中的客户和联系人下拉选项，防止回显失败
      customerOptions.value = [{ label: form.customerName, value: form.customerName, id: form.customerId }];
      contactOptions.value = [{ label: form.contactPerson, value: form.contactPerson }];
      loading.value = false;
      // 加载该客户下的其他联系人
      remoteSearchContacts('');
    }).catch(() => {
      loading.value = false;
    });
  }
}

/** 加载客户列表 (500条) */
const remoteLoadCustomers = (query) => {
  selectLoading.value = true;
  listCustomerInfo({ pageNum: 1, pageSize: 500, isHighSeas: 'all' }).then(res => {
    customerOptions.value = (res.rows || []).map(item => ({
      label: item.customerName,
      value: item.customerName,
      id: item.id,
      ...item
    }));
    selectLoading.value = false;
  }).catch(() => {
    selectLoading.value = false;
  });
};

/** 客户选中处理 */
const handleCustomerChange = async (val) => {
  const customer = customerOptions.value.find(item => item.label === val);
  if (customer) {
    form.customerId = customer.id;
    form.contactPerson = '';
    form.phone = '';
    form.telephone = '';
    
    try {
      const res = await getCustomerInfo(customer.id);
      const detail = res.data;
      if (detail) {
        form.profession = detail.industryCategory || '';
        if (detail.customerSalesInfoVo) {
          form.salesman = detail.customerSalesInfoVo.salesPerson || '';
          form.department = detail.customerSalesInfoVo.belongingDepartment || '';
        }
      }
    } catch (error) {}
    remoteSearchContacts('');
  }
};

/** 远程搜索联系人 */
const remoteSearchContacts = (query) => {
  contactSearchLoading.value = true;
  const params = { pageSize: 50 };
  if (form.customerId) params.customerId = form.customerId;
  if (query) params.contactName = query;
  
  listContact(params).then(res => {
    contactOptions.value = (res.rows || []).map(item => ({
      label: item.contactName,
      value: item.contactName,
      id: item.id,
      ...item
    }));
  }).finally(() => {
    contactSearchLoading.value = false;
  });
};

const onContactFocus = () => {
  if (contactOptions.value.length === 0) remoteSearchContacts('');
};

const handleContactChange = (val) => {
  if (!val) {
    form.phone = '';
    form.telephone = '';
    return;
  }
  const contact = contactOptions.value.find(item => item.label === val);
  if (contact) {
    form.phone = contact.phone || '';
    form.telephone = contact.officePhone || '';
  }
};

/** 提交按钮 */
function submitForm() {
  proxy.$refs["careRef"].validate(valid => {
    if (valid) {
      updateCare(form).then(() => {
        proxy.$modal.msgSuccess("修改成功");
        handleClose(true);
      });
    }
  });
}

/** 关闭抽屉 */
function handleClose(refresh = false) {
  visible.value = false;
  router.back();
}

/** 加载基础选项 */
const initBaseOptions = () => {
  listIndustryCategory().then(res => { industryOptions.value = res.data || res.rows || []; });
  listComStaff({ pageSize: 1000 }).then(res => { staffOptions.value = res.rows || res.data || []; });
  deptTreeSelect().then(res => {
    const data = res.data || [];
    deptOptions.value = proxy.handleTree(data, "id");
  });
};

onMounted(() => {
  getDetail();
  initBaseOptions();
  remoteLoadCustomers('');
});
</script>

<style scoped lang="scss">
.drawer-body { padding: 0 30px; }

.dialog-section {
  padding-bottom: 5px; margin-bottom: 5px;
  &.no-border { border-bottom: none; }
  &.no-margin { margin-bottom: 0; padding-bottom: 0; }
  .section-title {
    font-size: 15px; color: #333;
    margin-bottom: 25px; margin-top: 10px;
  }
}

.static-text {
  color: #606266;
  font-size: 14px;
}

:deep(.el-form-item) {
  margin-bottom: 22px;
}

.drawer-footer {
  padding: 15px 25px;
  text-align: right;
  border-top: 1px solid #ebeef5;
}

:deep(.amount-input .el-input__inner) {
  text-align: left !important;
}

/* 强制所有字体不加粗 */
:deep(*) {
  font-weight: 400 !important;
}
.section-title {
  font-weight: 400 !important;
}
</style>
