<script setup>

// 禁闭管理
import {timeFormat, calculateAge,extractInfoFromID} from "@/utils/util";
import {
  getConfinementList,
  upDateConfinement,
  getConfinementFiles,
  InsertConfinement,
  getPoliceList,
  DelConfinementById,
  getNursingOrgFun
} from "@/api/work/confinement";
import feedback from "@/utils/feedback";
import {BASE_PATH} from "@/api/request";
//禁闭管理表单检索条件
let query = ref({
  current: 1,
  size: 10,
  departBranch:false,
  confinementTime: []
})
//警员检索条件
let PoliceQuery = ref({
  current: 1,
  size: 30
})
//编辑状态码(修改：true,新增：false)
let isEdit = ref(false)

//编辑表单ref
const formRef = ref()
const total = ref(0)
let list = ref([])
//新增编辑表单
const formData = ref({})
//警员数据集合
let users = ref()
//编辑表单校验
const rules = ref({
  name: [
    {
      required: true,
      message: '请输入姓名',
      trigger: ['blur'],
    }
  ],
  idCode: [
    {
      required: true,
      message: '请输入身份证',
      trigger: ['blur'],
    }
  ],
  gender: [
    {
      required: true,
      message: '请输入性别',
      trigger: ['blur'],
    }
  ],
  age: [
    {
      required: true,
      message: '请输入年龄',
      trigger: ['blur'],
    }
  ],
  joinPartyTime: [
    {
      required: true,
      message: '请输入入党（团）时间',
      trigger: ['blur'],
    }
  ],
  joinWorkTime: [
    {
      required: true,
      message: '请输入参加工作时间',
      trigger: ['blur'],
    }
  ],
  joinPoliceTime: [
    {
      required: true,
      message: '请输入参加公安工作时间',
      trigger: ['blur'],
    }
  ],
  education: [
    {
      required: true,
      message: '请输入文化程度',
      trigger: ['blur'],
    }
  ],
  job: [
    {
      required: true,
      message: '请输入职务',
      trigger: ['blur'],
    }
  ],
  orgId: [
    {
      required: true,
      message: '请选择部门',
      trigger: ['blur'],
    }
  ],
  nursingOrgId: [
    {
      required: true,
      message: '请选择看护单位',
      trigger: ['blur'],
    }
  ],
  matter: [
    {
      required: true,
      message: '请选择事由',
      trigger: ['blur'],
    }
  ],
  startTime: [
    {
      required: true,
      message: '请选择开始时间',
      trigger: ['blur'],
    }
  ],
  endTime: [
    {
      required: true,
      message: '请选择开始时间',
      trigger: ['blur'],
    }
  ],
  confinementTime: [
    {
      required: true,
      message: '请选择开始时间',
      trigger: ['blur'],
    }
  ],
  files: [
    {
      required: true,
      message: '请上传相关文件',
      trigger: ['blur'],
    }
  ]
})
//加载状态码
let loading = ref(false)

//新增禁闭弹窗状态码
let editShow = ref(false)
//详情弹窗状态码
let detailShow = ref(false)

let NursingOrgList = ref([])

//数据导出
const handleExport = () => {
  console.log("数据导出")
  window.open(`${BASE_PATH}/confinement/export?` + new URLSearchParams(query.value).toString())
}
/**
 * 新增禁闭弹窗
 * */
const ShowAddForm = () => {
  formData.value = {}
  isEdit.value = false;
  editShow.value = true
}
//查询数据
const getList = async () => {
  loading.value = true
  getConfinementList(query.value).then((res) => {
    list.value = res.records;
    total.value = res.total;
    loading.value = false
  })
}

const getNursingOrgList =async ()=>{
  const res = await getNursingOrgFun()
  NursingOrgList.value = res;
  console.log('NursingOrgList',NursingOrgList.value)
  this.$nextTick()
}

//获取禁闭信息附件
const getConfinementFilesFun = async (id) => {
  const res = await getConfinementFiles(id)
  formData.value.files = res || []
}
/**
 * 获取详情数据
 * */
const handleDetail = (row) => {
  formData.value = row;
  getConfinementFilesFun(row.id)
  let {birthTime, gender, age} = extractInfoFromID(row.idCode)
  formData.value.gender = gender
  formData.value.age = age
  formData.value.birthTime = birthTime
  detailShow.value=true
}
/**
 * 删除数据
 * */
const handleDel = async (row) => {
  const res = await DelConfinementById(row.id);
  getList()
}
/**
 * 编辑
 * */
const handleUpDate = (row) => {
  formData.value = row;
  getConfinementFilesFun(row.id)
  let {birthTime, gender, age} = extractInfoFromID(row.idCode)
  formData.value.gender = gender
  formData.value.age = age
  formData.value.birthTime = birthTime
  isEdit.value = true;
  editShow.value = true;
}
/**
 * 编辑提交事件
 * */
const handleSumbit = async () => {
  await formRef.value.validate();
  //判断是新增还是修改
  if (isEdit.value) {
    const res = await upDateConfinement(formData.value);
  } else {
    const res = await InsertConfinement(formData.value);
  }
  feedback.msgSuccess("操作成功");
  editShow.value = false
  getList()
}
//获取警员信息组
const getPoliceListFun = async (query) => {
  if (query){
    PoliceQuery.value.name = query;
  }

  const res = await getPoliceList(PoliceQuery.value)
  users.value = res.records;
}
//重置查询
const reset = () => {
  query.value = {
    current: 1,
    size: 10
  };
  tableRef.value.clearSort();
  getList();
  // 重置路由
  // router.push("/query");
}

const CopyUserDetail = (row) => {

  let obj = users.value.filter(s => s.id == row);
  if (obj[0]) {
    let rowData = obj[0];
    formData.value.name = rowData.name
    formData.value.idCode = rowData.idCode
    formData.value.job = rowData.job
    formData.value.orgId = rowData.orgId
    formData.value.empNo = rowData.empNo
    let {birthTime, gender, age} = extractInfoFromID(rowData.idCode)
    formData.value.birthTime = birthTime
    formData.value.gender = gender
    formData.value.age = age

  }
}
/**
 * 禁闭时长的计算
 * */
const getConfinementTime = () => {
  if (formData.value.startTime && formData.value.endTime) {
    formData.value.confinementTime = getDaysBetweenDates(formData.value.startTime, formData.value.endTime)
  }
}

/**
 * 计算两个日期获取相隔天数
 * */
function getDaysBetweenDates(date1, date2) {
  var oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数
  var time1 = new Date(date1).getTime(); // 第一个日期的毫秒数
  var time2 = new Date(date2).getTime(); // 第二个日期的毫秒数
  var diffDays = Math.abs((time1 - time2) / oneDay); // 两个日期相差的天数
  return diffDays;
}




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

<template>
  <div class="container">
    <!--查询条件-->
    <header>
      <el-form>

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="姓名">
              <el-input placeholder="请输入姓名"
                        v-model="query.name"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门">
              <depart-tree-select
                  v-model="query.orgId"
                  placeholder="部门"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="禁闭时间">
              <date-time-range-picker-ext
                  v-model="query.confinementTime"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="事由">
              <el-input placeholder="请输入事由"
                        v-model="query.matter"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="flex between mt-20 mb-26">
        <div>
          <el-button type="primary" @click="handleExport"
          >数据导出
          </el-button>
          <el-button type="primary" @click="ShowAddForm"
          >新增禁闭
          </el-button>
        </div>
        <div>
          <el-button type="primary" @click="getList">
            <template #icon
            >
              <icon name="el-icon-Search"
              />
            </template>
            查询
          </el-button
          >
          <el-button @click="reset">重置</el-button>
        </div>
      </div>
    </header>
    <!--表单-->
    <main>
      <div class="table-container" v-loading="loading">

        <el-table
            :data="list"
            ref="tableRef"
        >
          <el-table-column type="selection" width="55"/>
          <el-table-column
              label="姓名"
              prop="name"
              width="80"
          ></el-table-column>
          <el-table-column
              label="警号"
              prop="empNo"
              width="80"
          ></el-table-column>
          <el-table-column
              label="部门"
              width="120"
          >
            <template #default="{row}">
              <div class="flex gap-4">
                                    <span v-if="row.parentDepartShortName"
                                    >{{ row.parentDepartShortName }}/</span
                                    ><span>{{ row.departShortName }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
              label="年龄"
              width="80"
          >
            <template #default="{row}">
              {{ calculateAge(row.birthTime) || '/' }}
            </template>
          </el-table-column>
          <el-table-column label="职务"
                           width="80"
                           prop="job"
          />
          <el-table-column
              label="事由"
              prop="matter"
              show-overflow-tooltip
          />
          <el-table-column label="禁闭时长（天）"
                           width="80"
                           prop="confinementTime"/>
          <el-table-column
              label="开始日期"
              prop="startTime"
          >
            <template #default="{row}">
              {{ timeFormat(row.startTime) }}
            </template>
          </el-table-column>
          <el-table-column
              label="结束日期"
              prop="endTime"
          >
            <template #default="{row}">
              {{ timeFormat(row.endTime) }}
            </template>
          </el-table-column>
          <el-table-column label="看护单位"
          >
            <template #default="{row}">
              <div class="flex gap-4">
                                    <span>{{ row.nursingShortName }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160" fixed="right">
            <template #default="{ row }">
              <div class="flex v-center">
                <el-button
                    type="primary"
                    text
                    @click="handleDetail(row)"
                >详情
                </el-button
                >
                <el-button
                    type="primary"
                    text
                    @click="handleUpDate(row)"
                >
                  编辑
                </el-button>
                <el-button
                    type="danger"
                    text
                    @click="handleDel(row)"
                >
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </main>
    <!--    编辑表单-->
    <el-dialog v-model="editShow" :title="isEdit?'编辑禁闭信息':'新增禁闭信息'" width="900px">
      <el-form label-width="148" :model="formData" ref="formRef" :rules="rules">
        <div style="margin-bottom: 80px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="姓名" prop="name">
                <!--                <el-input v-model="formData.name"></el-input>-->
                <el-select
                    v-model="formData.policeId"
                    filterable
                    remote
                    default-first-option
                    @change="CopyUserDetail"
                    :remote-method="getPoliceListFun"
                >
                  <el-option v-for="(item,key) in users" :key="key"
                             :label="item.name"
                             :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证" prop="idCode">
                <el-input v-model="formData.idCode"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="年龄" prop="age">
                <el-input-number v-model="formData.age"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="formData.gender">
                  <el-radio value="0">女</el-radio>
                  <el-radio value="1">男</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="出生日期" prop="birthTime">
                <el-date-picker
                    v-model="formData.birthTime"
                    type="datetime"
                    placeholder="请选择"
                    value-format="YYYY-MM-DD HH:mm"
                    time-format="HH:mm"
                    style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入党（团）时间" prop="joinPartyTime">
                <el-date-picker
                    v-model="formData.joinPartyTime"
                    type="datetime"
                    placeholder="请选择"
                    value-format="YYYY-MM-DD HH:mm"
                    time-format="HH:mm"
                    style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="参加工作时间" prop="joinWorkTime">
                <el-date-picker
                    v-model="formData.joinWorkTime"
                    type="datetime"
                    placeholder="请选择"
                    value-format="YYYY-MM-DD HH:mm"
                    time-format="HH:mm"
                    style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12" label="参加公安工作时间" prop="joinPoliceTime">
              <el-form-item label="参加公安工作时间" prop="joinPoliceTime">
                <el-date-picker
                    v-model="formData.joinPoliceTime"
                    type="datetime"
                    placeholder="请选择"
                    value-format="YYYY-MM-DD HH:mm"
                    time-format="HH:mm"
                    style="width: 100%"
                />
              </el-form-item>

            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="文化程度" prop="education">
                <el-input v-model="formData.education"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="职务" prop="job">
                <el-input v-model="formData.job"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="部门" prop="orgId">
                <depart-tree-select
                    v-model="formData.orgId"
                    placeholder="部门"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <hr style="color: #abaaaa;opacity: 0.2"/>
          <el-row>
            <el-col :span="12">
              <el-form-item label="看护单位" prop="nursingOrgId">
                <el-select
                    filterable
                    default-first-option
                    v-model ="formData.nursingOrgId">
                  <el-option v-for="(item,key) in NursingOrgList" :key="key"
                             :label="item.shortName"
                             :value="item.id"></el-option>

                </el-select>
<!--                <depart-tree-select-->
<!--                    v-model="formData.nursingOrgId"-->
<!--                    placeholder="看护单位"-->
<!--                />-->
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="查处单位" prop="investigateUnit">
                <el-input v-model="formData.investigateUnit"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="事由" prop="matter">
                <el-input type="textarea" :rows="3" v-model="formData.matter"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="开始日期" prop="startTime">
                <el-date-picker
                    v-model="formData.startTime"
                    type="datetime"
                    placeholder="请选择"
                    value-format="YYYY-MM-DD HH:mm"
                    time-format="HH:mm"
                    style="width: 100%"
                    @change="getConfinementTime"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束日期" prop="endTime">
                <el-date-picker
                    v-model="formData.endTime"
                    type="datetime"
                    placeholder="请选择"
                    value-format="YYYY-MM-DD HH:mm"
                    time-format="HH:mm"
                    style="width: 100%"
                    @change="getConfinementTime"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="禁闭时长" prop="confinementTime">
                <el-input v-model="formData.confinementTime"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否回访" prop="isVisit">
                <el-radio-group v-model="formData.isVisit">
                  <el-radio value="0">是</el-radio>
                  <el-radio value="1">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="附件上传" prop="files">
                <file-upload v-model:files="formData.files"/>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <footer class="flex end">
        <el-button @click="editShow = false" size="large">取消</el-button>
        <el-button type="primary" @click="handleSumbit" size="large"
        >确定
        </el-button
        >
      </footer>
    </el-dialog>
    <!--  详情-->
    <el-dialog v-model="detailShow" title="详情" width="900px">
      <el-form label-width="148">
        <div style="margin-bottom: 80px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="姓名" prop="name">
                {{ formData.name }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证" prop="idCode">
                {{ formData.idCode }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="年龄" prop="age">
                {{ formData.age }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="gender">
                {{ formData.gender == 0 ? '女' : '男' }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="出生日期" prop="birthTime">
                {{ formData.birthTime }}

              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入党（团）时间" prop="joinPartyTime">
               {{formData.joinPartyTime}}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="参加工作时间" prop="joinWorkTime">
                {{formData.joinWorkTime}}
              </el-form-item>
            </el-col>
            <el-col :span="12" label="参加公安工作时间" prop="joinPoliceTime">

              <el-form-item label="参加公安工作时间" prop="joinPoliceTime">
                {{formData.joinPoliceTime}}
              </el-form-item>

            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="文化程度" prop="education">
                {{formData.education}}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="职务" prop="job">
                {{formData.job}}
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="部门" prop="orgId">
                <div class="flex gap-4">
                                    <span v-if="formData.parentDepartShortName"
                                    >{{ formData.parentDepartShortName }}/</span
                                    ><span>{{ formData.departShortName }}</span>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
          <hr style="color: #abaaaa;opacity: 0.2"/>
          <el-row>
            <el-col :span="12">
              <el-form-item label="看护单位" prop="nursingOrgId">
                <div class="flex gap-4">
                                    <span v-if="formData.parentDepartNursingName"
                                    >{{ formData.parentDepartNursingName }}/</span
                                    ><span>{{ formData.nursingShortName }}</span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="查处单位" prop="investigateUnit">
                {{formData.investigateUnit}}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="事由" prop="matter">
                {{formData.matter}}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="开始日期" prop="startTime">
                {{formData.startTime}}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束日期" prop="endTime">
                {{formData.endTime}}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="禁闭时长" prop="confinementTime">
                {{formData.confinementTime}}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否回访" prop="isVisit">
                {{formData.isVisit== 0?'是':'否'}}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="附件" prop="files">
                <file-list
                    :files="formData.files"
                    v-if="formData.files"
                />
                <el-empty v-else description="无附件" style="--el-empty-image-width: 50px" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <footer class="flex end">
        <el-button @click="detailShow=false" size="large">取消</el-button>
        <el-button type="primary" @click="detailShow=false" size="large"
        >确定
        </el-button
        >
      </footer>
    </el-dialog>

  </div>
</template>

<style scoped lang="scss">

</style>
