<template>
  <vxe-modal type="modal" v-bind="modalConfig" v-model="show" :title="showTitle">
    <vxe-form
      ref="formRef"
      v-bind="formConfig"
      :data="formData"
      :rules="formRules"
      :loading="loadingDetail"
    >
      <template #dept_f_d="{ data }">
        <tree-dept
          :disabled="!!id"
          v-model="data.deptId"
          clearable
          class="w-full"
          :options="deptOptions"
          :props="{ emitPath: false, checkStrictly: true }"
          :autoFetch="false"
          @change="() => onChangeDept(data)"
        ></tree-dept>
      </template>
      <template #a3_f_d="{ data }">
        <div class="flex justify-center items-center">
          <vxe-input
            v-model="data.minPrice"
            class="flex-1"
            type="float"
            :min="0"
            :max="9999999.99"
            :step="1"
            :digits="2"
          />
          <span>——</span>
          <vxe-input
            v-model="data.maxPrice"
            class="flex-1"
            type="float"
            :min="0"
            :max="9999999.99"
            :step="1"
            :digits="2"
          />
        </div>
      </template>
    </vxe-form>
    <template #footer>
      <div class="flex justify-center">
        <vxe-button @click="onCancel">取 消</vxe-button>
        <vxe-button status="primary" @click="onSubmit" :loading="isLoading">确 认</vxe-button>
      </div>
    </template>
  </vxe-modal>
</template>
<script>
import TreeDept from "@/components/TreeDept";
import { modalConfigMap } from "@/config/vxeModal";
import { requireReg } from "@/regular";
import { getTreeHospDept } from "@/api/index";
import { getAllHospital } from "@/api/dictManage/hosp";
import { diseasePageList } from "@/api/dictManage/disease";
import {
  getTherapeuticApi,
  addTherapeuticApi,
  editTherapeuticApi,
} from "@/api/dictManage/therapeutic";
import { to } from "await-to-js";
import Decimal from "decimal.js";
export default {
  name: "AddTherapeuticDialog",
  components: {
    TreeDept,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      default: () => null,
    },
    getTableList: {
      type: Function,
      default: () => {},
    },
  },
  computed: {
    show: {
      get: function () {
        return this.visible;
      },
      set: function (newValue) {
        this.$emit("update:visible", newValue);
      },
    },
    showTitle: function () {
      return this.id ? "编辑治疗方案" : "新增治疗方案";
    },
  },
  data() {
    const priceValidator = ({ data }) => {
      if ((!data.minPrice && data.minPrice != "0") || (!data.maxPrice && data.maxPrice != "0")) {
        return new Error("请输入价格范围");
      }
      if (new Decimal(data.minPrice).comparedTo(new Decimal(data.maxPrice)) > 0) {
        return new Error("请输入正确的价格范围");
      }
    };
    return {
      modalConfig: {
        ...modalConfigMap.get("default"),
      },
      formConfig: {
        span: 24,
        titleAlign: "right",
        titleWidth: 120,
        titleColon: true,
        titleAsterisk: true,
        items: [
          {
            field: "wardId",
            title: "所属院区",
            itemRender: {
              name: "VxeSelect",
              props: {
                placeholder: "请选择",
                filterable: true,
                disabled: !!this.id,
              },
              options: [],
              optionProps: {
                value: "id",
                label: "name",
              },
              events: {
                change: this.onChangeWard,
              },
            },
          },
          {
            field: "deptId",
            title: "所属科室",
            slots: {
              default: "dept_f_d",
            },
          },
          {
            field: "medicalLabelId",
            title: "潜在疾病",
            itemRender: {
              name: "VxeSelect",
              props: {
                placeholder: "请选择",
                filterable: true,
                disabled: !!this.id,
              },
              options: [],
              optionProps: {
                value: "id",
                label: "name",
              },
            },
          },
          {
            field: "name",
            title: "治疗方案",
            itemRender: {
              name: "VxeInput",
              props: {
                placeholder: "请输入",
                clearable: true,
                maxlength: 32,
              },
            },
          },
          {
            field: "minPrice",
            title: "价格区间",
            titleAsterisk: true,
            slots: {
              default: "a3_f_d",
            },
          },
        ],
      },
      formRules: {
        wardId: [requireReg("请选择所属院区")],
        deptId: [requireReg("请选择所属科室")],
        medicalLabelId: [requireReg("请选择潜在疾病")],
        name: [requireReg("请输入治疗方案")],
        minPrice: [
          requireReg("请输入价格范围"),
          {
            validator: priceValidator,
          },
        ],
      },
      formData: {
        id: undefined,
        wardId: null,
        deptId: null,
        medicalLabelId: null,
        name: null,
        minPrice: null,
        maxPrice: null,
      },
      deptOptions: [],
      isLoading: false,
      loadingDetail: false,
    };
  },
  methods: {
    async init() {
      await this.getDetail();
      this.getWardOptions();
      this.getDeptOptions();
      this.getDiseaseOptions();
    },
    // 获取详情
    async getDetail() {
      console.log("this.editId=", this.id);
      if (this.id) {
        this.loadingDetail = true;
        const [err, res] = await to(getTherapeuticApi(this.id));
        setTimeout(() => {
          this.loadingDetail = false;
        }, 500);

        if (err) {
          return;
        }
        const { id, wardId, deptId, medicalLabelId, name, minPrice, maxPrice } = res?.data || {};
        this.formData = {
          id,
          wardId,
          deptId,
          medicalLabelId,
          name,
          minPrice,
          maxPrice,
        };
      }
    },
    // 获取院区下拉选项
    async getWardOptions() {
      const [err, res] = await to(getAllHospital());
      await this.$nextTick();
      const formItem = this.$refs.formRef.getItems();
      console.log("formItem=", formItem);
      if (err) {
        formItem[0].itemRender.options = [];
        return;
      }
      formItem[0].itemRender.options = res.data;
    },
    // 切换院区
    onChangeWard({ data }) {
      console.log("切换院区");
      data.deptId = null;
      data.medicalLabelId = null;
      this.getDeptOptions();
      this.getDiseaseOptions();
    },
    // 获取科室下拉选项
    async getDeptOptions() {
      const { wardId } = this.formData;
      const [err, res] = await to(
        getTreeHospDept({
          wardId,
        })
      );
      console.log("err=", err);
      if (err) {
        this.deptOptions = [];
        return;
      }
      this.deptOptions = res.data || [];
    },
    // 切换科室
    onChangeDept(data) {
      console.log("切换科室");
      // 切换科室
      data.medicalLabelId = null;
      this.getDiseaseOptions();
    },
    // 获取疾病选项
    async getDiseaseOptions() {
      const { wardId, deptId } = this.formData;
      const [err, res] = await to(
        diseasePageList({
          pageNum: 1,
          pageSize: 999,
          wardId,
          deptId,
        })
      );
      await this.$nextTick();
      const formItem = this.$refs.formRef.getItems();
      console.log("formItem=", formItem);
      if (err) {
        formItem[2].itemRender.options = [];
        return;
      }
      formItem[2].itemRender.options = res.data?.list;
    },
    // 提交
    async onSubmit() {
      await this.$nextTick();
      const isNoPass = await this.$refs.formRef.validate();
      if (isNoPass) {
        return;
      }
      this.isLoading = true;
      const { id, wardId, deptId, medicalLabelId, name, minPrice, maxPrice } = this.formData;
      const params = {
        id,
        wardId,
        deptId,
        medicalLabelId,
        name,
        minPrice,
        maxPrice,
      };
      if (this.formData.id) {
        const [err, res] = await to(editTherapeuticApi(params));
        this.isLoading = false;
        if (err) {
          return;
        }
      } else {
        const [err, res] = await to(addTherapeuticApi(params));
        this.isLoading = false;
        if (err) {
          return;
        }
      }
      this.show = false;
      this.$message.success("操作成功");
      this.getTableList();
    },
    // 取消
    onCancel() {
      this.show = false;
    },
  },
  created() {
    this.init();
  },
};
</script>
