<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: 215px">
          <el-option label="男" value="1" />
          <el-option label="女" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="医院科室" prop="departmentId">
        <el-select v-model="queryParams.hospitalId" placeholder="请选择医院" clearable @visible-change="getRelList(queryParams.hospitalId,-1)" style="width: 120px;">
          <el-option v-for="(v,i) in hospitalList" :key="i" :label="v.name" :value="v.id" />
        </el-select>
        <el-select v-model="queryParams.departmentId" placeholder="请选择科室" clearable style="width: 120px;">
          <el-option v-for="(v,i) in relList" :key="i" :label="v.name" :value="v.id" />
        </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="status">
        <el-select v-model="queryParams.status" placeholder="请输入状态" clearable size="small" style="width: 215px">
          <el-option label="上架" :value="true" />
          <el-option label="下架" :value="false" />
        </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>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <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="adName">
        <template slot-scope="{row}">
          {{row.sex==1?'男':row.sex==2?'女':'未知'}}
        </template>
      </el-table-column>
      <el-table-column label="年龄" prop="age" align="center" />
      <el-table-column label="手机号" prop="phoneNumber" align="center" />
      <el-table-column label="状态" align="center" prop="enableStatus">
        <template slot-scope="{row}">
          <el-tag type="success" v-if="row.enableStatus==0">启用</el-tag>
          <el-tag type="danger" v-if="row.enableStatus==1">禁用</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" 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=='0'?'禁用':'启用'}}</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">
        <el-form-item label="老师姓名" prop="name">
          <el-input v-model="form.name" maxlength="20" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="形象照片" prop="photographUrl">
          <imageUpload v-model="form.photographUrl" :limit="1" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择" style="width: 100%">
            <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" placeholder="请输入" @blur="getAge(form.idCard)" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="form.age" maxlength="3" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="工作年限" prop="workYears">
          <el-input v-model="form.workYears" maxlength="2" placeholder="请输入" />
        </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="departmentIds">
          <div class="flex mb10" v-for="(item, index) in form.departmentIds" :key="index">
            <el-select v-model="item.hospitalId" placeholder="请选择医院" clearable @change="getRelList(item.hospitalId,index)" style="width: 100%;margin-right:10px;">
              <el-option v-for="(v,i) in hospitalList" :key="i" :label="v.name" :value="v.id" />
            </el-select>
            <el-select v-model="item.departmentId" placeholder="请选择科室" multiple clearable style="width: 100%;margin-right:10px;">
              <el-option v-for="(v,i) in item.relList" :key="i" :label="v.name" :value="v.id" />
            </el-select>
            <el-button type="primary" @click="add">新增</el-button>
            <el-button type="danger" v-if="index>0" @click="del(index)">删除</el-button>
          </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="enableStatus">
          <el-select v-model="form.enableStatus" 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="manageNursingFlag" label-width="150px">
          <el-switch v-model="form.manageNursingFlag" active-value="Y" inactive-value="N"></el-switch>
          <div class="hint">开启后，管理老师在移动端拥有管理护工的权限</div>
        </el-form-item>
      </el-form>
      <div class="demo-drawer__footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { managementTeacherPage, managementTeacherAdd, managementTeacherInfo, managementTeacherEdit, managementTeacherUpdateStatus, managementTeacherDel } from "@/api/teacher.js";
import { hospitalSimpleList, hospitalDepartmentRelList, hospitalDepartmentSimpleList } from '@/api/hospital.js'
import { getToken } from "@/utils/auth";
export default {
  data () {
    return {
      //按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 测试单表表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 创建时间时间范围
      daterangeCreateTime: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "添加广告",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/demo/demo/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        phoneNumber: undefined,
        sex: undefined,
        hospitalId: undefined,
        departmentId: undefined,
      },
      // 表单参数
      form: {
        name: undefined,
        photographUrl: undefined,
        sex: undefined,
        idCard: undefined,
        age: undefined,
        workYears: undefined,
        phoneNumber: undefined,
        sortOrder: undefined,
        enableStatus: '0',
        departmentIds: [{
          hospitalId: undefined,
          relId: undefined,
        }],
        relList: [],
        manageNursingFlag: 'N'
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "请输入老师姓名", trigger: "blur" }
        ],
        photographUrl: [
          { required: true, message: "请上传老师形象照片", trigger: "blur" }
        ],
        sex: [
          { required: true, message: "请选择性别", trigger: "blur" }
        ],
        idCard: [
          { required: true, message: "请输入身份证号", trigger: "blur" }
        ],
        age: [
          { required: true, message: "请输入年龄", trigger: "blur" }
        ],
        workYears: [
          { required: true, message: "请输入工作年限", trigger: "blur" }
        ],
        phoneNumber: [
          { required: true, message: "请输入手机号", trigger: "blur" }
        ],
        sortOrder: [
          { required: true, message: "请输入排序", trigger: "blur" }
        ],
        departmentIds: [
          { required: true, message: "请选择管理科室", trigger: "blur" }
        ],
        enableStatus: [
          { required: true, message: "请选择状态", trigger: "blur" }
        ]
      },
      jumpTypeList: [
        { label: "内部页面", value: 0 },
        { label: "外部链接", value: 1 },
        // { label: "内部资源", value: 2 },
      ],
      resourceModelList: [
        // { label: '无', value: 0 },
        { label: "公告", value: 1 },
        { label: "积分商品", value: 2 },
        { label: "商户", value: 3 },
      ],
      hospitalList: [],
      relList: [],
    };
  },
  created () {
    this.getList();
    this.getHospitalList();
  },
  methods: {
    openSel () {
      if (this.form.resourceModel == 1) {
        this.$refs.SelNotice.open()
      } else if (this.form.resourceModel == 2) {
        this.$refs.SelPointsGoods.open()
      } else if (this.form.resourceModel == 3) {
        this.$refs.SelShop.open()
      }
    },
    add () {
      this.form.departmentIds.push({})
    },
    del (index) {
      this.form.departmentIds.splice(index, 1)
    },
    getHospitalList () {
      hospitalSimpleList().then(response => {
        this.hospitalList = response.data;
      });
    },
    // 获取科室列表
    getRelList (e, index) {
      if (index == -1) {
        this.queryParams.departmentId = undefined;
        if (e) {
          hospitalDepartmentSimpleList({ hospitalId: e }).then(res => {
            this.relList = res.data;
          })
        } else {
          this.relList = []
        }
      } else {
        this.form.departmentIds[index].relId = undefined;
        if (e) {
          hospitalDepartmentRelList({ hospitalId: e, teacherId: this.form.id }).then(res => {
            this.form.departmentIds[index].relList = res.data.filter(v => {
              if (!v.relFlag) {
                return v
              }
            });
            this.$forceUpdate();
          })
        } else {
          this.form.departmentIds[index].relList = []
        }
      }
    },
    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;
    },
    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';
      }
      managementTeacherPage(this.queryParams).then(response => {
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleResourceTip (type) {
      for (let item of this.resourceModelList) {
        if (type == item.value) {
          return item.label || "";
        }
      }
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        name: undefined,
        photographUrl: undefined,
        sex: undefined,
        idCard: undefined,
        age: undefined,
        workYears: undefined,
        phoneNumber: undefined,
        sortOrder: undefined,
        enableStatus: '0',
        departmentIds: [{
          hospitalId: undefined,
          relId: undefined,
        }],
        manageNursingFlag: 'N'
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.daterangeCreateTime = [];
      this.queryParams.hospitalId = undefined;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.adId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "新增";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      managementTeacherInfo(id).then(response => {
        this.loading = false;
        if (response.data.hospitalRelList && response.data.hospitalRelList.length > 0) {
          response.data.departmentIds = response.data.hospitalRelList.map((v, i) => {
            v.hospitalId = v.id,
              v.relList = [],
              v.departmentId = v.departmentList.map(k => {
                return k.id
              })
            return v
          })
        }
        this.form = response.data;
        if (this.form.departmentIds) {
          this.form.departmentIds.map((v, i) => {
            this.getRelList(v.hospitalId, i)
          })
        }
        this.open = true;
        this.title = "修改";
      });
    },
    handleExport () {
      this.download('/info/managementTeacher/export', {
        ...this.queryParams
      }, `管理老师列表_${new Date().getTime()}.xlsx`)
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          for (let item of this.form.departmentIds) {
            if (!item.hospitalId || !item.departmentId || item.departmentId.length <= 0) {
              return this.$modal.msgError("请选择科室");
            }
          }
          let formCopy = JSON.parse(JSON.stringify(this.form));
          let arr = []
          formCopy.departmentIds.map(v => {
            v.departmentId.map(k => {
              arr.push(k)
            })
          });
          formCopy.departmentIds = arr;
          this.buttonLoading = true;
          if (this.form.id != null) {
            managementTeacherEdit(formCopy).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            managementTeacherAdd(formCopy).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除老师姓名为"' + row.name + '"的数据项？').then(() => {
        this.loading = true;
        return managementTeacherDel(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 上下架按钮操作 */
    setStatus (row) {
      let statusText = row.enableStatus == '0' ? '禁用' : '启用';
      this.$modal.confirm('是否确认' + statusText + '老师姓名为"' + row.name + '"的数据项？').then(() => {
        this.loading = true;
        let param = {
          id: row.id,
          enableStatus: row.enableStatus == '0' ? '1' : '0'
        }
        return managementTeacherUpdateStatus(param);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess(statusText + "成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导入按钮操作 */
    handleImport () {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
  }
};
</script>
<style lang="scss">
.el-drawer__body {
  padding: 0 20px !important;
}
</style>
<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);
}
.hint {
  font-size: 12px;
  color: red;
  display: inline-block;
  margin-left: 10px;
}
.mb10 {
  margin-bottom: 10px;
}
</style>
