<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
        <div class="patient-info" v-loading="isLoading">
          <el-row>
            <el-col :span="24">
              <div class="sf-title">患者信息</div>
            </el-col>
            <el-form ref="formRef" :model="patientForm" :rules="formRules" label-width="100px">
              <el-col :span="12">
                <el-form-item label="姓名：" prop="name">
                  <el-input
                    :disabled="isDetail"
                    v-model.trim="patientForm.name"
                    placeholder="请输入姓名"
                    maxlength="20"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机号：" prop="phoneNumber">
                  <el-input
                    v-model.trim="patientForm.phoneNumber"
                    placeholder="请输入手机号"
                    maxlength="11"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="身份证号：" prop="cardNumber">
                  <el-input
                    :disabled="isDetail"
                    v-model.trim="patientForm.cardNumber"
                    placeholder="请输入身份证号"
                    maxlength="18"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="责任医生：" prop="doctorIds">
                  <el-select
                    multiple
                    :value="patientForm.doctorIds"
                    placeholder="请选择责任医生"
                    v-loading="bindLoading"
                    @change="onChangeDoctor"
                  >
                    <el-option
                      v-for="item in doctorOptions"
                      :key="item.doctorId"
                      :label="item.userInfo && item.userInfo.userName"
                      :value="item.doctorId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别：" prop="sex">
                  <el-radio-group v-model="patientForm.sex" disabled>
                    <el-radio :label="item.value" v-for="item in sexEnum.options" :key="item.value">
                      {{ item.label }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="年龄：" prop="age">
                  <el-input v-model="patientForm.age" disabled placeholder="请输入身份证获取年龄" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item v-if="patientId" label="就诊材料：" prop="materialList">
                  <div class="materials-box">
                    <!-- v-for="picItem in patientForm.materialList"
                      :key="picItem" -->
                    <div
                      class="image-box"
                      v-if="materialUrls && materialUrls.length > 0"
                    >
                      <el-image
                        :src="materialUrls[0]"
                        :preview-src-list="materialUrls"
                      />
                      <el-tooltip placement="right">
                        <div slot="content">
                          <span>点击可查看所有材料</span>
                        </div>
                        <i class="el-icon-question"></i>
                      </el-tooltip>
                    </div>
                    <div v-else>暂无数据</div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="疾病标签：">
                  <div class="disease-container">
                    <el-tag
                      class="disease-item"
                      v-for="item in patientForm.labelList"
                      :key="item.id"
                    >
                      {{ item.labelName }}
                    </el-tag>
                  </div>
                </el-form-item>
              </el-col>
            </el-form>
          </el-row>
        </div>
      </el-col>
      <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
        <el-row>
          <el-col :span="24">
            <div class="sf-title">随访计划</div>
          </el-col>
          <el-col :span="24">
            <vxe-grid ref="xGrid" v-bind="gridConfig" :columns="columns" :proxyConfig="proxyConfig">
              <template #t_operate_default="{ row }">
                <vxe-button type="text" status="primary" @click="onOperation(1, row)">
                  查看
                </vxe-button>
                <vxe-button
                  type="text"
                  :disabled="![0, 1].includes(row.status)"
                  status="danger"
                  @click="onDel(row)"
                >
                  删除
                </vxe-button>
              </template>
              <template #t_period_default="{ row }">
                {{ row.periodNumber }}{{ periodUnitEnum.getLabel(row.periodUnit) }}
              </template>
              <template #t_lagTime_default="{ row }">
                {{ row.lagTime ? parseTime(row.lagTime, "{y}-{m}-{d}") : "" }}
              </template>
              <template #bottom>
                <div>
                  <vxe-button
                    status="primary"
                    icon="vxe-icon--plus"
                    style="width: 100%; max-width: 100%"
                    @click="onAddPlan"
                  >
                    添加随访计划
                  </vxe-button>
                </div>
              </template>
            </vxe-grid>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <div class="footer">
      <el-button style="width: 200px" @click="onCancel">取消</el-button>
      <el-button type="primary" style="width: 200px" @click="onSubmit" v-loading="isSubmitting">
        保存
      </el-button>
    </div>
    <!-- 随访计划——查看 -->
    <el-dialog
      title="随访计划--查看"
      v-if="followTaskDetailVisible"
      :visible.sync="followTaskDetailVisible"
      width="90%"
      @close="(followTaskDetailVisible = false), getFollowList()"
      :close-on-click-modal="false"
    >
      <div style="height: 800px">
        <FollowTaskDetailComp :isAllList="false" :followRow="followRow"></FollowTaskDetailComp>
      </div>
    </el-dialog>
    <CreateFollowPlan
      v-if="createFollowPlanVisible"
      :visible.sync="createFollowPlanVisible"
      @success="initData"
    ></CreateFollowPlan>
    <SubmitDiag
      v-if="submitConfirmVisible"
      :visible.sync="submitConfirmVisible"
      @onOk="onSubmitApi"
    />
  </div>
</template>
<script>
import { patientDetail, getDoctorAllList } from "@/api/hospital";
import { requireReg, phoneReg, idCardReg } from "@/regular/index";
import { commonGridConfig1 } from "@/config/vxeGrid";
import CreateFollowPlan from "./components/CreateFollowPlan";
import { validIdCard } from "@/utils/validate";
import { parseIDCard, calculateAge } from "@/utils/ruoyi";
import {
  addPatient,
  editPatient,
  getFollowupPlanListApi,
  bindDoctorApi,
  unbindDoctorApi,
} from "@/api/hospital/patientManage/followupPatient";
import FollowTaskDetailComp from "./components/DetailDialog";
import {
  deleteFollowDocumentApi,
} from "@/api/hospital/patientManage/followupPatient";
import SubmitDiag from "./components/SubmitDiag";
export default {
  name: "AddPatient2",
  enums: ["sexEnum", "cardTypeEnum", "periodUnitEnum", "followItemStatusEnum"],
  components: {
    CreateFollowPlan,
    FollowTaskDetailComp,
    SubmitDiag,
  },
  computed: {
    isDetail() {
      return !!this.patientId;
    },
    materialUrls() {
      return this.patientForm.materialList ? this.patientForm.materialList.map(item => item.attachment) : []
    }
  },
  data() {
    return {
      patientId: null,
      isLoading: false,
      patientForm: {
        name: undefined,
        phoneNumber: undefined,
        cardType: "SF",
        cardNumber: undefined,
        sex: undefined,
        age: undefined,
        materialList: [],
        doctorIds: [],
        labelList: [],
      },
      formRules: {
        name: [
          requireReg("请输入姓名"),
          { max: 32, message: "长度不能超过32个字符", trigger: "blur" },
        ],
        sex: [{ required: true, message: "输入完整证件号后自动选择", trigger: "change" }],
        age: [{ required: true, message: "输入完整证件号后自动计算", trigger: "change" }],
        phoneNumber: [requireReg("请输入手机号"), phoneReg()],
        cardNumber: [requireReg("请输入身份证号"), idCardReg()],
        doctorIds: [{ required: true, message: "请选择责任医生", trigger: "change" }],
      },
      // 责任医生下拉框数据
      doctorOptions: [],
      // 解绑医生禁用控制
      bindLoading: false,
      gridConfig: {
        ...commonGridConfig1,
        showOverflow: false,
        maxHeight: 600,
      },
      columns: [
        {
          field: "name",
          title: "随访模板名称",
          minWidth: 160,
        },
        {
          field: "labelName",
          title: "应用疾病",
          minWidth: 100,
        },
        {
          field: "deptName",
          title: "应用科室",
          minWidth: 100,
        },
        {
          field: "doctorName",
          title: "责任医生",
          minWidth: 100,
        },
        {
          field: "reportId",
          title: "随访周期",
          minWidth: 100,
          slots: {
            default: "t_period_default",
          },
        },
        {
          field: "lagTime",
          title: "基线时间",
          minWidth: 100,
          slots: {
            default: 't_lagTime_default'
          }
        },
        {
          field: "statusDesc",
          title: "状态",
          minWidth: 100,
        },
        {
          field: "operation",
          title: "操作",
          width: 160,
          fixed: "right",
          slots: {
            default: "t_operate_default",
          },
        },
      ],
      proxyConfig: {
        autoLoad: false,
        response: {
          result: "data.list",
          total: "data.page.total",
        },
        ajax: {
          query: async ({ page, ...args }) => {
            const { currentPage: pageNum, pageSize } = page;
            const queryParams = {
              pageNum,
              pageSize,
              patientId: this.$route.params.id,
            };
            return getFollowupPlanListApi(queryParams);
          },
        },
      },
      // 创建随访计划，弹窗控制
      createFollowPlanVisible: false,
      // 点击保存按钮
      isSubmitting: false,
      // 查看随访计划数据
      followRow: {},
      // 随访计划查看弹窗
      followTaskDetailVisible: false,
      // 提交确认弹窗
      submitConfirmVisible: false,
    };
  },
  watch: {
    "patientForm.cardNumber": "idCardGetInfo",
  },
  methods: {
    // 加载责任医生下拉选项数据
    async loadDoctorOptions() {
      try {
        const { data } = await getDoctorAllList();
        this.doctorOptions = data || [];
      } catch (err) {}
    },
    // 获取患者详情
    async getPatientDetail() {
      this.patientId = this.$route.params.id;
      this.isLoading = true;
      try {
        const { data } = await patientDetail(this.patientId);
        const { id, name, phoneNumber, cardNumber, materialList, doctors, labelList } = data;
        const doctorIds = (doctors || []).map((item) => item.doctorId);
        this.patientForm = {
          id,
          name,
          phoneNumber,
          cardNumber,
          doctorIds,
          materialList: materialList,
          labelList
        };
        this.idCardGetInfo(cardNumber);
        this.getFollowList();
      } catch (err) {
        console.log("err", err);
        this.$message.error("获取患者信息失败");
      } finally {
        this.isLoading = false;
      }
    },
    // 查询随访计划数据
    async getFollowList() {
      await this.$nextTick();
      this.$refs.xGrid.commitProxy("query");
    },
    // 根据身份证号自动计算年龄和性别
    idCardGetInfo(val) {
      if (!validIdCard(val)) {
        this.patientForm.sex = "";
        this.patientForm.age = "";
        return;
      }
      const { birthYear, birthMonth, birthDay, gender } = parseIDCard(val);
      this.patientForm.sex = gender;
      this.patientForm.age = calculateAge(`${birthYear}-${birthMonth}-${birthDay}`);
    },
    // 解绑医生
    async unbindDoctor(val, newVal) {
      this.bindLoading = true;
      try {
        await unbindDoctorApi({
          patientId: this.patientId,
          doctorId: val,
        });
        this.patientForm.doctorIds = newVal;
      } catch (err) {
        console.log("err", err);
        this.$message.error("解绑医生失败");
      } finally {
        this.bindLoading = false;
      }
    },
    // 绑定医生
    async bindDoctor(val, newVal) {
      this.bindLoading = true;
      try {
        await bindDoctorApi({
          patientId: this.patientId,
          doctorId: val,
        });
        this.patientForm.doctorIds = newVal;
      } catch (err) {
        console.log("err");
        this.$message.error("绑定医生失败");
      } finally {
        this.bindLoading = false;
      }
    },
    // 更改选中责任医生：可能是绑定操作，也可能是解绑操作，也可能是新增的不操作
    async onChangeDoctor(val) {
      console.log("changeDoctor=", val);
      // 如果是新增，直接返回
      if (!this.patientId) {
        this.patientForm.doctorIds = val;
        return;
      }
      // 是编辑的话，判断解绑还是绑定
      const beforeLens = this.patientForm.doctorIds?.length || 0;
      const currentLens = val?.length || 0;
      // 删除
      if (beforeLens > currentLens) {
        await this.unbindDoctor(this.patientForm.doctorIds[beforeLens - 1], val);
      } else if (beforeLens < currentLens) {
        await this.bindDoctor(val[currentLens - 1], val);
      }
    },
    // 查看
    onOperation(type, row) {
      if (type === 1) {
        this.followRow = row;
        this.followTaskDetailVisible = true;
      }
    },
    // 新增计划
    onAddPlan() {
      if (!this.patientId) {
        return this.$message.warning("请先保存患者信息再操作！");
      }
      this.createFollowPlanVisible = true;
      console.log("点击了=", this.createFollowPlanVisible);
    },
    // 取消
    onCancel() {
      this.$router.go(-1);
    },
    // 点击提交
    async onSubmitApi() {
      const { id, name, phoneNumber, cardNumber, doctorIds } = this.patientForm;
      if (!this.patientId) {
        try {
          this.isSubmitting = true;
          const {
            data: { id },
          } = await addPatient({
            name,
            phoneNumber,
            cardNumber,
            doctorIds,
          });
          this.$message.success("创建成功");
          this.$router.replace({
            name: "EditPatient",
            params: {
              id,
            },
          });
        } catch (err) {
          console.log(err);
        } finally {
          this.isSubmitting = false;
        }
      } else {
        // 如果是编辑
        try {
            this.isSubmitting = true;
            await editPatient({
              id,
              phoneNumber,
              doctorIds,
            });
            this.submitConfirmVisible = false
            this.$message.success("修改成功");
          } catch (err) {
            console.log("err=", err);
          } finally {
            this.isSubmitting = false;
          }
      }
    },
    // 提交
    onSubmit() {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) {
          return;
        }
        // 如果是新增
          this.submitConfirmVisible = true;
      });
    },
    // 删除
    async onDel(row) {
      this.$modal.confirm("是否确认删除？").then(async () => {
        await deleteFollowDocumentApi({
          followId: row.id,
        });
        this.$message.success("操作成功");
        this.getFollowList();
      });
    },
    initData() {
      if (this.$route.params.id) {
        this.getPatientDetail();
      }
      this.loadDoctorOptions();
    },
  },
  created() {
    this.initData();
  },
};
</script>
<style lang="scss" scoped>
.materials-box {
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  .image-box {
    position: relative;
    width: 100px;
    height: 100px;
    i {
      position: absolute;
      top: 0;
      right: 0;
      transform: translate(100%, -50%);
      font-size: 14px;
      cursor: pointer;
    }
  }
  .el-image {
    width: 100px;
    height: 100px;
  }
}
.disease-container {
    display: flex;
    flex-wrap: wrap;
    .disease-item {
      margin-right: 10px;
      margin-bottom: 10px;
    }
  }
.el-select {
  width: 100%;
}
.doctor-select-container {
  display: flex;
  flex-direction: column;
}
.footer {
  margin-top: 50px;
  text-align: center;
}
</style>
