<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="护工姓名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入护工姓名" maxlength="20" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号" prop="phoneNumber">
        <el-input v-model="queryParams.phoneNumber" placeholder="请输入手机号" maxlength="11" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="queryParams.sex" placeholder="请选择性别" clearable size="small" style="width: 240px">
          <el-option label="男" value="1" />
          <el-option label="女" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="daterangeCreateTime" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="用户状态" prop="enableStatus">
        <el-select v-model="queryParams.enableStatus" placeholder="请选择用户状态" clearable size="small" style="width: 240px">
          <el-option label="启用" value="0" />
          <el-option label="禁用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="接单状态" prop="orderReceivingStatus">
        <el-select v-model="queryParams.orderReceivingStatus" placeholder="请选择接单状态" clearable size="small" style="width: 240px">
          <el-option label="正常" value="0" />
          <el-option label="关闭" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="常驻医院" prop="hospitalId">
        <el-select v-model="queryParams.hospitalId" placeholder="请选择常驻医院" clearable size="small" style="width: 240px">
          <el-option v-for="(v,i) in hospitalList" :key="i" :label="v.name" :value="v.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @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="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="list">
      <el-table-column type="index" width="55" label="序号" align="center">
        <template slot-scope="scope">
          <div>
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="形象照片" align="center" prop="photographUrl">
        <template slot-scope="scope">
          <el-image style="width: 50px; height: 50px" :src="scope.row.photographUrl" :preview-src-list="scope.row.photographUrl ? [scope.row.photographUrl] : []"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" prop="sex" width="80">
        <template slot-scope="{row}">
          {{row.sex==1?'男':row.sex==2?'女':'未知'}}
        </template>
      </el-table-column>
      <el-table-column label="年龄" align="center" prop="age" width="80" />
      <el-table-column label="工作年限" align="center" prop="workYears" width="80" />
      <el-table-column label="手机号" align="center" prop="phoneNumber" />
      <el-table-column label="常驻医院" align="center" prop="hospitalName" />
      <el-table-column label="接单数量" align="center" prop="orderCount" width="80" />
      <el-table-column label="接单状态" align="center" prop="locationCodeText">
        <template slot-scope="{row}">
          <el-tag v-if="row.orderReceivingStatus==0">正常</el-tag>
          <el-tag v-if="row.orderReceivingStatus==1" type="danger">关闭</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="用户状态" align="center" prop="enableStatus">
        <template slot-scope="{row}">
          <el-tag v-if="row.enableStatus==0">启用</el-tag>
          <el-tag v-if="row.enableStatus==1" type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row,'查看')">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row,'修改')">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          <el-button size="mini" type="text" @click="setStatus(scope.row)">{{scope.row.enableStatus=='1'?'启用':'禁用'}}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    <!-- 添加或修改对话框 -->
    <el-drawer :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" :disabled="title=='查看'">
        <el-form-item label="护工姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="形象照片" prop="photographUrl">
          <imageUpload key="photographUrl" :disabled="title=='查看'" v-model="form.photographUrl" :unique="'photograph-' + form.id" :limit="1" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择" clearable size="small">
            <el-option label="男" value="1" />
            <el-option label="女" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="身份证" prop="idCard">
          <el-input v-model="form.idCard" maxlength="18" placeholder="请输入" @blur="getAge(form.idCard)" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="form.age" placeholder="请输入" maxlength="3" oninput="value=value.replace(/[^0-9]/g,'')" />
        </el-form-item>
        <el-form-item label="工作年限" prop="workYears">
          <el-input v-model="form.workYears" placeholder="请输入" maxlength="2" oninput="value=value.replace(/[^0-9]/g,'')" />
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" maxlength="11" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="从业证书" prop="nursingCertificateList">
          <div class="box" v-for="(item, index) in form.nursingCertificateList" :key="index">
            <div class="box_t" v-if="title!='查看'">
              <el-input v-model="item.certificateName" maxlength="11" style="margin-right:10px" placeholder="请输入" />
              <el-button type="primary" @click="add">新增</el-button>
              <el-button type="danger" v-if="index>0" @click="del(index)">删除</el-button>
            </div>
            <imageUpload :key="'certificate-' + index" :disabled="title=='查看'" v-model="item.pictureUrl" :unique="'certificate-' + index" :limit="1" />
          </div>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="1" label="排序" :precision="0"></el-input-number>
        </el-form-item>
        <el-form-item label="接单状态" prop="orderReceivingStatus">
          <el-select v-model="form.orderReceivingStatus" placeholder="请选择" clearable style="width: 100%">
            <el-option label="正常" value="0" />
            <el-option label="关闭" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="常驻医院" prop="hospitalId">
          <el-select v-model="form.hospitalId" placeholder="请选择" clearable style="width: 100%">
            <el-option v-for="(v,i) in hospitalList" :key="i" :label="v.name" :value="v.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div class="demo-drawer__footer">
        <el-button v-if="title!='查看'" :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { nursingWorkerPage, nursingWorkerAdd, nursingWorkerInfo, nursingWorkerEdit, nursingWorkerDel, nursingWorkerUpdateStatus } from '@/api/caregiver.js'
import { hospitalSimpleList } from '@/api/hospital.js'
export default {
  data () {
    return {
      //按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 测试单表表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 创建时间时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        phoneNumber: undefined,
        sex: undefined,
        enableStatus: undefined,
        orderReceivingStatus: undefined,
        hospitalId: undefined,
      },
      form: {
        name: undefined,
        age: undefined,
        workYears: undefined,
        photographUrl: undefined,
        sex: undefined,
        idCard: undefined,
        phoneNumber: undefined,
        nursingCertificateList: [
          {
            id: undefined,
            pictureUrl: undefined,
            certificateName: undefined
          }
        ],
        sortOrder: 1,
        orderReceivingStatus: "0",
        enableStatus: "0",
        hospitalId: undefined
      },
      rules: {
        name: [
          { required: true, message: "请输入年龄护工姓名", trigger: "blur" }
        ],
        photographUrl: [
          { required: true, message: "请上传图片", trigger: "change" }
        ],
        sex: [
          { required: true, message: "请选择性别", trigger: "change" }
        ],
        idCard: [
          { required: true, message: "请输入身份证号码", trigger: "blur" }
        ],
        age: [
          { required: true, message: "请输入年龄", trigger: "blur" }
        ],
        workYears: [
          { required: true, message: "请输入工作年限", trigger: "blur" }
        ],
        phoneNumber: [
          { required: true, message: "请输入手机号", trigger: "blur" }
        ],
        orderReceivingStatus: [
          { required: true, message: "请选择接单状态", trigger: "change" }
        ],
        hospitalId: [
          { required: true, message: "请选择常驻医院", trigger: "change" }
        ]
      },
      hospitalList: []
    }
  },
  created () {
    this.getList();
    this.getHospitalList();
  },
  methods: {
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    getHospitalList () {
      hospitalSimpleList().then(response => {
        this.hospitalList = response.data;
      });
    },
    /** 查看/修改按钮操作 */
    handleUpdate (row, title) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      nursingWorkerInfo(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = title;
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除护工姓名为"' + row.name + '"的数据项？').then(() => {
        this.loading = true;
        return nursingWorkerDel(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 用户状态操作 */
    setStatus (row) {
      let statusText = row.enableStatus == '1' ? '启用' : '禁用';
      this.$modal.confirm('是否确认' + statusText + '护工名字为"' + row.name + '"的数据项？').then(() => {
        this.loading = true;
        let param = { id: row.id, enableStatus: row.enableStatus == '1' ? '0' : '1' };
        return nursingWorkerUpdateStatus(param);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess(statusText + "成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    getAge (idCard) {
      if (!/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/.test(idCard)) {
        throw new Error("身份证号码格式不正确");
      }

      // 提取出生年月日：第7到14位是 YYYYMMDD
      const year = parseInt(idCard.substring(6, 10), 10);
      const month = parseInt(idCard.substring(10, 12), 10);
      const day = parseInt(idCard.substring(12, 14), 10);

      // 获取当前日期
      const today = new Date();
      const currentYear = today.getFullYear();
      const currentMonth = today.getMonth() + 1; // 月份从0开始
      const currentDay = today.getDate();

      // 计算年龄
      let age = currentYear - year;

      // 检查是否还没过生日
      if (currentMonth < month || (currentMonth === month && currentDay < day)) {
        age--;
      }
      this.form.age = age;
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加护工";
    },
    // 表单重置
    reset () {
      this.form = {
        id: undefined,
        name: undefined,
        age: undefined,
        workYears: undefined,
        photographUrl: undefined,
        sex: undefined,
        idCard: undefined,
        phoneNumber: undefined,
        nursingCertificateList: [
          {
            pictureUrl: undefined,
            certificateName: undefined
          }
        ],
        sortOrder: 1,
        orderReceivingStatus: "0",
        enableStatus: "0",
        hospitalId: undefined
      };
      this.resetForm("form");
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            nursingWorkerEdit(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            nursingWorkerAdd(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    getList () {
      this.loading = true;
      this.queryParams["createTimeStart"] = undefined;
      this.queryParams["createTimeEnd"] = undefined;
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams["createTimeStart"] = this.daterangeCreateTime[0] + ' 00:00:00';
        this.queryParams["createTimeEnd"] = this.daterangeCreateTime[1] + ' 23:59:59';
      }
      nursingWorkerPage(this.queryParams).then(response => {
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    add () {
      this.form.nursingCertificateList.push({
        id: this.generateId(),
        certificateName: '',
        pictureUrl: ''
      })
    },
    del (index) {
      this.form.nursingCertificateList.splice(index, 1)
    },
  },
}
</script>

<style lang='scss' scoped>
.flex {
  display: flex;
}
.demo-drawer__footer {
  margin-left: 120px;
}
::v-deep .el-input.is-disabled .el-input__inner {
  background-color: #fff;
  color: rgb(96, 98, 102);
}
.box {
  .box_t {
    display: flex;
    margin-bottom: 10px;
  }
}
</style>