<template>
  <div class="app-container">
    <vxe-grid
      class="grid"
      ref="xGrid"
      v-bind="gridConfig"
      :formConfig="formConfig"
      :columns="columns"
      :span-method="spanMethod"
      :proxyConfig="proxyConfig"
      :toolbarConfig="toolbarConfig"
      @toolbar-button-click="toolbarBtnClick"
    >
      <template #patient_num>
        <div class="mb10" style="margin-left: 10px; font-size: 16px; font-weight: 500">
          总计患者
          <span style="color: #409eff; font-weight: bold">{{ total }}</span>
          人
        </div>
      </template>
      <template #date_item="{ data }">
        <el-date-picker
          style="width: 300px"
          v-model="data.dateRange"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          @change="(val) => onDateChange(val, data)"
        ></el-date-picker>
      </template>
      <template #dept_item="{ data }">
        <TreeDept
          v-model="data.deptId"
          clearable
          style="width: 300px"
          :options="deptList"
          :autoFetch="false"
          :props="{ emitPath: false }"
          @change="(value, deptItem) => onChangeDept(value, deptItem, data)"
        />
      </template>
      <template #btn_items>
        <vxe-button type="submit" status="primary" content="查询"></vxe-button>
        <vxe-button type="reset" content="重置"></vxe-button>
      </template>
      <template #table_cardType="{ row }">
        <span>{{ cardTypeEnum.getLabel(row.cardType) }}</span>
      </template>
      <template #createTime_t_d="{ row }">
        {{ row.doctor && row.doctor.reportStatus === 1 ? row.doctor.updateTime : '--' }}
      </template>
      <template #reportStatus_t_d="{ row }">
        <span :style="{color: reportStatusEnum.enum[row.doctor.reportStatus].color}">
          {{ reportStatusEnum.getLabel(row.doctor.reportStatus) }}
        </span>
      </template>
      <template #isFollowed_t_d="{row}">
        {{ row.doctor.isFollowed == 0 ? '否' :  row.doctor.isFollowed == 1 ? '是' : '--' }}
      </template>
      <template #operation="{ row }">
        <vxe-button type="text" status="primary" @click="onEdit(row)">编辑</vxe-button>
        <vxe-button type="text" status="danger" @click="onDel(row)">删除</vxe-button>
      </template>
    </vxe-grid>
  </div>
</template>
<script>
import { commonGridConfig1 } from "@/config/vxeGrid";
import { getTreeHospDeptByPatient } from "@/api/admin";
import { getDoctorAllList, getMedicalLabel, patientPageList, delPatient } from "@/api/hospital";
import { getReportStatusApi } from "@/api/hospital/patientManage/followupPatient";
import TreeDept from "@/components/TreeDept";
export default {
  name: "PatientList2",
  components: {
    TreeDept,
  },
  enums: ["reportStatusEnum", "cardTypeEnum"],
  data() {
    return {
      gridConfig: {
        ...commonGridConfig1,
      },
      formConfig: {
        titleWidth: 140,
        titleAlign: "right",
        titleColon: true,
        items: [
          {
            field: "dateRange",
            title: "报到时间",
            itemRender: {},
            slots: {
              default: "date_item",
            },
          },
          {
            field: "deptId",
            title: "科室",
            itemRender: {},
            slots: {
              default: "dept_item",
            },
          },
          {
            field: 'name',
            title: '患者姓名',
            itemRender: {
              name: "VxeInput",
              props: {
                placeholder: "请输入患者姓名"
              }
            }
          },
          {
            field: "doctorId",
            title: "责任医生",
            itemRender: {
              name: "VxeSelect",
              options: [],
              props: {
                clearable: true,
                placeholder: "请选择责任医生",
              },
              optionProps: {
                value: "doctorId",
                label: "userName",
              },
            },
          },
          {
            field: "labelId",
            title: "诊断疾病",
            itemRender: {
              name: "VxeSelect",
              options: [],
              props: {
                clearable: true,
                placeholder: "请选择诊断疾病",
              },
              optionProps: {
                value: "id",
                label: "name",
              },
            },
          },
          {
            field: "reportStatus",
            title: "报到状态",
            itemRender: {
              name: "VxeSelect",
              options: [],
              props: {
                clearable: true,
                placeholder: "请选择报到状态",
              },
              optionProps: {
                value: "value",
                label: "label",
              },
            },
          },
          {
            field: "isFollowed",
            title: "是否配置随访计划",
            itemRender: {
              name: "VxeSelect",
              options: [
                {
                  value: 0,
                  label: '否'
                },
                {
                  value: 1,
                  label: '是'
                }
              ],
              props: {
                clearable: true,
                placeholder: "请选择",
              },
              optionProps: {
              },
            },
          },
          { itemRender: {}, slots: { default: "btn_items" } },
          {
            span: 24,
            itemRender: {},
            slots: {
              default: "patient_num",
            },
          },
        ],
      },
      columns: [
        {
          field: "id",
          title: "患者ID",
          minWidth: 100,
        },
        {
          field: "name",
          title: "患者名称",
          minWidth: 200,
        },
        {
          field: "sex",
          title: "患者性别",
          minWidth: 200,
        },
        {
          field: "cardType",
          title: "证件类型",
          minWidth: 200,
          slots: {
            default: "table_cardType",
          },
        },
        {
          field: "cardNumber",
          title: "证件号",
          minWidth: 200,
        },
        {
          field: "phoneNumber",
          title: "联系电话",
          minWidth: 150,
        },
        {
          field: 'doctor.deptName',
          title: '科室名称',
          minWidth: 150
        },
        {
          field: "createTime",
          title: "报到时间",
          minWidth: 200,
          slots: {
            default: 'createTime_t_d'
          }
        },
        {
          field: 'doctor.userInfo.userName',
          title: '医生姓名',
          minWidth: 150
        },
        {
          field: "status",
          title: "报到状态",
          minWidth: 160,
          slots: {
            default: "reportStatus_t_d",
          },
        },
        {
          field: 'isFollowed',
          title: '是否配置随访计划',
          minWidth: 160,
          slots: {
            default: 'isFollowed_t_d'
          }
        },
        {
          field: "operation",
          title: "操作",
          width: 200,
          fixed: "right",
          slots: {
            default: "operation",
          },
        },
      ],
      proxyConfig: {
        form: true,
        response: {
          result: "list",
          total: "page.total",
        },
        ajax: {
          query: async ({ form, page, ...args }) => {
            const { dateRange, deptId, doctorId, labelId, name, reportStatus, isFollowed } = form;
            const { currentPage: pageNum, pageSize } = page;
            const queryParams = {
              beginTime: dateRange?.[0] ? dateRange?.[0] + " 00:00:00" : undefined,
              endTime: dateRange?.[1] ? dateRange?.[1] + " 23:59:59" : undefined,
              deptId,
              doctorId,
              labelId,
              name,
              reportStatus,
              isFollowed,
              pageNum,
              pageSize,
            };
            const { data: { list, page:page2} } = await patientPageList(queryParams);
            const params = {
              list: [],
              page: page2
            }
            list.forEach(item => {
              const { doctors, ...otherInfo } = item;
              const lens = doctors?.length
              if (doctors?.length > 0) {
                doctors.forEach((item2, index) => {
                  if (index === 0) {
                    params.list.push({
                      ...otherInfo,
                      doctor: item2,
                      rowspan: lens
                    });
                  } else {
                    params.list.push({
                      ...otherInfo,
                      doctor: item2,
                      rowspan: 0
                    });
                  }
                })
              } else {
                params.list.push({
                  ...otherInfo,
                  doctor: {
                    userInfo: {}
                  },
                  rowspan: 1
                });
              }
            })
            this.total = page2.total || 0;
            console.log('params=', params, page)
            return params;
          },
        },
      },
      toolbarConfig: {
        buttons: [
          {
            code: "add",
            name: "新增患者",
            status: "success",
            icon: "vxe-icon--plus",
          },
          {
            code: "download",
            name: "下载数据模板",
            status: "danger",
            icon: "vxe-icon--download",
          },
        ],
      },
      deptList: [],
      diseaseList: [],
      total: 0,
      // 患者状态查看按钮点击查看报道详情
      reportInfo: [],
      reportLoading: false,
    };
  },
  methods: {
    /*获取科室数据*/
    async getDeptList() {
      const res = await getTreeHospDeptByPatient();
      this.deptList = res.data || [];
    },
    // 获取医生下拉框数据
    async findDoctorList() {
      const { data } = await getDoctorAllList();
      await this.$nextTick();
      const $grid = this.$refs.xGrid;
      if ($grid) {
        const doctorItem = $grid.getFormItems(3);
        doctorItem.itemRender.options =
          data.map((item) => {
            const { userInfo, ...params } = item;
            return {
              ...params,
              ...userInfo,
            };
          }) || [];
      }
      console.log("res=", data);
    },
    // 获取疾病下拉框数据
    async findDiseaseList(deptId) {
      const { data } = await getMedicalLabel({
        deptId,
      });
      await this.$nextTick();
      const $grid = this.$refs.xGrid;
      if ($grid) {
        const diseaseItem = $grid.getFormItems(4);
        diseaseItem.itemRender.options = data;
      }
    },
    async onDateChange(val, data) {
      if (val && val.length > 0) {
        data.reportStatus = 1
        await this.$nextTick();
        const $grid = this.$refs.xGrid;
        if ($grid) {
          const reportItem = $grid.getFormItems(5)
          reportItem.itemRender.props = {
            ...reportItem.itemRender.props,
            disabled: true
          }
        }
      } else {
        data.reportStatus = null
        await this.$nextTick();
        const $grid = this.$refs.xGrid;
        if ($grid) {
          const reportItem = $grid.getFormItems(5)
          reportItem.itemRender.props = {
            ...reportItem.itemRender.props,
            disabled: false
          }
        }
      }
      console.log('val=', val)
      console.log('data=', data)
     },
    // 获取报到状态
    async findReportStatusOptions() {
      await this.$nextTick();
      const $grid = this.$refs.xGrid
      if ($grid) {
        const reportItem = $grid.getFormItems(5)
        reportItem.itemRender.options = this.reportStatusEnum.options
      }
    },
    // 加载下拉框数据
    loadOptions() {
      this.getDeptList();
      this.findDoctorList();
      this.findDiseaseList();
      this.findReportStatusOptions();
    },
    // 选择科室
    onChangeDept(value, deptItem, formData) {
      console.log("value=", value, deptItem, formData);
      formData.labelId = null;
      this.findDiseaseList(value);
    },
    toolbarBtnClick({ code, button, $event }) {
      console.log("code=", code);
      console.log("button=", button);
      console.log("$event=", $event);
      if (code === "download") {
        window.open(process.env.VUE_APP_BASE_PATH + "template/patientTemplate.xlsx");
      } else if (code === "add") {
        this.$router.push({
          path: "/patientManage/followupPatient/add",
        });
      }
    },
    async onReportStatusDetail(row) {
      console.log("查看患者详情=", row);
      this.reportInfo = [];
      try {
        this.reportLoading = true;
        const { data } = await getReportStatusApi(row.id);
        this.reportInfo = data || [];
      } catch (err) {
        console.log(err);
      } finally {
        this.reportLoading = false;
      }
    },
    // 编辑
    onEdit(row) {
      if (!row.id) {
        return this.$message.warning('缺失患者id')
      }
      this.$router.push({
        name: 'EditPatient',
        params: {
          id: row.id
        }
      })
    },
    // 删除
    async onDel(row) {
      this.$modal.confirm("是否确认删除？").then(async () => {
        await delPatient(row.id);
        this.$message.success("操作成功");
        await this.$nextTick();
        const $grid = this.$refs.xGrid;
        $grid.commitProxy("query");
      });
    },
    spanMethod({ row, rowIndex, columnIndex }) {
      if ([7, 8, 9, 10].includes(columnIndex)) {
        return {
          rowspan: 1,
          colspan: 1
        }
      }
      return {
        rowspan: row.rowspan,
        colspan: 1
      }
    }
  },
  created() {
    this.loadOptions();
  },
};
</script>
<style lang="scss" scoped>
::v-deep .vxe-grid--form-wrapper {
  .vxe-select {
    width: 300px;
  }
  .vxe-input {
  width: 300px
  }
}
</style>
