<template>
  <div class="app-container">
    <vxe-grid ref="gridRef" v-bind="gridConfig">
      <template #toolbar_button_d="{ $grid }">
        <vxe-button status="primary" icon="vxe-icon-add" class="mr-10" @click="onAdd">
          新增治疗方案
        </vxe-button>
        <vxe-button
          status="danger"
          icon="vxe-icon-delete"
          class="mr-10"
          :disabled="
            !($grid && $grid.getCheckboxRecords && $grid.getCheckboxRecords(true).length > 0)
          "
          @click="onBatchDel"
        >
          批量删除
        </vxe-button>
        <el-upload
          ref="upload"
          action=""
          accept=".xlsx, .csv"
          list-type="text"
          :multiple="false"
          :limit="1"
          :show-file-list="false"
          :http-request="handleUpload"
          auto-upload
        >
          <vxe-button status="success" icon="vxe-icon-upload" class="mr-10">
            批量导入数据
          </vxe-button>
        </el-upload>
        <a :href="exportTemplateUrl" download="批量导入治疗方案模版.xlsx">
          <vxe-button status="danger" icon="vxe-icon-download" class="mr-10">
            下载数据模板
          </vxe-button>
        </a>
      </template>
      <template #dept_f_d="{ data }">
        <tree-dept
          v-model="data.deptId"
          clearable
          class="w-240"
          :options="deptOptions"
          :props="{ emitPath: false, checkStrictly: true }"
          placeholder="全部"
          @change="() => onChangeDept(data)"
        ></tree-dept>
      </template>
      <template #op_t_d="{ row }">
        <vxe-button type="text" status="primary" @click="onEdit(row)">编辑</vxe-button>
        <vxe-button type="text" status="danger" @click="onDelete(row)">删除</vxe-button>
      </template>
    </vxe-grid>
    <add-therapeutic-dialog
      v-if="visible"
      :visible.sync="visible"
      :id="editId"
      :getTableList="getTableList"
    />
    <ImportResultPopup ref="importResult" />
  </div>
</template>
<script>
import ImportResultPopup from "@/components/ImportResultPopup";
import AddTherapeuticDialog from "./components/AddTherapeuticDialog.vue";
import { commonGridConfig2 } from "@/config/vxeGrid";
import { getAllHospital } from "@/api/dictManage/hosp";
import TreeDept from "@/components/TreeDept";
import { getTreeHospDept } from "@/api/index";
import {
  getTherapeuticListApi,
  delTherapeuticApi,
  batchDelTherapeuticApi,
  bathImportTherapeuticApi,
} from "@/api/dictManage/therapeutic";
import { diseasePageList } from "@/api/dictManage/disease";
import { to } from "await-to-js";
export default {
  name: "TherapeuticRegimen",
  components: {
    TreeDept,
    AddTherapeuticDialog,
    ImportResultPopup,
  },
  data() {
    return {
      exportTemplateUrl: process.env.VUE_APP_BASE_PATH + "template/therapeuticTemplate.xlsx",
      gridConfig: {
        ...commonGridConfig2,
        keepSource: true,
        formConfig: {
          data: {
            wardId: null,
          },
          titleColon: true,
          titleAlign: "right",
          titleWidth: 80,
          items: [
            {
              field: "wardId",
              title: "院区",
              itemRender: {
                name: "VxeSelect",
                props: {
                  placeholder: "全部",
                  className: "w-240",
                  clearable: true,
                  filterable: true,
                },
                options: [],
                optionProps: {
                  value: "id",
                  label: "name",
                },
                events: {
                  change: this.onChangeWard,
                },
              },
            },
            {
              field: "deptId",
              title: "科室",
              itemRender: {},
              slots: {
                default: "dept_f_d",
              },
            },
            {
              field: "medicalLabelId",
              title: "潜在疾病",
              itemRender: {
                name: "VxeSelect",
                props: {
                  placeholder: "全部",
                  className: "w-240",
                  clearable: true,
                  filterable: true,
                },
                options: [],
                optionProps: {
                  value: "id",
                  label: "name",
                },
              },
            },
            {
              field: "name",
              title: "治疗方案",
              itemRender: {
                name: "VxeInput",
                props: {
                  placeholder: "请输入治疗方案",
                  className: "w-240",
                },
              },
            },
            {
              itemRender: {
                name: "VxeButtonGroup",
                options: [
                  { type: "submit", content: "搜索", status: "primary" },
                  { type: "reset", content: "重置" },
                ],
              },
            },
          ],
        },
        columns: [
          {
            type: "checkbox",
            width: 60,
          },
          {
            type: "seq",
            title: "序号",
            minWidth: 100,
          },
          {
            field: "medicalLabelName",
            title: "潜在疾病",
            minWidth: 200,
          },
          {
            field: "name",
            title: "治疗方案名称",
            minWidth: 200,
          },
          {
            field: "minPrice",
            title: "最低价格",
            minWidth: 200,
          },
          {
            field: "maxPrice",
            title: "最高价格",
            minWidth: 200,
          },
          {
            field: "wardName",
            title: "院区",
            minWidth: 200,
          },
          {
            field: "level1DeptName",
            title: "一级科室",
            minWidth: 200,
          },
          {
            field: "level2DeptName",
            title: "二级科室",
            minWidth: 200,
          },
          {
            field: "operation",
            title: "操作",
            width: 200,
            fixed: "right",
            slots: {
              default: "op_t_d",
            },
          },
        ],
        checkboxConfig: {
          trigger: "cell",
          // reserve: true,
        },
        rowConfig: {
          keyField: "id",
          isCurrent: true,
          isHover: true,
        },
        proxyConfig: {
          form: true,
          response: {
            result: "data.list",
            total: "data.page.total",
          },
          ajax: {
            query: ({ form, page }) => {
              console.log("form=", form);
              console.log("page=", page);
              const { currentPage: pageNum, pageSize } = page;
              console.log("pageNum=", pageNum);
              console.log("pageSize=", pageSize);
              const params = {
                pageNum,
                pageSize,
                ...form,
              };
              return getTherapeuticListApi(params);
            },
          },
        },
        toolbarConfig: {
          slots: {
            buttons: "toolbar_button_d",
          },
        },
      },
      deptOptions: [],
      uploading: false,
      visible: false,
      editId: null,
    };
  },
  methods: {
    init() {
      this.getWardOptions();
      this.getDeptOptions();
      this.getDiseaseOptions();
    },
    // 获取院区下拉选项
    async getWardOptions() {
      const [err, res] = await to(getAllHospital());
      await this.$nextTick();
      const formItem = this.$refs.gridRef.getFormItems(0);
      console.log("formItem=", formItem);
      if (err) {
        formItem.itemRender.options = [];
        return;
      }
      formItem.itemRender.options = res.data;
    },
    // 院区改变
    onChangeWard({ data }) {
      data.deptId = null;
      data.medicalLabelId = null;
      const { wardId } = data;
      const params = {
        wardId,
      };
      this.getDeptOptions(params);
      this.getDiseaseOptions(params);
    },
    // 获取科室选项
    async getDeptOptions(params = {}) {
      const [err, res] = await to(
        getTreeHospDept({
          ...params,
        })
      );
      console.log("err=", err);
      if (err) {
        this.deptOptions = [];
        return;
      }
      this.deptOptions = res.data || [];
    },
    // 选择科室
    onChangeDept(formData) {
      formData.medicalLabelId = null;
      console.log("deptId=", deptId);
      const { wardId, deptId } = formData;
      const params = { wardId, deptId };
      this.getDiseaseOptions(params);
    },
    // 获取疾病选项
    async getDiseaseOptions(params = {}) {
      const [err, res] = await to(
        diseasePageList({
          pageNum: 1,
          pageSize: 999,
          ...params,
        })
      );
      await this.$nextTick();
      const formItem = this.$refs.gridRef.getFormItems(2);
      if (err) {
        formItem.itemRender.options = [];
        return;
      }
      formItem.itemRender.options = res.data?.list;
    },
    getTableList() {
      this.$nextTick(() => {
        this.$refs.gridRef.commitProxy("query");
      });
    },
    onAdd() {
      this.editId = null;
      this.visible = true;
    },
    // 编辑
    onEdit(row) {
      console.log("row=", row);
      const { id } = row;
      this.editId = id;
      this.visible = true;
    },
    // 删除
    onDelete(row) {
      this.$modal
        .confirm("是否确认删除？")
        .then(async () => {
          console.log("row.id", row.id);
          const [err, _] = await to(delTherapeuticApi(row.id));
          this.getTableList();
          if (err) {
            return;
          }
          this.$message.success("操作成功");
        })
        .catch(() => {});
    },
    // 导入
    async handleUpload({ file }) {
      this.uploading = true;
      try {
        const res = await bathImportTherapeuticApi(file);
        if (res.data.successSize > 0) {
          // 刷新
          this.getTableList();
        }
        this.$refs.importResult.open(res.data);
      } finally {
        this.$refs.upload.clearFiles();
        this.uploading = false;
      }
    },
    // 批量删除
    onBatchDel() {
      this.$modal.confirm("是否确认批量删除？").then(async () => {
        await this.$nextTick();
        const checkedData = this.$refs.gridRef.getCheckboxRecords(true);
        console.log("checkedData=", checkedData);
        const ids = checkedData.map((item) => item.id);
        const [err, _] = await to(batchDelTherapeuticApi(ids));
        this.getTableList();
        if (err) {
          return;
        }
        this.$message.success("操作成功");
      });
    },
  },
  mounted() {
    this.init();
  },
};
</script>
