<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" label-width="100px">
            <el-form-item label="供应商编号" prop="supplierNo">
              <el-input v-model="queryParams.supplierNo" placeholder="请输入供应商编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="供应商名称" prop="supplierName">
              <el-input v-model="queryParams.supplierName" placeholder="请输入供应商名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="联系人" prop="userName">
              <el-input v-model="queryParams.userName" 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>
              <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>
        业务联系人
      </template>

      <el-table v-loading="loading" border :data="contactList" @selection-change="handleSelectionChange">
        <el-table-column label="主键ID" align="center" prop="id" v-if="false" />
        <el-table-column label="供应商编号" align="center" prop="supplierNo" min-width="120" />
        <el-table-column label="所属供应商" align="left" prop="supplierName" min-width="260" />
        <el-table-column label="用户ID" align="center" prop="userNo" min-width="110" />
        <el-table-column label="员工姓名" align="center" prop="userName" min-width="110" />
        <el-table-column label="手机号" align="center" prop="phone" min-width="140" />
        <el-table-column label="角色" align="center" prop="roleNo" min-width="90" />
        <el-table-column label="部门" align="center" prop="departmentNo" min-width="90" />
        <el-table-column label="职位" align="center" prop="position" min-width="90" />
        <el-table-column label="主要联系人" align="center" prop="isPrimaryContact" min-width="120">
          <template #default="scope">
            <span :style="String(scope.row.isPrimaryContact) === '0' ? { color: '#409EFF' } : undefined">
              {{ String(scope.row.isPrimaryContact) === '0' ? '是' : '否' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="允许登录供应商端" align="center" prop="isRegister" min-width="160">
          <template #default="scope">
            <span :style="String(scope.row.isRegister) === '1' ? { color: '#409EFF' } : undefined">
              {{ String(scope.row.isRegister) === '1' ? '是' : '否' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
          <template #default="scope">
            <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['supplier:contact:edit']">编辑</el-button>
            <el-button link type="primary" @click="handleResetPassword(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="contactFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="供应商" prop="supplierId">
              <el-select v-model="form.supplierId" placeholder="请选择供应商" style="width: 100%;" filterable :disabled="!!form.id">
                <el-option
                  v-for="item in supplierList"
                  :key="item.id"
                  :label="item.enterpriseName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="员工姓名" prop="userName">
              <el-input v-model="form.userName" 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="roleNo">
              <el-input v-model="form.roleNo" placeholder="请输入角色" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门" prop="departmentNo">
              <el-input v-model="form.departmentNo" placeholder="请输入部门" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input v-model="form.position" placeholder="请输入职位" />
            </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 label="0">男</el-radio>
                <el-radio label="1">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="主要联系人" prop="isPrimaryContact">
              <el-radio-group v-model="form.isPrimaryContact">
                <el-radio label="0">是</el-radio>
                <el-radio label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="允许登录" prop="isRegister">
              <el-radio-group v-model="form.isRegister">
                <el-radio label="0">否</el-radio>
                <el-radio label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="人员描述" prop="userDescribe">
              <el-input v-model="form.userDescribe" type="textarea" :rows="3" placeholder="请输入人员描述" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="联系地址" prop="connAddr">
              <el-input v-model="form.connAddr" type="textarea" :rows="3" placeholder="请输入联系地址" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog title="重置密码" v-model="resetPasswordDialog.visible" width="500px" append-to-body>
      <el-form ref="resetPasswordFormRef" :model="resetPasswordForm" :rules="resetPasswordRules" label-width="100px">
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="resetPasswordForm.newPassword" type="password" placeholder="请输入新密码" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="resetPasswordForm.confirmPassword" type="password" placeholder="请输入确认密码" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmResetPassword">确 认</el-button>
          <el-button @click="cancelResetPassword">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Contact" lang="ts">
import { listContact, getContact, delContact, addContact, updateContact } from '@/api/supplier/contact';
import { ContactVO, ContactQuery, ContactForm } from '@/api/supplier/contact/types';
import { listInfo } from '@/api/customer/info';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { is_primary_contack, is_register } = toRefs<any>(proxy?.useDict('is_primary_contack', 'is_register'));

const contactList = ref<ContactVO[]>([]);
const supplierList = ref<any[]>([]);
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 contactFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const resetPasswordDialog = reactive({
  visible: false,
  userId: '',
  userName: ''
});

const resetPasswordForm = ref({
  newPassword: '',
  confirmPassword: ''
});

const resetPasswordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请输入确认密码', trigger: 'blur' },
    { 
      validator: (rule: any, value: any, callback: any) => {
        if (value !== resetPasswordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      }, 
      trigger: 'blur' 
    }
  ]
};

const resetPasswordFormRef = ref<ElFormInstance>();

const initFormData: ContactForm = {
  id: undefined,
  supplierId: undefined,
  userName: undefined,
  phone: undefined,
  officePhone: undefined,
  roleNo: undefined,
  departmentNo: undefined,
  position: undefined,
  gender: '0',
  isPrimaryContact: '1',
  isRegister: '1',
  userDescribe: undefined,
  connAddr: undefined,
  status: undefined
}
const data = reactive<PageData<ContactForm, ContactQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    supplierNo: undefined,
    supplierName: undefined,
    userName: undefined,
    phone: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {
    supplierId: [
      { required: true, message: '请选择供应商', trigger: 'change' }
    ],
    userName: [
      { required: true, message: '请输入员工姓名', trigger: 'blur' }
    ],
    phone: [
      { required: true, message: '请输入电话', trigger: 'blur' },
      {
        validator: (rule: any, value: any, callback: any) => {
          const v = String(value || '').trim();
          const mobile = /^1[3-9]\d{9}$/;
          const landline = /^0\d{2,3}-?\d{7,8}(-\d{1,6})?$/;
          if (!v) {
            callback(new Error('请输入电话'));
            return;
          }
          if (!mobile.test(v) && !landline.test(v)) {
            callback(new Error('请输入正确的手机号或座机号'));
            return;
          }
          callback();
        },
        trigger: 'blur'
      }
    ],
    officePhone: [
      {
        validator: (rule: any, value: any, callback: any) => {
          const v = String(value || '').trim();
          const mobile = /^1[3-9]\d{9}$/;
          const landline = /^0\d{2,3}-?\d{7,8}(-\d{1,6})?$/;
          if (!v) {
            callback();
            return;
          }
          if (!mobile.test(v) && !landline.test(v)) {
            callback(new Error('请输入正确的手机号或座机号'));
            return;
          }
          callback();
        },
        trigger: 'blur'
      }
    ],
    isPrimaryContact: [
      { required: true, message: '请选择是否为主要联系人', trigger: 'change' }
    ],
    isRegister: [
      { required: true, message: '请选择是否允许登录', trigger: 'change' }
    ]
  }
});

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

/** 查询联系人列表 */
const getList = async () => {
  loading.value = true;
  const res = await listContact(queryParams.value);
  contactList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 获取供应商列表 */
const getSupplierList = async () => {
  try {
    const res = await listInfo();
    supplierList.value = res.rows || [];
  } catch (e) {
    console.error('获取供应商列表失败:', e);
  }
}

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

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

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加联系人";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: ContactVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getContact(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改联系人";
}

/** 重置密码按钮操作 */
const handleResetPassword = (row: ContactVO) => {
  resetPasswordDialog.userId = String(row.id);
  resetPasswordDialog.userName = row.userName;
  resetPasswordForm.value = {
    newPassword: '',
    confirmPassword: ''
  };
  resetPasswordDialog.visible = true;
}

/** 确认重置密码 */
const confirmResetPassword = () => {
  resetPasswordFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await updateContact({ 
          id: resetPasswordDialog.userId, 
          password: resetPasswordForm.value.newPassword 
        });
        proxy?.$modal.msgSuccess("重置密码成功");
        resetPasswordDialog.visible = false;
        resetPasswordForm.value = {
          newPassword: '',
          confirmPassword: ''
        };
      } catch (e) {
        console.error('重置密码失败:', e);
      }
    }
  });
}

/** 取消重置密码 */
const cancelResetPassword = () => {
  resetPasswordDialog.visible = false;
  resetPasswordForm.value = {
    newPassword: '',
    confirmPassword: ''
  };
}

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

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

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

onMounted(() => {
  getList();
  getSupplierList();
});
</script>

<style scoped>

</style>
