<template>
  <div>
    <el-dialog
        :title="title"
        :visible.sync="state.isShowDialog"
        :close-on-click-modal="false"
        width="1200px"
    >
      <el-form
          ref="editFormRef"
          :model="form"
          label-width="100px"
          size="mini"
          label-position="top"
          :rules="rules"
          closeable
      >
        <div class="form-group">
          <h3>申请入室平台</h3>
          <el-row :gutter="20" class="form-row-wrap">
            <el-col :span="12">
              <el-form-item label="预约平台" prop="platformName">
                <div class="flex">
                  <el-input
                      disabled
                      placeholder="请输入"
                      class="w100"
                      maxlength="11"
                      v-model="form.platformName"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预约周期" prop="appointDate">
                <div class="flex">
                  <el-date-picker
                      class="mr8"
                      style="width: 80%"
                      @change="calculateMonths"
                      v-model="form.appointDate"
                      type="daterange"
                      range-separator="-"
                      start-placeholder="预约开始时间"
                      end-placeholder="预约结束时间"
                  />
                  <el-input style="width: 20%" disabled v-model.number="form.platformTime" >
                    <template #append>个月</template>
                  </el-input>
                </div>
              </el-form-item>
            </el-col>
            <!-- END -->
          </el-row>
          <h3>预约信息</h3>
          <el-row :gutter="20" class="form-row-wrap">
            <el-col :span="24">
              <el-form-item label="身份" prop="memberType">
                <el-radio-group v-model="form.memberType"
                                style="width: 100%"
                                disabled
                                clearable>
                  <el-radio v-for="item in userTypeList"
                            :key="item.id"
                            :label="item.dictValue">{{ item.dictLabel }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="人员姓名" prop="memberName">
                <div class="flex">
                  <el-select
                      v-model="form.memberName"
                      @change="memberChange"
                      value-key="id"
                      class="w100"
                      placeholder="请选择"
                      filterable
                      clearable
                      disabled
                  >
                    <el-option :label="v.nickName" :value="v" :key="v.id" v-for="v in userList" />
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号" prop="memberPhone">
                <div class="flex">
                  <el-input
                      placeholder="请输入"
                      class="w100"
                      maxlength="11"
                      v-model="form.memberPhone"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="memberSex">
                <div class="flex">
                  <el-radio-group v-model="form.memberSex">
                    <el-radio v-for="item in userSexList"
                              :key="item.dictValue"
                              :label="item.dictValue">{{ item.dictLabel }}</el-radio>
                  </el-radio-group>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工号/学号" prop="memberNo">
                <div class="flex">
                  <el-input
                      placeholder="请输入"
                      class="w100"
                      maxlength="11"
                      v-model="form.memberNo"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.memberType === '30'">
              <el-form-item label="身份证号(仅院外)" prop="memberIden">
                <div class="flex">
                  <el-input
                      placeholder="请输入"
                      class="w100"
                      maxlength="11"
                      v-model="form.memberIden"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="实验起止时间" prop="dateRange">
                <div class="flex">
                  <el-date-picker
                      class="w100 mr8"
                      v-model="form.dateRange"
                      type="daterange"
                      range-separator="-"
                      start-placeholder="实验开始时间"
                      end-placeholder="实验结束时间"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="课题组" prop="applyPg">
                <div class="flex">
                  <el-select v-model="form.applyPg"
                             placeholder="请选择课题组"
                             value-key="id"
                             class="w100">
                    <el-option v-for="item in pjtList"
                               :key="item.id"
                               :label="item.pgName"
                               :value="item"></el-option>
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="科室" prop="deptId">
                <div class="flex">
                  <el-cascader ref="memberDept"
                               :options="deptData"
                               @change="memberDeptChange"
                               :props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'deptName' }"
                               placeholder="请选择科室"
                               clearable
                               class="w100"
                               v-model="form.deptId">
                    <template #default="{ node, data }">
                      <span>{{ data.deptName }}</span>
                      <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                    </template>
                  </el-cascader>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工作单位" prop="workPlace">
                <div class="flex">
                  <el-input
                      placeholder="请输入"
                      class="w100"
                      maxlength="100"
                      v-model="form.workPlace"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.memberType === '20'">
              <el-form-item label="导师姓名" prop="mentorName">
                <div class="flex">
                  <el-select
                      v-model="form.mentorName"
                      @change="mentorChange"
                      value-key="id"
                      class="w100"
                      placeholder="请选择"
                      filterable
                      clearable
                  >
                    <el-option :label="v.nickName" :value="v" :key="v.id" v-for="v in userList" />
                  </el-select>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.memberType === '20'">
              <el-form-item label="导师电话" prop="mentorPhone">
                <div class="flex">
                  <el-input
                      placeholder="请输入"
                      class="w100"
                      maxlength="11"
                      v-model="form.mentorPhone"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.memberType === '20'">
              <el-form-item label="导师科室" prop="mentorDeptId">
                <div class="flex">
                  <el-cascader ref="mentorDept"
                               :options="deptData"
                               @change="mentorDeptChange"
                               :props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'deptName' }"
                               placeholder="请选择科室"
                               clearable
                               class="w100"
                               v-model="form.mentorDeptId">
                    <template #default="{ node, data }">
                      <span>{{ data.deptName }}</span>
                      <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                    </template>
                  </el-cascader>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div>
          <el-checkbox v-model="checked">
            我已完整阅读并同意
            <el-button type="text" @click="openDisclaimerDialog">
              《预约须知》
            </el-button>
            的内容，承诺如实遵守实验室及各平台的各项规章制度，遵守在室的积分管理制度。
          </el-checkbox>
        </div>
        <!-- END -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" size="small">取 消</el-button>
          <el-button type="primary" @click="subAdd" size="small">
            提 交
          </el-button>
        </span>
      </template>
    </el-dialog>
    <disclaimer
        ref="disclaimerRef"
        @agreeDisclaimer="handleAgreeDisclaimer"
    ></disclaimer>
  </div>
</template>

<script lang="ts">
import disclaimer from "./disclaimer.vue";
import { getToken } from "@/utils/auth";
import { getDeptTree, getProjectGroupList, getDictDataByType, getProjectGroupByUser } from "@/api/dict";
import { getUserList } from "@/api/instr";
import { create } from "@/api/platform"
import to from "await-to-js";
import { mapGetters } from "vuex";
export default {
  name: "FrontendWebTest",
  components: {
    disclaimer,
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  data() {
    return {
      title: "遵义医科大学附属医院临床医学公共实验中心-入室申请表",
      type: '',
      form: {
        id: 0,
        memberId: 0,
        memberName: "",
        memberPhone: "",
        memberSex: "",
        memberNo: "",
        memberIden: "",
        startDate: "",
        endDate: "",
        memberType: "",
        deptId: 0,
        deptName: "",
        workPlace: "",
        mentorId: 0,
        mentorName: "",
        mentorPhone: "",
        mentorDeptId: 0,
        mentorDeptName: "",
        platformId: 0,
        platformName: "",
        platformType: "",
        platformTime: 0,
        other: "",
        pgId: 0,
        pgName: "",
        applyPg: {},
        appointDate: [],
        dateRange: [],
        appointStartDate: "",
        appointEndDate: "",
      },
      checked: false,
      state: {
        isShowDialog: false,
        loading: false,
      },
      rules: {
        memberName: [{ required: true, message: "人员姓名不能为空", trigger: "blur" }],
        memberType: [{ required: true, message: "身份不能为空", trigger: "change" }],
        deptId: [{ required: true, message: "不能为空", trigger: "change" }],
        platformName: [{ required: true, message: "预约平台不能为空", trigger: "blur" }],
        appointDate: [{ required: true, message: "预约周期不能为空", trigger: "blur" }],
        memberPhone: [{ required: true, message: "手机号不能为空", trigger: "blur" }],
        memberSex: [{ required: true, message: "性别不能为空", trigger: "change" }],
        memberNo: [{ required: true, message: "工号/学号不能为空", trigger: "blur" }],
        dateRange: [{ required: true, message: "实验起止时间不能为空", trigger: "change" }],
        applyPg: [{ required: true, message: "请选择课题组", trigger: "change" }],
      },
      deptData: [], // 部门树
      userList: [], // 用户列表
      pjtList: [], // 课题组列表
      userTypeList: [], // 成员类型
      userSexList: [], // 性别
    };
  },
  methods: {
    getDicts() {
      Promise.all([
        getDeptTree(),
        getUserList({ noPage: true }),
        getProjectGroupList(),
        getDictDataByType("sys_user_type"),
        getDictDataByType("sys_com_sex"),
      ]).then(([dept, user, pjt, type, sex]) => {
        this.deptData = dept.data || [];
        this.userList = user.data.list || [];
        this.pjtList = pjt.data.list || [];
        this.userTypeList = type.data.values || [];
        this.userSexList = sex.data.values || [];
      });
    },
    async openDialog(type, row) {
      // 校验token
      const token = getToken();
      if (!token) {
        return this.$router.push("/login?redirect=/technical-plat/index");
      }
      this.form = {
        id: 0,
        memberId: 0,
        memberName: "",
        memberPhone: "",
        memberSex: "",
        memberNo: "",
        memberIden: "",
        startDate: "",
        endDate: "",
        memberType: "",
        deptId: 0,
        deptName: "",
        workPlace: "",
        mentorId: 0,
        mentorName: "",
        mentorPhone: "",
        mentorDeptId: 0,
        mentorDeptName: "",
        platformId: 0,
        platformName: "",
        platformType: "",
        platformTime: 0,
        other: "",
        pgId: 0,
        pgName: "",
        applyPg: {},
      }
      this.checked = false
      this.type = type;
      this.getDicts()
      if (type === 'add') {
        this.memberChange(this.userInfo)
        this.form.platformId = row.id
        this.form.platformName = row.platformName
        this.form.platformType = row.platformType
      }
      this.state.isShowDialog = true;
    },
    openDisclaimerDialog() {
      this.$refs.disclaimerRef.openDialog();
    },
    memberDeptChange() {
      const nodes = this.$refs.memberDept.getCheckedNodes();
      this.form.deptName = nodes[0].label;
    },
    mentorDeptChange() {
      const nodes = this.$refs.mentorDept.getCheckedNodes();
      this.form.mentorDeptName = nodes[0].label;
    },
    async memberChange(user) {
      this.form.memberId = user.id || null;
      this.form.memberName = user.nickName || null;
      this.form.memberPhone = user.phone || '';
      this.form.memberSex = user.sex || '';
      this.form.memberNo = user.idCode || '';
      this.form.memberIden = '';
      this.form.deptId = user.deptId || null;
      this.form.deptName = user.deptName || '';
      this.form.memberType = user.userType || '';
      if (this.form.memberId) {
        const [err, res] = await to(getProjectGroupByUser({ id: this.form.memberId }))
        if (err) return
        this.form.pgId = res.data.id || 0
        this.form.pgName = res.data.pgName || 0
        this.form.applyPg = res.data
      }
    },
    mentorChange(user) {
      this.form.mentorId = user.id || null;
      this.form.mentorName = user.nickName || null;
      this.form.mentorPhone = user.phone || '';
      this.form.mentorDeptId = user.deptId || null;
      this.form.mentorDeptName = user.deptName || '';
    },
    // 获取月份数
    calculateMonths() {
      if (this.form.appointDate.length === 2) {
        const startDate = this.form.appointDate[0];
        const endDate = this.form.appointDate[1];
        this.form.platformTime = this.getMonthDifference(startDate, endDate)
      } else {
        this.form.platformTime = 0
      }
    },
    getMonthDifference(startDate, endDate) {
      let months;
      months = (endDate.getFullYear() - startDate.getFullYear()) * 12;
      months -= startDate.getMonth();
      months += endDate.getMonth();
      return months < 0 ? 0 : months+1;
    },
    onCancel() {
      this.$refs.editFormRef.clearValidate();
      this.$refs.editFormRef.resetFields();
      this.state.isShowDialog = false;
    },
    subAdd() {
      this.$refs.editFormRef.validate(async valid => {
        if(valid) {
          if (!this.checked) {
            this.$refs.disclaimerRef.openDialog();
          } else {
            // 提交申请
            if (this.type === 'add') {
              this.form.isTemporary = '20'
              if (this.form.applyPg != null) {
                this.form.pgId = this.form.applyPg.id
                this.form.pgName = this.form.applyPg.pgName
              }
              if(this.form.appointDate.length) {
                this.form.appointStartDate = this.form.appointDate[0]
                this.form.appointEndDate = this.form.appointDate[1]
              }
              if(this.form.dateRange.length) {
                this.form.startDate = this.form.dateRange[0]
                this.form.endDate = this.form.dateRange[1]
              }
              const [err] = await to(create(this.form));
              if(err) {
                this.$message.warning('操作失败')
                return
              }
              this.$message.success("操作成功");
            }
            this.state.isShowDialog = false;
          }
        }
      })
    },
    handleAgreeDisclaimer() {
      this.checked = true
      // this.$message.success("提交成功");
      // this.state.isShowDialog = false;
    },
  },
};
</script>

<style lang="scss" scoped>
:deep(.el-dialog__body) {
  padding-top: 10px;
}
.appoint-section {
  min-height: 450px;
}
.exper-info-list {
  h3 {
    color: #2c405e;
    font-weight: bold;
  }
  .label {
    width: 100px;
  }
}
.step-tit {
  color: #2c405e;
  font-weight: bold;
}
</style>
