<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="用户编码" prop="contactNo">
              <el-input v-model="queryParams.contactNo" placeholder="请输入用户编码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="姓名" prop="contactName">
              <el-input v-model="queryParams.contactName" placeholder="请输入姓名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="queryParams.phone" placeholder="请输入联系电话" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="所属客户" prop="customerName">
              <el-input v-model="queryParams.customerName" placeholder="请输入所属客户" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="19">
            <span>员工信息列表</span>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">批量删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain :disabled="single">修改密码</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport">导出数据</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="员工编号" align="center" prop="contactNo" />
        <el-table-column label="姓名" align="center" prop="contactName" />
        <el-table-column label="手机号" align="center" prop="phone" />
        <el-table-column label="采购角色" align="center" prop="roleName" />
        <el-table-column label="职位" align="center" prop="postName" />
        <el-table-column label="所属客户" align="center" prop="customerName" />
        <el-table-column label="注册时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <!-- <dict-tag :options="sys_normal_disable" :value="scope.row.status" /> -->
            {{ scope.row.status === '0' ? '启用' : '停用' }}
          </template>
        </el-table-column>

        <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button link type="primary">查看</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: 'deptId', label: 'deptName', children: 'children' }"
                value-key="deptId"
                placeholder="请选择"
                check-strictly
                :render-after-expand="false"
                @change="handleDeptChange"
                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-select v-model="form.roleId" placeholder="请选择采购角色" clearable filterable style="width: 100%" @change="handleRoleChange">
                <el-option v-for="role in roleOptions" :key="role.roleId" :label="role.roleName" :value="role.roleId" />
              </el-select>
            </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="regionOptions" 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,
  changeIsPrimary,
  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 { listRole } from '@/api/system/role';
import type { RoleVO } from '@/api/system/role/types';
import { regionData } from 'element-china-area-data';

const regionOptions = regionData as any;
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 roleOptions = ref<any>([]);

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' },
      { pattern: /^1[3-9]\d{9}$/ as RegExp, message: '请输入正确的手机号格式', trigger: 'blur' }
    ]
  }
});

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

/** 查询客户联系人信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCustomerContact(queryParams.value);
  customerContactList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 加载角色列表 */
const loadRoleOptions = async () => {
  try {
    // const res: any = await listRole({
    //   pageNum: 1,
    //   pageSize: 9999,
    //   roleName: '',
    //   roleKey: '',
    //   status: ''
    // } as any);
    // roleOptions.value = res?.rows || res?.data?.rows || res?.data || [];
    roleOptions.value = [
      { roleId: 1, roleName: '管理角色' },
      { roleId: 2, roleName: '采购角色' },
      { roleId: 3, roleName: '查询角色' },
      { roleId: 4, roleName: '审核角色' }
    ];
  } catch (error) {
    console.error('加载角色列表失败:', error);
    roleOptions.value = [];
  }
};

const handleDeptChange = (deptId: string | number) => {
  const dept = customerDeptList.value.find((d) => d.deptId === deptId);
  form.value.deptName = dept?.deptName;
};

const handleRoleChange = (roleId: string | number) => {
  const role = roleOptions.value.find((r) => r.roleId === roleId);
  form.value.roleName = role?.roleName;
};

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

/** 状态修改  */
const handlePrimaryChange = async (row: any) => {
  //   const text = row.status === '0' ? '是' : '否';
  try {
    // await proxy?.$modal.confirm('确认要"' + text + '"吗?');
    await changeIsPrimary(row.id, row.isPrimary);
    proxy?.$modal.msgSuccess('操作成功');
    getList();
  } catch (err) {
    row.status = row.status === '0' ? '1' : '0';
  }
};

/** 取消按钮 */
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 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(() => {
  loadRoleOptions();
  getList();
});
</script>
