<template>
  <div class="pharmacyd">
    <!-- <div class="back flex-center" @click="$router.back()">返回</div> -->
    <div style="margin-bottom:10px;">
      <el-button @click="$router.back()" type="primary" size="mini">返回</el-button>
      <el-button @click="save()" type="warning" size="mini">保存</el-button>
    </div>
    <div class="form flex-vertical-center-l flex-wrap">
      <div class="form-item flex-vertical-center-l">
        <div class="left flex-vertical-center-r">
          <span></span>
          <div>医共体：</div>
        </div>
        <div class="right">
          <!-- multiple -->
          <el-select
            size="mini"
            v-model="form.area"
            placeholder="请选择"
            @change="getMedSelect(form.area)"
            clearable
          >
            <el-option
              :label="item.name"
              :value="item.pid"
              v-for="(item,index) in doctorBodyList"
              :key="index"
            ></el-option>
          </el-select>
        </div>
      </div>
      <div class="form-item flex-vertical-center-l">
        <div class="left flex-vertical-center-r">
          <span></span>
          <div>医疗机构：</div>
        </div>
        <div class="right">
          <el-select
            size="mini"
            v-model="form.medName"
            placeholder="请选择"
            @change="changeMed"
            clearable
          >
            <el-option
              :label="item.name"
              :value="item.pid"
              v-for="(item,index) in medSelectList"
              :key="index"
            ></el-option>
          </el-select>
        </div>
      </div>
      <div class="form-item flex-vertical-center-l">
        <div class="left flex-vertical-center-r">
          <span></span>
          <div>科室：</div>
        </div>
        <div class="right">
          <!-- <el-select size="mini" v-model="form.departName" placeholder="请选择" clearable>
            <el-option
              :label="item.name"
              :value="item.pid"
              v-for="(item,index) in departSelect"
              :key="index"
            ></el-option>
          </el-select>-->

          <el-cascader
            size="mini"
            :options="departListTree"
            :props="departProps"
            collapse-tags
            clearable
            v-model="form.departName"
          ></el-cascader>
        </div>
      </div>
      <div class="form-item flex-vertical-center-l">
        <div class="left flex-vertical-center-r">
          <span></span>
          <div>排序号：</div>
        </div>
        <div class="right">
          <el-input size="mini" placeholder="请输入" v-model="form.sqen"></el-input>
        </div>
      </div>
      <div class="form-item flex-vertical-center-l">
        <div class="left flex-vertical-center-r">
          <span>*</span>
          <div>显示名称：</div>
        </div>
        <div class="right">
          <el-input size="mini" placeholder="请输入" v-model="form.showName"></el-input>
        </div>
      </div>
      <div class="form-item flex-vertical-center-l">
        <div class="left flex-vertical-center-r">
          <span>*</span>
          <div>药剂类型：</div>
        </div>
        <div class="right">
          <el-select size="mini" v-model="form.doseType" placeholder="请选择" multiple>
            <el-option label="散装饮片" value="1"></el-option>
            <el-option label="散装颗粒剂" value="2"></el-option>
            <el-option label="小包装饮片" value="3"></el-option>
            <el-option label="小包装颗粒剂" value="4"></el-option>
            <el-option label="膏方" value="5"></el-option>
            <el-option label="中药制剂" value="6"></el-option>
          </el-select>
        </div>
      </div>
      <div class="form-item flex-vertical-center-l">
        <div class="left flex-vertical-center-r">
          <span>*</span>
          <div>药房ID：</div>
        </div>
        <div class="right">
          <el-input size="mini" placeholder="请输入" v-model="form.id"></el-input>
        </div>
      </div>

      <div class="form-item flex-vertical-center-l">
        <div class="left flex-vertical-center-r">
          <span>*</span>
          <div>药房名称：</div>
        </div>
        <div class="right">
          <el-input size="mini" placeholder="请输入" v-model="form.name"></el-input>
        </div>
      </div>
      <div class="form-item flex-vertical-center-l">
        <div class="left flex-vertical-center-r">
          <span>*</span>
          <div>地址编号：</div>
        </div>
        <div class="right">
          <!-- <el-select v-model="form.addressCode" placeholder="请选择">
                        <el-option label="区域一" value="shanghai"></el-option>
                        <el-option label="区域二" value="beijing"></el-option>
          </el-select>-->
          <el-input size="mini" v-model="form.addressCode"></el-input>
        </div>
      </div>
      <div class="form-item flex-vertical-center-l">
        <div class="left flex-vertical-center-r">
          <span></span>
          <div>药房属性：</div>
        </div>
        <div class="right">
          <el-select size="mini" v-model="form.attribute" placeholder="请选择">
            <el-option label="门诊" value="0"></el-option>
            <el-option label="住院" value="1"></el-option>
          </el-select>
        </div>
      </div>
      <div class="form-item flex-vertical-center-l">
        <div class="left flex-vertical-center-r">
          <span></span>
          <div>制膏：</div>
        </div>
        <div class="right">
          <el-select size="mini" v-model="form.zhigao" placeholder="请选择">
            <el-option label="显示" value="0"></el-option>
            <el-option label="不显示" value="1"></el-option>
          </el-select>
        </div>
      </div>
      <div class="form-item flex-vertical-center-l">
        <div class="left flex-vertical-center-r">
          <span></span>
          <div>默认制膏：</div>
        </div>
        <div class="right">
          <el-select size="mini" v-model="form.dzhigao" placeholder="请选择">
            <el-option label="是" value="0"></el-option>
            <el-option label="否" value="1"></el-option>
          </el-select>
        </div>
      </div>
      <div class="form-item flex-vertical-center-l">
        <div class="left flex-vertical-center-r">
          <span>{{form.zhigao=='0'?'*':''}}</span>
          <div>制膏费：</div>
        </div>
        <div class="right">
          <el-input size="mini" placeholder="请输入" v-model="form.zhigaoPrice"></el-input>
        </div>
      </div>
      <div class="form-item flex-vertical-center-l">
        <div class="left flex-vertical-center-r">
          <span></span>
          <div>代煎：</div>
        </div>
        <div class="right">
          <el-select size="mini" v-model="form.daijian" placeholder="请选择" multiple clearable>
            <el-option v-for="item in optionsAgency" :key="item.value" v-bind="item" />
          </el-select>
        </div>
      </div>
      <div class="form-item flex-vertical-center-l">
        <div class="left flex-vertical-center-r">
          <span></span>
          <div>默认代煎：</div>
        </div>
        <div class="right">
          <el-select size="mini" v-model="form.ddaijian" placeholder="请选择" clearable>
            <el-option v-for="item in optionsAgency" :key="item.value" v-bind="item" />
          </el-select>
        </div>
      </div>
      <div class="form-item flex-vertical-center-l">
        <div class="left flex-vertical-center-r">
          <span>{{form.daijian=='0'?'*':''}}</span>
          <div>代煎费：</div>
        </div>
        <div class="right">
          <el-input size="mini" placeholder="请输入" v-model="form.daijianPrice"></el-input>
        </div>
      </div>
      <div class="form-item flex-vertical-center-l">
        <div class="left flex-vertical-center-r">
          <span></span>
          <div>配送：</div>
        </div>
        <div class="right">
          <el-select size="mini" v-model="form.peisong" placeholder="请选择" multiple clearable>
            <el-option v-for="item in optionsDelivery" :key="item.value" v-bind="item" />
          </el-select>
        </div>
      </div>
      <div class="form-item flex-vertical-center-l">
        <div class="left flex-vertical-center-r">
          <span></span>
          <div>默认配送：</div>
        </div>
        <div class="right">
          <el-select size="mini" v-model="form.dpeisong" placeholder="请选择" clearable>
            <el-option v-for="item in optionsDelivery" :key="item.value" v-bind="item" />
          </el-select>
        </div>
      </div>
      <div class="form-item flex-vertical-center-l">
        <div class="left flex-vertical-center-r">
          <span>{{form.peisong=='0'?'*':''}}</span>
          <div>配送费：</div>
        </div>
        <div class="right">
          <el-input size="mini" placeholder="请输入" v-model="form.peisongPrice"></el-input>
        </div>
      </div>
      <div class="form-item flex-vertical-center-l">
        <div class="left flex-vertical-center-r">
          <span></span>
          <div>特殊调配：</div>
        </div>
        <div class="right">
          <el-select size="mini" v-model="form.tiaopei" placeholder="请选择">
            <el-option label="显示" value="0"></el-option>
            <el-option label="不显示" value="1"></el-option>
          </el-select>
        </div>
      </div>
      <div class="form-item flex-vertical-center-l">
        <div class="left flex-vertical-center-r">
          <span></span>
          <div>默认特殊调配：</div>
        </div>
        <div class="right">
          <el-select size="mini" v-model="form.dtiaopei" placeholder="请选择">
            <el-option label="是" value="0"></el-option>
            <el-option label="否" value="1"></el-option>
          </el-select>
        </div>
      </div>
      <div class="form-item flex-vertical-center-l">
        <div class="left flex-vertical-center-r">
          <span>{{form.tiaopei=='0'?'*':''}}</span>
          <div>特殊调配费：</div>
        </div>
        <div class="right">
          <el-input size="mini" placeholder="请输入" v-model="form.tiaopeiPrice"></el-input>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
import {
  getDoctorBodySelect,
  getDepartSelect,
  getMedSelect
} from "@/api/system.js";
import {
  addPharmacyData,
  getPharmacyMsg,
  editPharmacMsg,
  getDepartTreeData
} from "@/api/business.js";
export default {
  data() {
    return {
      optionsAgency: [],
      optionsDelivery: [],
      form: {
        area: "",
        medName: "", // 医疗结构
        sqen: "",
        showName: "",
        doseType: [],
        id: "",
        departName: "",
        name: "",
        addressCode: "",
        attribute: "", // 药房属性
        zhigao: "0",
        dzhigao: "1", // 默认制膏
        zhigaoPrice: "", // 制膏费
        daijian: "0",
        ddaijian: "1", // 默认代煎
        daijianPrice: "", // 代煎费
        peisong: "0",
        dpeisong: "1", // 默认配送
        peisongPrice: "", // 配送费
        tiaopei: "0",
        dtiaopei: "1", // 默认调配
        tiaopeiPrice: "" // 调配费
      },
      doctorBodyList: [],
      departSelect: [],
      medSelectList: [], // 医疗结构下拉
      type: "add",
      pid: "",
      departProps: {
        multiple: true,
        value: "id",
        label: "name"
      },
      departListTree: []
    };
  },
  created() {
    this.getDoctorBodySelect();
    // this.getDepartSelect()

    this.pid = this.$route.query.pid;

    if (this.pid) {
      this.type = "edit";
      this.getPharmacyMsg();
    }
  },
  methods: {
    // 医疗机构修改
    changeMed() {
      // this.getDepartSelect(this.form.medName);
      this.getDepartList(this.form.medName);
    },
    // id去重
    removalID(arr) {
      let setArr = new Set(arr);
      return Array.from(setArr);
    },
    save() {
      if (this.form.showName == "") {
        this.$message({
          message: "请输入显示名称",
          type: "error",
          showClose: true
        });
        return;
      }
      if (this.form.doseType.length == 0) {
        this.$message({
          message: "请选择药剂类型",
          type: "error",
          showClose: true
        });
        return;
      }
      if (this.form.id == "") {
        this.$message({
          message: "请输入药房id",
          type: "error",
          showClose: true
        });
        return;
      }
      if (this.form.name == "") {
        this.$message({
          message: "请输入药房名称",
          type: "error",
          showClose: true
        });
        return;
      }
      // if (this.form.addressCode == '') {
      //     this.$message({
      //         message: '请输入地址编号',
      //         type: 'error',
      //         showClose: true
      //     })
      //     return
      // }
      if (this.form.zhigaoPrice === "" && this.form.zhigao == "0") {
        this.$message({
          message: "请输入制膏费",
          type: "error",
          showClose: true
        });
        return;
      }
      if (this.form.daijianPrice === "" && this.form.daijian == "0") {
        this.$message({
          message: "请输入代煎费",
          type: "error",
          showClose: true
        });
        return;
      }
      if (this.form.peisongPrice === "" && this.form.peisong == "0") {
        this.$message({
          message: "请输入配送费",
          type: "error",
          showClose: true
        });
        return;
      }
      if (this.form.tiaopeiPrice === "" && this.form.tiaopei == "0") {
        this.$message({
          message: "请输入特殊调配费",
          type: "error",
          showClose: true
        });
        return;
      }
      this.setPharmacyMsg();
    },

    // 获取医共体选择器
    async getDoctorBodySelect() {
      let res = await getDoctorBodySelect();
      if (res.ResultCode == 0) {
        this.doctorBodyList = res.Data;
      }
    },
    // 获取医疗机构选择器
    async getMedSelect(id, type = "change") {
      let params = {
        organizationId: id
      };
      let res = await getMedSelect(params);
      if (res.ResultCode == 0) {
        this.medSelectList = res.Data;
        if (type == "change") {
          this.form.medName = "";
          this.form.departName = [];
        }
      }
    },
    // 获取科室树形结构
    async getDepartList(id, type = "1") {
      let res = await getDepartTreeData({ institutionId: id });
      if (res.ResultCode == 0) {
        // res.Data.forEach(item => {
        //   if (item.children) {
        //     item.children.forEach(item1 => {
        //       if (!item1.children) {
        //         item1.children = [
        //           {
        //             name: item1.name + Math.random() * 100,
        //             id: new Date().getTime(),
        //             parentdepartmentidSelsource: item1.id
        //           },
        //           {
        //             name: item1.name + Math.random() * 100,
        //             id: new Date().getTime(),
        //             parentdepartmentidSelsource: item1.id
        //           },
        //           {
        //             name: item1.name + Math.random() * 100,
        //             id: new Date().getTime(),
        //             parentdepartmentidSelsource: item1.id
        //           }
        //         ];
        //       }
        //     });
        //   }
        // });
        this.departListTree = res.Data;
        if (type != 1) return;
        this.form.departName = makeData([], [], res.Data);

        res.Data.forEach((item, index) => {});
      }

      function makeData(list, upArray, dataSource) {
        dataSource.forEach(item => {
          const array = [...upArray, item.id];
          if (item.children) {
            makeData(list, array, item.children);
          } else {
            list.push(array);
          }
        });
        return list;
      }
    },
    // 获取科室选择器
    async getDepartSelect(id, type = "change") {
      let res = await getDepartSelect({
        // institutionId: this.getuserinfo.sititutionid
        institutionId: id
      });
      if (res.ResultCode == 0) {
        this.departSelect = res.Data;
        if (type == "change") {
          this.form.departName = [];
        }
      }
    },
    // 获取详细数据
    async getPharmacyMsg() {
      let res = await getPharmacyMsg(this.pid);
      if (res.ResultCode == 0) {
        let data = res.Data;
        this.optionsAgency = data.optionsAgency;
        this.optionsDelivery = data.optionsDelivery;
        this.form = {
          area: data.usableRange,
          sqen: data.seqn,
          showName: data.displayName,
          doseType: data.dosageForms.split(","),
          id: data.pharmacyId,
          // departName: data.departmentidSelsource,
          departName: data.ksIds ? JSON.parse(data.ksIds) : [],
          name: data.pharmacyName,
          addressCode: data.areaCode,
          attribute: data.pharmacyProperties, // 药房属性
          zhigao: data.displaySystemOfCream,
          dzhigao: data.defaultSystemOfCream, // 默认制膏
          zhigaoPrice: data.systemOfCreamPrice, // 制膏费
          daijian: data.displayAgency,
          ddaijian: data.defaultAgency, // 默认代煎
          daijianPrice: data.agencyPrice, // 代煎费
          peisong: data.displayDelivery,
          dpeisong: data.defaultDelivery, // 默认配送
          peisongPrice: data.deliveryPrice, // 配送费
          tiaopei: data.displaySpecialDeployment,
          dtiaopei: data.defaultSpecialDeployment, // 默认调配
          tiaopeiPrice: data.specialDeploymentPrice, // 调配费
          medName: data.stitutionsId
        };

        this.getMedSelect(this.form.area, "auto");
        // this.getDepartSelect(this.form.medName, "auto");
        this.getDepartList(this.form.medName, data.ksIds ? "auto" : "1");
      }
    },
    // 设置详细数据
    async setPharmacyMsg() {
      let ksIds = JSON.stringify(this.form.departName);
      let departmentidSelsource = [];
      let list = this.form.departName;

      let departIds = [];
      list.forEach(item => {
        departIds = [...departIds, ...item];
      });

      departmentidSelsource = this.removalID(departIds);

      let displayAgency = '';
      let displayDelivery = '';
      if (Array.isArray(this.form.daijian)) {
        displayAgency = this.form.daijian.map(value => {
          const option = this.optionsAgency.find(option => option.value === value);
          return option ? `${option.label}:${option.value}` : void 0;
        }).filter(Boolean).join(',');
      }
      if (Array.isArray(this.form.peisong)) {
        displayDelivery = this.form.peisong.map(value => {
          const option = this.optionsDelivery.find(option => option.value === value);
          return option ? `${option.label}:${option.value}` : void 0;
        }).filter(Boolean).join(',');
      }
      let params = {
        agencyPrice: this.form.daijianPrice,
        areaCode: this.form.addressCode,
        defaultAgency: this.form.ddaijian,
        defaultDelivery: this.form.dpeisong,
        defaultSpecialDeployment: this.form.dtiaopei,
        defaultSystemOfCream: this.form.dzhigao,
        deliveryPrice: this.form.peisongPrice,
        departmentidSelsource: departmentidSelsource.join(","),
        ksIds,
        displayAgency,
        displayDelivery,
        displayName: this.form.showName,
        displaySpecialDeployment: this.form.tiaopei,
        displaySystemOfCream: this.form.zhigao,
        dosageForms: this.form.doseType.join(","),
        pharmacyId: this.form.id,
        pharmacyName: this.form.name,
        pharmacyProperties: this.form.attribute,
        seqn: this.form.sqen,
        specialDeploymentPrice: this.form.tiaopeiPrice,
        // stitutionsId: this.getuserinfo.sititutionid,
        systemOfCreamPrice: this.form.zhigaoPrice,
        usableRange: this.form.area,
        stitutionsId: this.form.medName,
        pid: this.pid
      };
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      let request = Promise.reject();
      if (this.type === 'edit') {
        params.pid = this.pid;
        request = editPharmacMsg(params);
      } else if (this.type === 'add') {
        request = addPharmacyData(params);
      }
      try {
        const res = await request;
        if (+res.ResultCode === 0) {
          this.$message({
            message: '提交成功',
            showClose: true,
            type: 'success',
          });
          setTimeout(() => { this.$router.back(); }, 1000);
        }
      } finally {
        loading.close();
      }
    }
  },
  computed: {
    ...mapGetters(["getuserinfo", "getPatiensInfo", "getActiveID", "getActive"])
  }
};
</script>
<style lang="scss" scoped>
@import "../../style/common.scss";

.pharmacyd {
  height: 100%;
  padding: 10px 10px;
  background: #ffffff;
  border-radius: 5px;

  box-sizing: border-box;

  .back {
    width: 74px;
    height: 36px;
    background: #5386f6;
    border-radius: 4px;
    font-size: 14px;
    font-family: PingFang SC;
    font-weight: 400;
    color: #ffffff;
    cursor: pointer;
    margin-bottom: 60px;
  }

  .form {
    height: 90%;
    overflow: auto;

    .form-item {
      margin-right: 10px;
      margin-bottom: 10px;

      .left {
        width: 130px;
        font-size: 16px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #333333;

        span {
          color: #ff3a3a;
        }
      }

      .right {
        width: 260px;
      }
    }
  }

  .save {
    width: 74px;
    height: 36px;
    background: #ffae45;
    border-radius: 4px;
    font-size: 14px;
    font-family: PingFang SC;
    font-weight: 400;
    color: #ffffff;
    cursor: pointer;
    margin-top: 30px;
  }
}

.right::v-deep .el-select {
  width: 100%;
}

.right ::v-deep .el-cascader--mini {
  width: 100%;
}
</style>