<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable>
          <el-option
            v-for="dict in sys_user_sex"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="住址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入住址"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="紧急联系人" prop="emergencyContact">
        <el-input
          v-model="queryParams.emergencyContact"
          placeholder="请输入紧急联系人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="紧急联系人电话" prop="emergencyPhone">
        <el-input
          v-model="queryParams.emergencyPhone"
          placeholder="请输入紧急联系人电话"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否残疾" prop="disability">
        <el-select v-model="queryParams.disability" placeholder="请选择是否残疾" clearable>
          <el-option
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="登记日期" prop="registeredDate">
        <el-input
          v-model="queryParams.registeredDate"
          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-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['care:persons:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['care:persons:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['care:persons:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['care:persons:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="personsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="出生日期" align="center" prop="dateOfBirth" />
      <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="phoneNumber" />
      <el-table-column label="住址" align="center" prop="address" />
      <el-table-column label="是否残疾" align="center" prop="disability" >
        <template #default="scope">
          <dict-tag :options="sys_yes_no" :value="scope.row.disability"/>
        </template>
      </el-table-column>
      <el-table-column label="登记日期" align="center" prop="registeredDate">
        <template #default="scope">
          <span>{{ parseTime(scope.row.registeredDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <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)" v-hasPermi="['care:persons:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['care:persons:remove']">删除</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-dialog :title="title" v-model="open" width="900px" append-to-body>
      <el-form ref="personsRef" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="身份证号码" prop="idNumber"  @input="getIdCardInfo">
              <el-input v-model="form.idNumber" placeholder="请输入身份证号码" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="phoneNumber">
              <el-input v-model="form.phoneNumber" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="年龄" prop="age">
              <el-input v-model="form.age" placeholder="年龄" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出生日期" prop="dateOfBirth">
              <el-input v-model="form.dateOfBirth" placeholder="出生日期" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="form.gender" placeholder="性别" disabled>
                <el-option
                    v-for="dict in sys_user_sex"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="住址" prop="address">
              <el-input v-model="form.address" placeholder="请输入住址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="紧急联系人" prop="emergencyContact">
              <el-input v-model="form.emergencyContact" placeholder="请输入紧急联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="紧急联系人电话" prop="emergencyPhone">
              <el-input v-model="form.emergencyPhone" placeholder="请输入紧急联系人电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="疾病史" prop="medicalConditions">
              <el-input v-model="form.medicalConditions" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否残疾" prop="disability">
              <el-select v-model="form.disability" placeholder="是否残疾">
                <el-option
                    v-for="dict in sys_yes_no"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登记日期" prop="registeredDate">
              <el-date-picker clearable
                              v-model="form.registeredDate"
                              type="date"
                              value-format="YYYY-MM-DD"
                              placeholder="请选择登记日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Persons">
import { listPersons, getPersons, delPersons, addPersons, updatePersons } from "@/api/care/persons";

const { proxy } = getCurrentInstance();
const { sys_user_sex,sys_yes_no } = proxy.useDict('sys_user_sex','sys_yes_no');

const personsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    dateOfBirth: null,
    gender: null,
    idNumber: null,
    address: null,
    phoneNumber: null,
    emergencyContact: null,
    emergencyPhone: null,
    healthStatus: null,
    medicalConditions: null,
    disability: null,
    registeredDate: null,
    userId: null,
  },
  rules: {
    name: [
      { required: true, message: "姓名不能为空", trigger: "blur" }
    ],
    idNumber: [
      { required: true, pattern: /^(^\d{15}$|^\d{18}$|^\d{17}(\d|x|X)$)/, message: '无效的身份证格式', trigger: 'blur' }
    ],
    disability: [
      { required: true, message: "是否残疾不能为空", trigger: "blur" }
    ],
    registeredDate: [
      { required: true, message: "登记日期不能为空", trigger: "blur" }
    ],
    phoneNumber: [
      { required: true,pattern: /^1[3-9]\d{9}$/, message: '无效的手机号格式', trigger: 'blur' }
    ]
  }
});

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

/** 查询特困人员列表 */
function getList() {
  loading.value = true;
  listPersons(queryParams.value).then(response => {
    personsList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    personId: null,
    name: null,
    dateOfBirth: null,
    gender: null,
    idNumber: null,
    address: null,
    phoneNumber: null,
    emergencyContact: null,
    emergencyPhone: null,
    healthStatus: null,
    medicalConditions: null,
    disability: null,
    registeredDate: null,
    userId: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("personsRef");
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.personId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加特困人员";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _personId = row.personId || ids.value
  getPersons(_personId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改特困人员";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["personsRef"].validate(valid => {
    if (valid) {
      if (form.value.personId != null) {
        updatePersons(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPersons(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _personIds = row.personId || ids.value;
  proxy.$modal.confirm('是否确认删除特困人员编号为"' + _personIds + '"的数据项？').then(function() {
    return delPersons(_personIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('care/persons/export', {
    ...queryParams.value
  }, `persons_${new Date().getTime()}.xlsx`)
}
function getIdCardInfo () {
  const idCardValue = form.value.idNumber.trim();
  const parsedInfo = parseIdCard(idCardValue);
  console.info(parsedInfo)
  if (parsedInfo) {
    form.value.dateOfBirth = parsedInfo.birthDate;
    form.value.age = parsedInfo.age;
    form.value.gender = parsedInfo.gender;
  } else {
    form.value.dateOfBirth = '';
    form.value.age = '';
    form.value.gender = '';
  }
};

//通过身份证号获取出生年月、性别、年龄
function parseIdCard (idCard){
  if (idCard.length !== 18) {
    return null;
  }

  const year = idCard.substring(6, 10);
  const month = idCard.substring(10, 12);
  const day = idCard.substring(12, 14);
  const genderCode = parseInt(idCard.charAt(16), 10);

  const parsedBirthDate = `${year}-${month}-${day}`;
  const parsedAge = calculateAge(parsedBirthDate);
  const parsedGender = genderCode % 2 === 0 ? '1' : '0';

  return { birthDate: parsedBirthDate, age: parsedAge, gender: parsedGender };
};
//计算年龄
function calculateAge (birthDate) {
  const today = new Date();
  const birthDateObj = new Date(birthDate);
  let age = today.getFullYear() - birthDateObj.getFullYear();
  const m = today.getMonth() - birthDateObj.getMonth();
  if (m < 0 || (m === 0 && today.getDate() < birthDateObj.getDate())) {
    age--;
  }
  return age;
};
getList();
</script>
