<script>
import useColumns from "./columns";
import {
  addReq,
  getReqDetail,
  editReq,
  saveAndToOa,
  betchSubmit,
  classifyDetails,
  getDiCode,
} from "@/api/requisition/basic";
import { REFER } from "@/components/popover-select/api/index";
export default {
  name: "AddRequsition",
  props: {
    dict: {
      type: [Object, Array],
    },
    addType: {
      type: String,
      default: "add",
    },
  },
  components: {
    ElSuperForm: () => import("@/components/super-form/index.vue"),
    ElSuperTable: () => import("@/components/super-table/index.vue"),
    ElSuperUxTable: () => import("@/components/super-ux-table/index.vue"),
    ElPopoverSelectV2: () => import("@/components/popover-select-v2/index.vue"),
    ElPopoverTreeSelect: () =>
      import("@/components/popover-tree-select/index.vue"),
  },
  data() {
    const {
      MaterialColums,
      TabColumns,
      TabColumns: [
        {
          item: { key: tabName },
        },
      ],
    } = useColumns();

    let rules = TabColumns.reduce((pre, cur) => {
      pre = {
        ...pre,
        ...this.$init.rules([...cur.TableColumns]),
      };
      return pre;
    }, {});
    const sysMaterialApply = this.$init.params([
      ...TabColumns.find(({ item }) => item.key === "sysMaterialApply")
        .TableColumns,
    ]);
    const sysMaterialMedcineApply = this.$init.params([
      ...TabColumns.find(({ item }) => item.key === "sysMaterialMedcineApply")
        .TableColumns,
    ]);
    const applyBillInfo = this.$init.params([
      ...TabColumns.find(({ item }) => item.key === "applyBillInfo")
        .TableColumns,
    ]);
    const materialReference = this.$init.params([...MaterialColums]);
    return {
      width: "100%",
      visible: false,
      loading: false,
      rules,
      params: {
        sysMaterialApply: sysMaterialApply,
        sysMaterialMedcineApply: sysMaterialMedcineApply,
        sysMaterialMedcineItemApply: [],
        applyBillInfo: applyBillInfo,
      },
      // 维护物料类别
      maintenanceMaterialType: {
        drugName: "",
        drugCode: "",
        drugId: "",
      },
      // 物料参考
      materialReference: materialReference,
      materialColums: MaterialColums[0],
      tabName: tabName,
      TabColumns: TabColumns,
      count: 0,
      delDemandItemList: [],
    };
  },
  computed: {
    title: {
      get() {
        const { addType } = this;
        if (addType === "add") {
          return "新 增";
        }
        if (addType === "edit") {
          return "编 辑";
        }
        if (addType === "see") {
          return "查 看";
        }
      },
      set() {},
    },
  },
  watch: {
    "params.sysMaterialApply.isMedicine": {
      handler: async function (nVal, oVal) {
        this.params.sysMaterialMedcineApply.isDrug = nVal === "0" ? "2" : "";
        if (nVal === "2") {
          // 维护物料类别
          try {
            let { code, rows } = await REFER({
              type: "MEDICINE_DRUG",
              search: "其他非医疗器械",
              isPage: false,
            });

            if (code == 200) {
              let { id, code, name } = rows[0];
              this.params.sysMaterialMedcineItemApply = [
                {
                  drugName: name,
                  drugCode: code,
                  drugId: id,
                },
              ];
            }
          } catch (error) {}
        }
      },
    },
    "params.sysMaterialApply.expiryDateManagerment": {
      handler: function (nVal, oVal) {
        if (nVal === "0") {
          this.rules.expiryUnitId = [
            {
              required: true,
              message: "效期单位",
              trigger: "change",
            },
          ];
          this.rules.usefulLife = [
            {
              required: true,
              message: "有效期",
              trigger: "change",
            },
          ];
          this.rules.usefulLifeUnitId = [
            {
              required: true,
              message: "有效期至单位",
              trigger: "change",
            },
          ];
          this.rules.recentWarningPeriod = [
            {
              required:
                this.params.sysMaterialApply.nearOnsetManagerment === "0",
              message: "近效期预警天数",
              trigger: "change",
            },
          ];
        } else {
          let { sysMaterialApply } = this.params;
          sysMaterialApply.expiryUnitId = "";
          sysMaterialApply.usefulLife = "";
          sysMaterialApply.usefulLifeUnitId = "";
          sysMaterialApply.recentWarningPeriod = "";
          this.rules.expiryUnitId = null;
          this.rules.usefulLife = null;
          this.rules.usefulLifeUnitId = null;
          this.rules.recentWarningPeriod = null;
          this.params.sysMaterialApply.nearOnsetManagerment = "2";
        }
        this.count++;
      },
    },
    "params.sysMaterialApply.nearOnsetManagerment": {
      handler: function (nVal, oVal) {
        if (nVal === "0") {
          this.rules.recentWarningPeriod = [
            {
              required:
                this.params.sysMaterialApply.expiryDateManagerment === "0",
              message: "近效期预警天数",
              trigger: "change",
            },
          ];
        } else {
          this.rules.recentWarningPeriod = null;
        }
        this.count++;
      },
    },
    "params.sysMaterialMedcineApply.isDrug": {
      handler: function (nVal, oVal) {
        if (nVal === "2") {
          this.rules.registrationNo = [
            {
              required: true,
              message: "注册证号/备案凭证编号",
              trigger: "change",
            },
          ];
          this.rules.medicalInstruments = [
            {
              required: true,
              message: "管理类别",
              trigger: "change",
            },
          ];
        } else {
          this.rules.registrationNo = null;
          this.rules.medicalInstruments = null;
        }
        this.count++;
      },
    },
  },
  methods: {
    setVisible(prop) {
      this.visible = prop;
    },
    beforeOpen() {
      let { name, nickName, deptId, deptName, orgId, orgName } =
        this.$store.state.user;
      if (this.addType === "add") {
        this.params.sysMaterialApply.isMedicine = "0";
        this.params.sysMaterialApply.storageCondition = "MED2001";
        this.params.sysMaterialApply.isInventoryStatus = "0";
        this.params.sysMaterialApply.transportationCondition = "MED3003";
        this.params.sysMaterialApply.isEnable = "0";
        this.params.sysMaterialApply.materialRateName = "专票13%";
        this.params.sysMaterialApply.materialRate = "1001A11000000000TPTF";
        this.params.sysMaterialApply.rateCode = "CN011";
        this.params.sysMaterialApply.proposerId = name;
        this.params.sysMaterialApply.proposerName = nickName;
        this.params.sysMaterialApply.orgId = "";
        this.params.sysMaterialApply.orgName = "德荣集团";
        this.params.sysMaterialApply.expiryDateManagerment = "0";
        this.params.sysMaterialApply.nearOnsetManagerment = "0";
        //
        this.params.sysMaterialMedcineApply.dosageFrom = "0001A11000000000BX7Z";
        this.params.sysMaterialMedcineApply.dosageFromName = "其他";
      }
      if (this.addType === "see") {
        this.TabColumns = this.TabColumns.map((tab) => {
          return {
            ...tab,
            TableColumns: tab.TableColumns.map(({ item, attr }) => {
              return {
                item: { ...item },
                attr: {
                  ...attr,
                  disabled: true,
                },
              };
            }),
          };
        });
      }
    },

    //
    async fetchItem(prop) {
      console.log(prop, "prop----------------");
      try {
        // try
        this.loading = true;

        let { code, data } = await getReqDetail(prop.id);

        if (code == 200) {
          this.params = data;
          // 复制
          if (this.addType === "add") {
            this.copyEmpty();
          }
        }
      } catch (err) {
        // catch
        console.error(err);
      } finally {
        // finally
        this.loading = false;
      }
    },

    // 复制清空值
    copyEmpty() {
      const { id, name, nickName } = this.$store.state.user;
      let {
        sysMaterialApply,
        sysMaterialMedcineApply,
        sysMaterialMedcineItemApply,
      } = this.params;
      // 基本信息
      sysMaterialApply["id"] = "";
      sysMaterialApply["code"] = "";
      sysMaterialApply["billCode"] = "";
      sysMaterialApply["diCode"] = "";
      sysMaterialApply["healthCode"] = "";
      sysMaterialApply["proposerName"] = nickName;
      sysMaterialApply["proposerId"] = name;
      // 医药属性
      sysMaterialMedcineApply["id"] = "";
      // 维护物料类别
      sysMaterialMedcineItemApply.length &&
        (this.params.sysMaterialMedcineItemApply =
          sysMaterialMedcineItemApply.map((item) => {
            return {
              ...item,
              id: "",
            };
          }));
      // 单据信息
      this.params.applyBillInfo = {
        ...this.$init.params([
          ...this.TabColumns.find(({ item }) => item.key === "applyBillInfo")
            .TableColumns,
        ]),
        auditTime: "",
      };
    },

    //
    async hide() {
      const {
        TabColumns,
        TabColumns: [
          {
            item: { key: tabName },
          },
        ],
      } = useColumns();
      this.visible = false;
      this.$emit("success");
      this.tabName = tabName;
      this.TabColumns = TabColumns;
      this.params = {
        sysMaterialApply: this.$init.params([
          ...TabColumns.find(({ item }) => item.key === "sysMaterialApply")
            .TableColumns,
        ]),
        sysMaterialMedcineApply: this.$init.params([
          ...TabColumns.find(
            ({ item }) => item.key === "sysMaterialMedcineApply"
          ).TableColumns,
        ]),
        sysMaterialMedcineItemApply: [],
        applyBillInfo: this.$init.params([
          ...TabColumns.find(({ item }) => item.key === "applyBillInfo")
            .TableColumns,
        ]),
      };
    },
    //
    async useRowAdd(prop) {
      let { open } = this.$refs.materialTypeTree[0];
      open();
      // const { TableColumns } = this.TabColumns.find(
      //   ({ item: { key } }) => key === prop
      // );
      // this.params[prop].push({
      //   delFlag: "0",
      //   ...this.$init.params(TableColumns),
      // });
    },
    //
    async useRowRemove(prop, scope) {
      scope.row.delFlag = "2";

      let delList = [];

      delList = this.params[prop].filter((item) => {
        return item.delFlag == "2";
      });
      this.params[prop] = this.params[prop].filter((item) => {
        return item.delFlag == "0";
      });
      this.delDemandItemList.push(...delList);
    },
    // saveParams
    handleParams() {
      let list = [];

      let {
        sysMaterialApply: { isMedicine },
        sysMaterialMedcineItemApply,
      } = this.params;

      list.push(...sysMaterialMedcineItemApply, ...this.delDemandItemList);

      // 深拷贝一下参数对象
      let param = JSON.parse(JSON.stringify(this.params));
      param.sysMaterialMedcineItemApply = list;

      if (isMedicine === "0" && !sysMaterialMedcineItemApply.length) {
        return this.$modal.notifyWarning("医药物料需要维护物料类别!");
      }
      console.log(param, "param最终保存传输的值");
      return param;
    },
    // 保存
    async useSave() {
      try {
        this.loading = true;
        let params = await this.handleParams();
        if (params) {
          let { code, msg } =
            this.addType === "add"
              ? await addReq(params)
              : await editReq(params);
          code == 200 && this.hide();
          this.$notify({
            type: code == 200 ? "success" : "error",
            message: msg,
          });
        }
      } catch (error) {
      } finally {
        this.loading = false;
      }
    },
    // 提交
    async useSubmit() {
      try {
        this.loading = true;
        let params = await this.handleParams();
        if (params) {
          let { code, msg } = await betchSubmit({
            ids: [Number(params.sysMaterialApply.id)],
          });
          code == 200 && this.hide();
          this.$notify({
            type: code == 200 ? "success" : "error",
            message: msg,
          });
        }
      } catch (error) {
      } finally {
        this.loading = false;
      }
    },
    // 保存并提交
    async saveSubmit() {
      try {
        this.loading = true;
        let params = await this.handleParams();
        if (params) {
          let { code, msg } = await saveAndToOa(params);
          code == 200 && this.hide();
          this.$notify({
            type: code == 200 ? "success" : "error",
            message: msg,
          });
        }
      } catch (error) {
      } finally {
        this.loading = false;
      }
    },

    materialTypeChange(tabName) {
      let { drugId } = this.maintenanceMaterialType;

      let isExist = this.params[tabName].find((item) => item.drugId === drugId);

      if (isExist) {
        this.$message.warning({
          message: "请勿重复选择",
        });
      } else {
        this.params[tabName].push({
          ...this.maintenanceMaterialType,
          delFlag: "0",
        });
      }
    },
    // 物料参考
    openMaterialReference() {
      let { open } = this.$refs.materialPopoverSelect[0];
      open();
    },
    materialReferenceChange(prop, { source }) {
      this.params.sysMaterialApply = {
        ...this.params.sysMaterialApply,
        ...source,
      };
    },
    // 四级分类带出一二三级分类
    async classifyNameChange(prop, { source }) {
      console.log(source, "source");
      let { classifyId } = source;
      try {
        let {
          code,
          msg,
          data: { oneClass, twoClass, threeClass },
        } = await classifyDetails({ id: classifyId });
        if (code == 200) {
          source.oneClass = oneClass;
          source.twoClass = twoClass;
          source.threeClass = threeClass;
        }
      } catch (error) {}
    },
    // 批号及库存状态管理
    isInventoryStatusChange(prop) {
      let { sysMaterialApply } = this.params;
      if (prop !== "0") {
        sysMaterialApply.expiryDateManagerment = "2";
        sysMaterialApply.serialNoManager = "2";
      }
    },
    // 效期管理
    expiryDateManagermentChange(prop) {
      let { sysMaterialApply } = this.params;
      if (prop !== "0") {
        sysMaterialApply.expiryUnitId = "";
        sysMaterialApply.usefulLife = "";
        sysMaterialApply.usefulLifeUnitId = "";
        sysMaterialApply.recentWarningPeriod = "";
      }
    },
    async changeDiCode(prop) {
      console.log(prop, "prop");
      try {
        let { code, data } = await getDiCode(prop);
        let { sysMaterialApply, sysMaterialMedcineApply } = this.params;
        if (code == 200) {
          if (data.length) {
            sysMaterialApply.name = data[0].cpmctymc;
            sysMaterialApply.model = data[0].ggxh;
            sysMaterialApply.registrant = data[0].ylqxzcrbarmc;
            sysMaterialApply.minPackQty = data[0].zxxsdyzsydydsl;
            sysMaterialApply.manufacturersMaterialCode = data[0].cphhhbh;
            sysMaterialMedcineApply.registrationNo = data[0].zczbhhzbapzbh;
          }
        }
      } catch (error) {}
    },
  },
  created() {},
  mounted() {},
  destroyed() {},
};
</script>

<template>
  <el-drawer
    class="detailsRequsition"
    v-bind="$attrs"
    v-on="$listeners"
    v-loading="loading"
    :visible.sync="visible"
    :size="width"
    :show-close="false"
    destroy-on-close
    @close="hide"
    @open="beforeOpen"
  >
    <div
      slot="title"
      style="display: flex; justify-content: space-between; align-items: center"
    >
      <h3>{{ title }}</h3>
      <div>
        <el-button
          v-if="addType !== 'see'"
          type="primary"
          :size="$attrs.size"
          :loading="loading"
          @click="useSave"
          >保 存</el-button
        >
        <el-button
          v-if="
            addType !== 'see' &&
            (params.sysMaterialApply.status == '0' ||
              params.sysMaterialApply.status == '3')
          "
          type="primary"
          :size="$attrs.size"
          :loading="loading"
          @click="saveSubmit"
          >保存并提交</el-button
        >
        <el-button
          v-if="
            addType === 'see' &&
            (params.sysMaterialApply.status == '0' ||
              params.sysMaterialApply.status == '3')
          "
          type="primary"
          :size="$attrs.size"
          :loading="loading"
          @click="useSubmit"
          >提交</el-button
        >
        <el-button :size="$attrs.size" :loading="loading" @click="hide"
          >取 消</el-button
        >
      </div>
    </div>

    <el-tabs
      v-model="tabName"
      style="margin: 0 16px"
      type="border-card"
      :key="count"
    >
      <el-tab-pane
        v-for="(
          { item, TableColumns: columns, attr: { is } }, index
        ) in TabColumns"
        :key="index"
        :label="item.title"
        :name="item.key"
        lazy
      >
        <!--  -->
        <component
          v-if="is === 'el-super-form' && visible"
          :is="is"
          v-model="params[item.key]"
          :dict="dict"
          :rules="rules"
          :size="$attrs.size"
          :columns="columns"
          :ref="tabName"
          label-width="166px"
          label-position="right"
          style="padding: 0px 18px"
        >
          <!-- 物料名称 -->
          <template slot="name" slot-scope="scope">
            <component
              v-bind="scope.attr"
              v-model="scope.row[scope.item.key]"
              :size="$attrs.size"
              :source.sync="scope.row"
              :disabled="addType === 'see'"
              style="width: 100%"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="openMaterialReference"
              >
                <el-popover-select-v2
                  ref="materialPopoverSelect"
                  v-show="false"
                  title="物料"
                  v-model="materialReference.name"
                  :source.sync="materialReference"
                  v-bind="materialColums.attr"
                  :disabled="addType === 'see'"
                  style="width: 100%"
                  @change="materialReferenceChange"
                >
                </el-popover-select-v2>
              </el-button>
            </component>
          </template>
          <!-- 四级分类 -->
          <template slot="classifyName" slot-scope="scope">
            <component
              v-bind="scope.attr"
              v-model="scope.row[scope.item.key]"
              :size="$attrs.size"
              :source.sync="scope.row"
              :disabled="addType === 'see'"
              @change="classifyNameChange"
              style="width: 100%"
            >
            </component>
          </template>
          <!-- 药品 -->
          <template slot="isDrug" slot-scope="scope">
            <component
              v-bind="scope.attr"
              v-model="scope.row[scope.item.key]"
              :size="$attrs.size"
              :source.sync="scope.row"
              :disabled="
                params.sysMaterialApply.isMedicine !== '0' || addType === 'see'
              "
            >
              <!-- @change="Change({ ...scope, selectData: $event })" -->
              <el-option
                v-for="item in dict.type[scope.attr.dictName]"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </component>
          </template>
          <!--  近效期管理:nearOnsetManagerment -->
          <!-- 批号及库存状态管理 -->
          <template slot="isInventoryStatus" slot-scope="scope">
            <component
              v-bind="scope.attr"
              v-model="scope.row[scope.item.key]"
              :size="$attrs.size"
              :source.sync="scope.row"
              :disabled="addType === 'see'"
              @change="isInventoryStatusChange"
            >
              <el-option
                v-for="item in dict.type[scope.attr.dictName]"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </component>
          </template>
          <!-- 效期管理 -->
          <template slot="expiryDateManagerment" slot-scope="scope">
            <component
              v-bind="scope.attr"
              v-model="scope.row[scope.item.key]"
              :size="$attrs.size"
              :source.sync="scope.row"
              :disabled="
                params.sysMaterialApply.isInventoryStatus !== '0' ||
                addType === 'see'
              "
              @change="expiryDateManagermentChange"
            >
              <el-option
                v-for="item in dict.type[scope.attr.dictName]"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </component>
          </template>
          <!-- 序列号管理 -->
          <template slot="serialNoManager" slot-scope="scope">
            <component
              v-bind="scope.attr"
              v-model="scope.row[scope.item.key]"
              :size="$attrs.size"
              :source.sync="scope.row"
              :disabled="
                params.sysMaterialApply.isInventoryStatus !== '0' ||
                addType === 'see'
              "
            >
              <el-option
                v-for="item in dict.type[scope.attr.dictName]"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </component>
          </template>
          <!-- 有效期 -->
          <template slot="usefulLife" slot-scope="scope">
            <component
              v-bind="scope.attr"
              v-model="scope.row[scope.item.key]"
              :size="$attrs.size"
              :source.sync="scope.row"
              :disabled="
                params.sysMaterialApply.expiryDateManagerment !== '0' ||
                addType === 'see'
              "
              style="width: 100%"
            ></component>
          </template>
          <!-- 效期单位 -->
          <template slot="expiryUnitId" slot-scope="scope">
            <component
              v-bind="scope.attr"
              v-model="scope.row[scope.item.key]"
              :size="$attrs.size"
              :source.sync="scope.row"
              :disabled="
                params.sysMaterialApply.expiryDateManagerment !== '0' ||
                addType === 'see'
              "
            >
              <el-option
                v-for="item in dict.type[scope.attr.dictName]"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </component>
          </template>
          <!-- 有效期至单位 -->
          <template slot="usefulLifeUnitId" slot-scope="scope">
            <component
              v-bind="scope.attr"
              v-model="scope.row[scope.item.key]"
              :size="$attrs.size"
              :source.sync="scope.row"
              :disabled="
                params.sysMaterialApply.expiryDateManagerment !== '0' ||
                addType === 'see'
              "
            >
              <el-option
                v-for="item in dict.type[scope.attr.dictName]"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </component>
          </template>

          <!-- 近效期预警天数 -->
          <template slot="recentWarningPeriod" slot-scope="scope">
            <component
              v-bind="scope.attr"
              v-model="scope.row[scope.item.key]"
              :size="$attrs.size"
              :source.sync="scope.row"
              :disabled="
                params.sysMaterialApply.expiryDateManagerment !== '0' ||
                addType === 'see'
              "
              style="width: 100%"
            ></component>
          </template>

          <!-- 生产厂家/代理人 -->
          <template slot="manufacturerName" slot-scope="scope">
            <component
              v-bind="scope.attr"
              v-model="scope.row[scope.item.key]"
              copy
              readonly
              :size="$attrs.size"
              :source.sync="scope.row"
              :disabled="addType === 'see'"
              style="width: 100%"
            ></component>
          </template>

          <!-- DI -->
          <template slot="diCode" slot-scope="scope">
            <component
              v-bind="scope.attr"
              v-model="scope.row[scope.item.key]"
              :size="$attrs.size"
              :source.sync="scope.row"
              :disabled="addType === 'see'"
              style="width: 100%"
              @change="changeDiCode"
            ></component>
          </template>
        </component>

        <!--  -->
        <component
          v-if="is === 'el-super-ux-table'"
          :is="is"
          v-model="params[item.key]"
          :dict="dict"
          :height="420"
          :ref="tabName"
          :columns="columns"
          :size="$attrs.size"
        >
          <ux-table-column
            fixed="right"
            title="操作"
            width="120"
            align="center"
          >
            <template slot="header" slot-scope="scope">
              <el-button
                v-if="tabName === 'sysMaterialMedcineItemApply'"
                type="text"
                :size="$attrs.size"
                :disabled="addType === 'see'"
                @click="useRowAdd(tabName)"
              >
                增行
                <el-popover-tree-select
                  ref="materialTypeTree"
                  v-show="false"
                  :size="$attrs.size"
                  v-model="maintenanceMaterialType.drugName"
                  :source.sync="maintenanceMaterialType"
                  referName="MEDICINE_DRUG"
                  valueKey="name"
                  :dataMapping="{
                    drugCode: 'code',
                    drugId: 'id',
                  }"
                  :defaultProps="{
                    label: function (data, node) {
                      return data.code + '' + data.name;
                    },
                    children: 'children',
                  }"
                  @change="materialTypeChange(tabName)"
                ></el-popover-tree-select>
              </el-button>
            </template>
            <template slot-scope="scope">
              <el-button
                type="text"
                :size="$attrs.size"
                :disabled="addType === 'see'"
                @click.native.prevent="useRowRemove(tabName, scope)"
              >
                删除
              </el-button>
            </template>
          </ux-table-column>
        </component>
      </el-tab-pane>
    </el-tabs>
  </el-drawer>
</template>

<style scoped lang="scss">
::v-deep.detailsRequsition .el-drawer__header {
  margin: 0;
  padding: 0 16px;
}
</style>
