<template>
  <div class="p-2">
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="22">
            <span>联系人信息列表</span>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd">添加联系人</el-button>
          </el-col>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="customerContactList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="用户ID" align="center" prop="customerId" />
        <el-table-column label="A10标识" align="center" />
        <el-table-column label="员工姓名" align="center" prop="contactName" />
        <el-table-column label="性别" align="center" prop="gender">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.gender" />
          </template>
        </el-table-column>
        <el-table-column label="手机号" align="center" prop="phone" />
        <el-table-column label="自定义登录名" align="center" prop="customLoginName" />
        <el-table-column label="部门" align="center" prop="" />
        <el-table-column label="采购角色" align="center" prop="roleName" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="主联系人" align="center" prop="isPrimary">
          <template #default="scope">
            <dict-tag :options="sys_platform_yes_no" :value="scope.row.isPrimary" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改客户联系人信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="900px" append-to-body>
      <el-form ref="customerContactFormRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人姓名" prop="contactName">
              <el-input v-model="form.contactName" placeholder="请输入联系人姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="办公电话" prop="officePhone">
              <el-input v-model="form.officePhone" placeholder="请输入办公电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="自定义登录名" prop="customLoginName">
              <el-input v-model="form.customLoginName" placeholder="请输入自定义登录名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属部门" prop="deptId">
              <el-tree-select
                v-model="form.deptId"
                :data="customerDeptList"
                :props="{ value: 'id', label: 'deptName', children: 'children' }"
                value-key="id"
                placeholder="请选择"
                check-strictly
                :render-after-expand="false"
                filterable
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="采购角色" prop="roleId">
              <el-input v-model="form.roleId" placeholder="请输入采购角色" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生日" prop="birthday">
              <el-date-picker v-model="form.birthday" type="date" placeholder="请选择" class="w-full" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="form.gender">
                <el-radio v-for="dict in sys_user_sex" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用状态" prop="status">
              <el-switch v-model="form.status" active-value="0" inactive-value="1" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="详细地址" prop="codeArr">
              <el-cascader v-model="codeArr" :options="regionData" placeholder="请选择" @change="handleChange" style="width: 100%"></el-cascader>
            </el-form-item>
            <el-form-item prop="addressDetail">
              <el-input v-model="form.addressDetail" type="textarea" :rows="3" placeholder="请输入详细地址" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="buttonLoading" @click="submitForm">确认</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CustomerContact" lang="ts">
import {
  listCustomerContact,
  getCustomerContact,
  delCustomerContact,
  addCustomerContact,
  updateCustomerContact
} from '@/api/customer/customerFile/customerContact';
import { CustomerContactVO, CustomerContactQuery, CustomerContactForm } from '@/api/customer/customerFile/customerContact/types';
import { listCustomerDept, getCustomerDept } from '@/api/customer/customerFile/customerDept';
import { CustomerDeptVO, CustomerDeptQuery } from '@/api/customer/customerFile/customerDept/types';
import { regionData } from 'element-china-area-data';
// 接收父组件传递的props
const props = defineProps<{
  customerId?: string;
  customerNo?: string;
}>();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_platform_yes_no, sys_user_sex, sys_normal_disable } = toRefs<any>(
  proxy?.useDict('sys_platform_yes_no', 'sys_user_sex', 'sys_normal_disable')
);

const customerContactList = ref<CustomerContactVO[]>([]);
const customerDeptList = ref<CustomerDeptVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const customerContactFormRef = ref<ElFormInstance>();
const codeArr = ref([]);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: CustomerContactForm = {
  id: undefined,
  customerId: undefined,
  contactName: undefined,
  phone: undefined,
  customLoginName: undefined,
  officePhone: undefined,
  officePhoneTwo: undefined,
  gender: '2',
  roleId: undefined,
  deptId: undefined,
  email: undefined,
  birthday: undefined,
  isPrimary: undefined,
  addressDetail: undefined,
  addressProvince: undefined,
  addressCity: undefined,
  addressCounty: undefined,
  provincialCityCounty: undefined,
  status: '0',
  remark: undefined
};
const data = reactive<PageData<CustomerContactForm, CustomerContactQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    customerId: undefined,
    contactName: undefined,
    phone: undefined,
    officePhone: undefined,
    officePhoneTwo: undefined,
    gender: undefined,
    roleId: undefined,
    isPrimary: undefined,
    addressDetail: undefined,
    addressProvince: undefined,
    addressCity: undefined,
    addressCounty: undefined,
    provincialCityCounty: undefined,
    status: undefined,
    platformCode: undefined,
    params: {}
  },
  rules: {
    contactName: [{ required: true, message: '联系人姓名不能为空', trigger: 'blur' }],
    phone: [{ required: true, message: '手机号码不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询客户联系人信息列表 */
const getList = async () => {
  loading.value = true;
  // 使用props传递的customerId进行查询
  if (props.customerId) {
    queryParams.value.customerId = props.customerId;
  }
  const res = await listCustomerContact(queryParams.value);
  customerContactList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 加载客户部门列表 */
const loadCustomerDeptList = async () => {
  if (!props.customerId) return;
  try {
    const query: CustomerDeptQuery = {
      customerId: props.customerId
    };
    const res = await listCustomerDept(query);
    // 将数据转换为树形结构
    customerDeptList.value = proxy?.handleTree<CustomerDeptVO>(res.data, 'id', 'parentId') || [];
  } catch (error) {
    console.error('加载部门列表失败:', error);
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  codeArr.value = [];
  customerContactFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 处理区域选择变化 */
const handleChange = (val: string[]) => {
  // 保存编码
  form.value.addressProvince = val[0];
  form.value.addressCity = val[1];
  form.value.addressCounty = val[2];

  // 根据编码获取名称
  const names: string[] = [];
  if (val[0]) {
    const province = regionData.find((item: any) => item.value === val[0]);
    if (province) {
      names.push(province.label);

      if (val[1] && province.children) {
        const city = province.children.find((item: any) => item.value === val[1]);
        if (city) {
          names.push(city.label);

          if (val[2] && city.children) {
            const county = city.children.find((item: any) => item.value === val[2]);
            if (county) {
              names.push(county.label);
            }
          }
        }
      }
    }
  }

  // 将省市区名称用斜杠连接
  form.value.provincialCityCounty = names.join('/');
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: CustomerContactVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  // 加载部门列表
  await loadCustomerDeptList();
  // 设置客户ID
  if (props.customerId) {
    form.value.customerId = props.customerId;
  }
  dialog.visible = true;
  dialog.title = '添加客户联系人信息';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: CustomerContactVO) => {
  reset();
  // 加载部门列表
  await loadCustomerDeptList();
  const _id = row?.id || ids.value[0];
  const res = await getCustomerContact(_id);
  // 如果有省市区编码，回显到级联选择器
  if (res.data.addressProvince && res.data.addressCity && res.data.addressCounty) {
    codeArr.value = [res.data.addressProvince, res.data.addressCity, res.data.addressCounty] as any;
  }
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改客户联系人信息';
};

/** 提交按钮 */
const submitForm = () => {
  customerContactFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateCustomerContact(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addCustomerContact(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: CustomerContactVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除客户联系人信息编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delCustomerContact(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'customer/customerContact/export',
    {
      ...queryParams.value
    },
    `customerContact_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  // 初始化时设置customerId
  if (props.customerId) {
    queryParams.value.customerId = props.customerId;
  }
  getList();
});

// 监听props变化
watch(
  () => props.customerId,
  (newCustomerId) => {
    if (newCustomerId) {
      queryParams.value.customerId = newCustomerId;
      getList();
    }
  }
);
</script>
