<template>
  <div>
    <el-dialog
      title="随访计划--添加"
      :visible="showModal"
      :before-close="onBeforeClose"
      width="90%"
      append-to-body
    >
      <div class="step1" v-show="currentStep === 1" key="1">
        <el-row>
          <el-col :span="24">
            <div class="sf-title">报到</div>
          </el-col>
          <el-col :span="24">
            <vxe-grid
              ref="xGrid1"
              v-bind="gridConfig1"
              :columns="columns1"
              :proxyConfig="proxyConfig1"
              @radio-change="onChangeDoctor"
            >
              <template #table_create_time="{ row }">
                {{ row.createTime ? parseTime(row.createTime, "{y}-{m}-{d}") : "" }}
              </template>
              <!-- <template #table_visit_time="{ row }">
                {{ row.visitTime ? parseTime(row.visitTime, "{y}-{m}-{d}") : "" }}
              </template> -->
            </vxe-grid>
          </el-col>
        </el-row>
      </div>
      <div class="step2" v-show="currentStep === 2" key="2">
        <el-row>
          <el-col :span="24">
            <div class="sf-title">选择随访模板</div>
          </el-col>
          <el-col :span="24">
            <vxe-grid
              ref="xGrid2"
              v-bind="gridConfig2"
              :columns="columns2"
              :formConfig="formConfig2"
              :proxyConfig="proxyConfig2"
            >
              <template #form_dept="{ data }">
                <TreeDept
                  v-model="data.deptIds"
                  clearable
                  style="width: 300px"
                  :options="deptOptions"
                  :autoFetch="false"
                  :props="{ emitPath: true }"
                  @change="(val) => onDeptChange(val, data)"
                />
              </template>
              <template #form_btn_items>
                <vxe-button type="submit" status="primary" content="查询"></vxe-button>
                <vxe-button type="reset" content="重置"></vxe-button>
              </template>
              <template #t_period_default="{ row }">
                {{ row.periodNumber }}{{ periodUnitEnum.getLabel(row.periodUnit) }}
              </template>
              <template #table_operation="{ row }">
                <vxe-button type="text" status="primary" @click="onPreview(row)">预览</vxe-button>
              </template>
            </vxe-grid>
          </el-col>
        </el-row>
      </div>
      <div class="step3" v-show="currentStep === 3" key="3">
        <el-row>
          <el-col :span="24">
            <vxe-grid ref="xGrid3" v-bind="gridConfig3" :columns="columns3" :data="step3TableList">
              <template #table_lagTime="{ row }">
                {{ row.lagTime }}
              </template>
              <template #table_lagTime_edit="{ row, rowIndex }">
                <el-date-picker
                  transfer
                  v-model="row.lagTime"
                  value-format="yyyy-MM-dd"
                  type="date"
                  placeholder="选择日期"
                  :picker-options="pickerOptions"
                ></el-date-picker>
              </template>
              <template #t_period_default="{ row }">
                {{ row.periodNumber }}{{ periodUnitEnum.getLabel(row.periodUnit) }}
              </template>
              <template #table_operation="{ row }">
                <vxe-button type="text" status="primary" @click="onEditPlan(row)">编辑</vxe-button>
              </template>
            </vxe-grid>
          </el-col>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onLeftBtn">{{ showLeftBtnText }}</el-button>
        <el-button
          type="primary"
          @click="onRightBtn"
          style="margin-left: 20px"
          v-loading="submitting"
        >
          {{ showRightBtnText }}
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="预览模板事项" :visible.sync="previewVisible" width="90%" append-to-body>
      <FollowTaskSetting
        :maxDays="maxDays"
        v-model="detailTaskList"
        :isPreview="previewVisible"
      ></FollowTaskSetting>
      <span slot="footer" class="dialog-footer">
        <el-button @click="previewVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog
      v-if="editFollowPlanVisible"
      title="随访模板编辑"
      :visible.sync="editFollowPlanVisible"
      width="90%"
      append-to-body
      :before-close="onBeforeCloseEditFollowPlan"
    >
      <el-row>
        <el-col :span="24">
          <FollowTaskSetting
            v-show="!visiable"
            :maxDays="maxDays"
            :isPreview="previewVisible"
            v-model="detailTaskList"
            @selectTodo="handleSelectTodo"
            @closeEditDialog="editFollowPlanVisible = false"
            @save="saveItems"
          ></FollowTaskSetting>
          <el-collapse-transition>
            <TodoItemSelector ref="todoSelector" :form="formData" :visiable.sycn="visiable"/>
          </el-collapse-transition>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { commonGridConfig1 } from "@/config/vxeGrid";
import TreeDept from "@/components/TreeDept";
import { getTreeHospDeptByPatient } from "@/api/admin";
import { getMedicalLabel } from "@/api/hospital";
import FollowTaskSetting from "../FollowTaskSetting";
import TodoItemSelector from "../TodoItemSelector";
import {
  getFollowupReportListAPi,
  submitFollowupPlanApi,
} from "@/api/hospital/patientManage/followupPatient";
import {
  getPlanDetail,
  getFollowupTemplateListApi,
} from "@/api/hospital/followupManage/followupPlan";
export default {
  name: "CreateFollowPlan",
  components: {
    TreeDept,
    FollowTaskSetting,
    TodoItemSelector,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  enums: ["followItemStatusEnum", "periodUnitEnum", "periodUnitMap"],
  computed: {
    showModal: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit("update:visible", val);
      },
    },
    showLeftBtnText() {
      if (this.currentStep === 1) {
        return "取 消";
      } else if ([2, 3].includes(this.currentStep)) {
        return "上一步";
      } else {
        return "取 消";
      }
    },
    showRightBtnText() {
      if (this.currentStep === 1) {
        return "下一步";
      } else if (this.currentStep === 2) {
        return "下一步";
      } else {
        return "保 存";
      }
    },
    selectReports() {
      return this.$refs?.xGrid1.getRadioRecord(true) || [];
    },
    selectTemps() {
      return this.$refs?.xGrid2?.getCheckboxRecords(true) || [];
    },
  },
  data() {
    return {
      // 当前所处步骤
      currentStep: 1,
      /**
       * 报到表格配置
       */
      gridConfig1: {
        ...commonGridConfig1,
        rowConfig: {
          keyField: "id",
        },
        radioConfig: {
          reserve: true,
          trigger: "row",
          highlight: true,
        },
        maxHeight: 600,
        transfer: true,
        pagerConfig: {
          enabled: false,
        },
      },
      columns1: [
        {
          type: "seq",
          title: "序号",
          width: 60,
        },
        {
          field: "deptName",
          title: "科室",
        },
        {
          field: "userInfo.userName",
          title: "医生",
        },
        {
          field: "createTime",
          title: "报到时间",
          slots: {
            default: "table_create_time",
          },
        },
        // {
        //   field: "visitTime",
        //   title: "就诊时间",
        //   slots: {
        //     default: "table_visit_time",
        //   },
        // },
        {
          type: "radio",
          width: 120,
          fixed: "right",
        },
      ],
      proxyConfig1: {
        response: {
          list: "data",
        },
        ajax: {
          query: ({ page }) => {
            const { currentPage: pageNum, pageSize } = page;
            console.log("page=", page);
            console.log("执行了");
            return getFollowupReportListAPi(this.$route.params.id);
          },
        },
      },
      /**
       * 随访模板表格配置
       */
      gridConfig2: {
        ...commonGridConfig1,
        rowConfig: {
          keyField: "id",
        },
        checkboxConfig: {
          showHeader: false,
          keyField: "id",
          reserve: true,
          trigger: "row",
          highlight: true,
          checkMethod: ({ row }) => {
            return (
              this.selectTemps.length < 5 ||
              this.selectTemps.findIndex((item) => item.id === row.id) >= 0
            );
          },
        },
        maxHeight: 600,
      },
      formConfig2: {
        titleWidth: 90,
        titleAlign: "right",
        titleColon: true,
        items: [
          {
            field: "deptId",
            title: "科室",
            itemRender: {},
            slots: {
              default: "form_dept",
            },
          },
          {
            field: "labelId",
            title: "应用疾病",
            itemRender: {
              name: "VxeSelect",
              options: [],
              props: {
                clearable: true,
                placeholder: "请选择应用疾病",
                transfer: true,
              },
              optionProps: {
                value: "id",
                label: "name",
              },
            },
          },
          {
            field: "name",
            title: "模板名称",
            itemRender: {
              name: "VxeInput",
              props: {
                clearable: true,
                placeholder: "请选择模板名称",
                style: "width: 300px",
              },
            },
          },
          { itemRender: {}, slots: { default: "form_btn_items" } },
        ],
      },
      columns2: [
        {
          field: "name",
          title: "随访模板名称",
        },
        {
          field: "wardName",
          title: "院区",
        },
        {
          field: "labelName",
          title: "应用疾病",
        },
        {
          field: "deptName",
          title: "科室",
        },
        {
          field: "periodNumber",
          title: "随访周期",
          slots: {
            default: "t_period_default",
          },
        },
        {
          field: "operation",
          title: "操作",
          slots: {
            default: "table_operation",
          },
        },
        {
          type: "checkbox",
        },
      ],
      proxyConfig2: {
        form: true,
        response: {
          result: "data.list",
          total: "data.page.total",
        },
        ajax: {
          query: async ({ form, page }) => {
            const { deptIds, labelId, name } = form;
            const { currentPage: pageNum, pageSize } = page;
            console.log("form=", form);
            console.log("page=", page);
            const queryParams = {
              status: 2,
              deptIds,
              labelId,
              name,
              pageNum,
              pageSize,
            };
            return getFollowupTemplateListApi(queryParams);
          },
        },
      },
      // 科室下拉框数据
      deptOptions: [],
      // 预览弹窗控制
      previewVisible: false,
      maxDays: 0,
      detailTaskList: [],
      /**
       * 随访模板基线
       */
      gridConfig3: {
        ...commonGridConfig1,
        // editConfig: {
        //   trigger: 'click',
        //   mode: 'row'
        // },
        maxHeight: 600,
      },
      columns3: [
        {
          field: "name",
          title: "随访模板名称",
        },
        {
          field: "wardName",
          title: "院区",
        },
        {
          field: "labelName",
          title: "应用疾病",
        },
        {
          field: "deptName",
          title: "应用科室",
        },
        {
          field: "periodNumber",
          title: "随访周期",
          slots: {
            default: "t_period_default",
          },
        },
        {
          field: "lagTime",
          title: "基线时间",
          width: 300,
          slots: {
            default: "table_lagTime_edit",
          },
        },
        {
          field: "operation",
          title: "操作",
          slots: {
            default: "table_operation",
          },
        },
      ],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      // 步骤三表格数据
      step3TableList: [],
      editFollowPlanVisible: false,
      visiable: false,
      submitting: false,
      // 患者id
      patientId: null,
      // 选择的医生id
      doctorId: null,
      // 没选择基线时间的数据
      noLagTime: [],
    };
  },
  methods: {
    // 关闭弹窗
    onBeforeClose(done) {
      this.showModal = false;
    },
    /**
     * 选择随访模板
     *  */
    // 查询科室下拉框数据
    async loadDeptOptions() {
      const res = await getTreeHospDeptByPatient();
      this.deptOptions = res.data || [];
    },
    // 选中科室
    onDeptChange(val, data) {
      console.log("vla=", val);
      console.log("vla=", data);
      data.labelId = null;
      const deptId = val?.[val?.length - 1] || undefined;
      this.loadDiseaseOptions(deptId);
    },
    // 查询应用疾病下拉数据
    async loadDiseaseOptions(deptId) {
      const { data } = await getMedicalLabel({
        deptId: deptId ? deptId : undefined,
      });
      console.log("diseaseOptions=", data);
      await this.$nextTick();
      const $grid = this.$refs.xGrid2;
      if ($grid) {
        const diseaseItem = $grid.getFormItems(1);
        console.log("diseaseItem=", diseaseItem);
        diseaseItem.itemRender.options = data;
      }
    },
    // 选择医生
    onChangeDoctor({ newValue }) {
      console.log("newValue=", newValue);
      this.doctorId = newValue.doctorId;
    },
    // 预览
    async onPreview(row) {
      const { data } = await getPlanDetail(row.id);
      console.log("data=", data);
      this.detailTaskList = data.taskList;
      this.previewVisible = true;
    },
    getDays(periodNumber, periodUnit) {
      switch (periodUnit) {
        case this.periodUnitMap.day:
          return periodNumber;
        case this.periodUnitMap.month:
          return periodNumber * 30;
        case this.periodUnitMap.year:
          return periodNumber * 30 * 12;
      }
    },
    // 编辑计划
    onEditPlan(row) {
      console.log("row=", row);
      this.previewVisible = false;
      this.formData = row;
      this.maxDays = this.getDays(row.periodNumber, row.periodUnit);
      this.detailTaskList = row.taskList;
      this.editFollowPlanVisible = true;
    },
    // 选择待办事项
    async handleSelectTodo(index) {
      const curTask = this.detailTaskList[index];
      this.visiable = true;
      await this.$nextTick();
      this.$refs.todoSelector
        .open(curTask.items)
        .then((items) => {
          this.detailTaskList.splice(index, 1, {
            ...curTask,
            items,
          });
          this.visiable = false;
        })
        .catch(() => {
          this.visiable = false;
        });
    },
    validate() {
      console.log("validate");
      if (this.detailTaskList.length === 0) {
        this.$message.error("随访任务不能为空");
        return false;
      }
      let preTime = 0;
      for (const [index, task] of this.detailTaskList.entries()) {
        if (typeof task.lagNumber !== "number") {
          this.$message.error(`第${index + 1}次随访任务[基线时间+]未选择`);
          return false;
        }
        if (task.items.length === 0) {
          this.$message.error(`第${index + 1}次随访任务未添加待办事项`);
          return false;
        }
        if (task.lagNumber < preTime) {
          this.$message.error(
            `第${index + 1}次随访任务[基线时间+]不能小于${index === 0 ? "0" : "前一次"}`
          );
          return false;
        }
        preTime = task.lagNumber;
        if (task.lagNumber > this.maxDays) {
          this.$message.error(`随访任务[基线时间+]超过了随访总周期`);
          return false;
        }
      }
      return true;
    },
    saveItems() {
      if (!this.validate()) return;
      this.editFollowPlanVisible = false;
    },
    // 上一步/取消
    onLeftBtn() {
      if (this.currentStep === 1) {
        this.showModal = false;
      } else if (this.currentStep === 2) {
        this.currentStep = 1;
      } else if (this.currentStep === 3) {
        this.currentStep = 2;
      }
    },
    // 下一步/保存
    async onRightBtn() {
      if (this.currentStep === 1) {
        if (this.selectReports.length <= 0) {
          console.log("asdadsa", this.selectReports);
          return this.$message.error("请选择一个报到单！");
        }
        this.currentStep = 2;
      } else if (this.currentStep === 2) {
        if (this.selectTemps.length <= 0) {
          return this.$message.error("请至少选择一个随访模版！");
        }
        this.selectTemps.forEach((item) => {
          item.lagTime = "";
        });
        this.step3TableList = JSON.parse(JSON.stringify(this.selectTemps)) || [];
        this.currentStep = 3;
      } else if (this.currentStep === 3) {
        try {
          this.submitting = true;
          console.log();
          await this.$nextTick();
          const labelIds = [];
          this.noLagTime = [];
          const documentList = this.step3TableList.map((item1, index) => {
            const { lagTime, labelId, id: tempId, taskList } = item1;
            if (!lagTime) {
              this.noLagTime.push(index);
            }
            if (labelIds.findIndex(i => i === item1.labelId ) < 0) {
              labelIds.push(labelId);
            }
            const newTaskList = taskList.map((item2) => {
              const { batchNo, lagNumber, lagUnit, items } = item2;
              const newItems = items.map((item3) => {
                const { targetId: itemTempId, targetType: itemType, targetName: itemName } = item3;
                return {
                  itemTempId,
                  itemName,
                  itemType,
                };
              });
              return {
                batchNo,
                lagNumber,
                lagUnit,
                items: newItems,
              };
            });
            return {
              lagTime: new Date(lagTime + " 00:00:00").getTime(),
              tempId,
              taskList: newTaskList,
            };
          });
          if (this.noLagTime.length > 0) {
            return this.$message.error("请完善基线时间");
          }
          const params = {
            patientId: this.patientId,
            doctorId: this.doctorId,
            documentList,
            labelIdList: labelIds,
          };
          await submitFollowupPlanApi(params);
          this.$message.success("操作成功");
          this.showModal = false;
          this.$emit("success");
        } catch (err) {
          console.log("err=", err);
        } finally {
          this.submitting = false;
        }
      }
    },
    onBeforeCloseEditFollowPlan() {
      this.visiable = false
      this.editFollowPlanVisible = false
    },
    async init() {
      this.patientId = this.$route.params.id;
      this.loadDeptOptions();
      await this.$nextTick();
      this.loadDiseaseOptions();
    },
  },
  created() {
    this.init();
  },
};
</script>
<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
}
::v-deep .red-tip {
  .el-input__inner {
    border: 1px solid red !important;
  }
}
::v-deep .el-card__body {
  height: 100%;
}
</style>
