<template>
  <div class="accordEdit">
    <!-- <div class="flex-center back" @click="$router.back()" v-if='showBtn'>返回</div> -->
    <div class="sticky" v-if="showBtn">
      <el-button size="mini" type="primary" @click="$router.back()" v-if="showBtn">返回</el-button>
      <el-button
        size="mini"
        type="warning"
        v-if="type === 'edit' || type === 'add'"
        @click="save()"
      >保存</el-button>
    </div>
    <div class="flex-vertical-center-l flex-wrap">
      <div class="item flex-vertical-center-l">
        <span>*</span>
        <div class="name">方名：</div>
        <div class="input">
          <el-input size="mini" v-model="form.name" placeholder="请输入" :disabled="type=='find'"></el-input>
        </div>
      </div>
      <div class="item">
        <TCMDiagnosis :patiensMsg="null" ref="tcmd"></TCMDiagnosis>
      </div>
    </div>
    <div class="topForm flex-vertical-center-l flex-wrap">
      <div class="item flex-vertical-center-l">
        <span></span>
        <div class="name">功效与适应症：</div>
        <div class="input">
          <el-input size="mini" v-model="form.efficacy" placeholder="请输入" :disabled="type=='find'"></el-input>
        </div>
      </div>
      <div class="item flex-vertical-center-l">
        <span>*</span>
        <div class="name">共享至：</div>
        <div class="input">
          <el-select size="mini" v-model="form.share" placeholder="请选择" :disabled="type=='find'">
            <el-option
              :label="item.name"
              :value="item.pid"
              v-for="(item,index) in shareSelect"
              :key="index"
            ></el-option>
          </el-select>
        </div>
      </div>
      <div class="item flex-vertical-center-l">
        <span>*</span>
        <div class="name">是否可修改：</div>
        <div class="input">
          <el-select size="mini" v-model="form.type" placeholder="请选择" :disabled="type=='find'">
            <el-option label="是" value="0"></el-option>
            <el-option label="否" value="1"></el-option>
          </el-select>
        </div>
      </div>
      <div class="item flex-vertical-center-l">
        <span></span>
        <div class="name">处方出处：</div>
        <div class="input">
          <el-input size="mini" v-model="form.provenance" placeholder="请输入" :disabled="type=='find'"></el-input>
        </div>
      </div>
      <template v-if="showPurposeType">
        <div class="item flex-vertical-center-l">
          <span></span>
          <div class="name"></div>
          <div class="input">
            <el-checkbox size="mini" :value="isPurposeType" :disabled="!!medicineLength"
                         @change="form.purposeType = $event ? '1' : '0';isPurposeType && getHospitalCategory();"
            >统建处方</el-checkbox>
          </div>
        </div>
        <template v-if="isPurposeType">
          <div class="item flex-vertical-center-l">
            <span></span>
            <div class="name">医派：</div>
            <div class="input">
              <el-input v-model="form.sectCategory" placeholder="请输入"></el-input>
            </div>
          </div>
          <div class="item flex-vertical-center-l">
            <span></span>
            <div class="name">科室：</div>
            <div class="input">
              <el-input v-model="form.sectDept" placeholder="请输入"></el-input>
            </div>
          </div>
        </template>
      </template>
    </div>

    <div class="bottom">
      <MedicineAccord :isPurposeType="isPurposeType" @length="medicineLength = $event"></MedicineAccord>
    </div>
    <div class="topForm flex-vertical-center-l">
      <div class="item flex-vertical-center-l">
        <span></span>
        <div class="name">剂数：</div>
        <div class="input">
          <el-input size="mini" v-model="form.doseNum" placeholder="请输入" :disabled="type=='find'"></el-input>
        </div>
      </div>
      <div class="item flex-vertical-center-l">
        <span>*</span>
        <div class="name">剂型：</div>
        <div class="input">
          <el-select size="mini" v-model="form.doseType" placeholder="请选择" :disabled="type=='find'">
            <el-option
              :label="item.value"
              :value="item.key"
              v-for="(item,index) in doseTypeList"
              :key="index"
            ></el-option>
          </el-select>
        </div>
      </div>
      <div class="item flex-vertical-center-l">
        <span></span>
        <div class="name">处方用法：</div>
        <div class="input">
          <el-select
            size="mini"
            v-model="form.recipeUse"
            placeholder="请选择"
            :disabled="type=='find'"
          >
            <el-option
              :label="item.value"
              :value="item.key"
              v-for="(item,index) in recipeUseList"
              :key="index"
            ></el-option>
          </el-select>
        </div>
      </div>
      <div class="item flex-vertical-center-l" v-if="form.doseType=='0'">
        <span></span>
        <div class="name">浓煎每次：</div>
        <div class="input">
          <el-select
            size="small"
            v-model="form.nongjian"
            placeholder="请选择"
            :disabled="type=='find'"
          >
            <el-option label="50ml" value="50"></el-option>
            <el-option label="100ml" value="100"></el-option>
            <el-option label="150ml" value="150"></el-option>
            <el-option label="200ml" value="200"></el-option>
            <el-option label="250ml" value="250"></el-option>
            <el-option label="300ml" value="300"></el-option>
            <el-option label="400ml" value="400"></el-option>
            <el-option label="500ml" value="500"></el-option>
            <el-option label="1000ml" value="1000"></el-option>
          </el-select>
        </div>
      </div>
      <div class="item flex-vertical-center-l" v-if="form.doseType=='1'">
        <span></span>
        <div class="name">每次：</div>
        <div class="input">
          <el-select
            size="small"
            v-model="form.nongjian"
            placeholder="请选择"
            :disabled="type=='find'"
          >
            <el-option label="50ml" value="50"></el-option>
            <el-option label="100ml" value="100"></el-option>
            <el-option label="150ml" value="150"></el-option>
            <el-option label="200ml" value="200"></el-option>
            <el-option label="250ml" value="250"></el-option>
          </el-select>
        </div>
      </div>
      <div class="item flex-vertical-center-l">
        <span></span>
        <div class="name">频次：</div>
        <div class="input">
          <el-select size="small" v-model="form.times" placeholder="请选择" :disabled="type=='find'">
            <el-option
              :label="item.value"
              :value="item.key"
              v-for="(item,index) in timesList"
              :key="index"
            ></el-option>
          </el-select>
        </div>
        <div class="input">
          <el-select size="small" v-model="form.useTime" placeholder="请选择" :disabled="type=='find'">
            <el-option
              :label="item.value"
              :value="item.key"
              v-for="(item,index) in useTimeList"
              :key="index"
            ></el-option>
          </el-select>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import {
  getAccordShareList,
  getChinesMedType,
  addAccordData,
  getAccordDetail
} from "@/api/business.js";
// import TCMDiagnosis from "./components/accoundTCMD.vue";
import TCMDiagnosis from "../../components/TCMDiagnosis.vue";
import { debounce } from "@/utils/format.js";
import {
  getTableDrug,
  getPharmacyID,
  changePharmacy,
  customerQuery
} from "@/api/diagnosis.js";
import MedicineAccord from "../../components/MedicineAccord.vue";
import {getHospitalCategory, getHospitalDepartment, getSelectType} from "@/api/city.js";
export default {
  props: {
    showBtn: {
      type: Boolean,
      default: true
    }
  },
  components: {
    MedicineAccord,
    TCMDiagnosis
  },
  computed: {
    isPurposeType() {
      return this.form.purposeType === '1';
    },
    showPurposeType() {
      return this.showBtn
    }
  },
  data() {
    return {
      hospitalCategory: [],
      hospitalDepartment: [],

      medicineLength: 0,

      shareSelect: [], // 共享至选择器
      doseTypeList: [], // 剂型选择器
      recipeUseList: [], // 处方用法
      timesList: [], // 频次选择器
      useList: [], // 用法选择器
      useTimeList: [], // 服药时间
      pharmacyID: "", // 药房id
      pharmacyList: [],
      cMedType: [
        {
          pharmacyName: "散装",
          pid: "0"
        },
        {
          pharmacyName: "小包装",
          pid: "1"
        }
      ], // 中药类型 pharmacyName /pharmacyId
      form: {
        name: "",
        type: "", // 处方类型
        share: "", // 共享至
        efficacy: "", // 功效
        provenance: "", // 处方出处
        purposeType: "0", // 用途类型 1 八病九方
        sectCategory: '', // 医派
        sectDept: '', // 科室

        times: "", // 频次
        recipeUse: "", // 处方用法
        doseType: "", //剂型

        nongjian: "", // 浓煎

        doseNum: "", // 剂数
        useTime: "" // 服药时间
      },
      totalTableD: [
        {
          id: 1,
          name: "",
          spec: "", // 规格
          dose: "", // 剂量
          unit: "", // 单位
          usage: "", // 用法
          key: "",
          search_i: "",
          // price: '12',
          // total: 12,
          // inventory: '999', // 库存
          usageList: [], // 用法
          drugList: [],
          loadMore: true,
          page: 1
        }
      ],
      tableData: [
        {
          id: 1
        }
      ],
      tableData1: [],
      index: 1,
      pid: "", // 协定方id
      type: "add", // 是否是 查看
      isRecipe: false, // 是否从处方添加
      isNeedOpenRecipe: false
    };
  },
  created() {
    this.pid = this.$route.query.pid ? this.$route.query.pid : "";
    this.type = this.$route.query.type ? this.$route.query.type : "add";

    if (this.type != "find") {
      this.getAccordShareList();
    }
    this.getSelectType("剂型");
    this.getSelectType("处方用法");
    this.getSelectType("中药频次");
    this.getSelectType("中药服药时间");
    this.getSelectType("中药药品用法");
  },
  mounted() {
    if (this.$route.query.pid) {
      this.getAccordDetail().then(() => {
        if (this.isPurposeType) this.getHospitalCategory()
      });
    }
  },
  methods: {
    async getHospitalCategory() {
      this.hospitalCategory = await getHospitalCategory();
      await this.getHospitalDepartment();
    },
    async getHospitalDepartment() {
      this.hospitalDepartment = await getHospitalDepartment({hospital: this.form.sectCategory || ''});
      if (!this.hospitalDepartment.find(item => item.id === this.form.sectDept)) this.form.sectDept = '';
    },
    // 保存按钮点击
    save() {
      if (this.form.name == "") {
        this.$message({
          type: "error",
          message: "请输入方名称",
          showClose: true
        });

        return;
      }

      if (this.form.share == "") {
        this.$message({
          type: "error",
          message: "请选择共享信息",
          showClose: true
        });

        return;
      }

      if (this.form.doseType == "") {
        this.$message({
          type: "error",
          message: "请选择剂型",
          showClose: true
        });

        return;
      }

      if (!this.form.type) {
        this.$message({
          type: "error",
          message: "是否可修改项不能为空",
          showClose: true
        });
        return;
      }

      // let tcmdParams = this.$refs.tcmd.getParams();
      /*if (tcmdParams.namemedicine == "") {
        this.$message({
          type: "error",
          message: "请输入病名",
          showClose: true
        });
        return;
      }*/

      /*if (tcmdParams.syndrometypes == "") {
        this.$message({
          type: "error",
          message: "请输入证型",
          showClose: true
        });
        return;
      }*/

      /*if (tcmdParams.treatment == "") {
        this.$message({
          type: "error",
          message: "请输入治法",
          showClose: true
        });
        return;
      }*/

      this.addAccordData();
    },

    // 合并表一 表二
    arraySpanMethod1({ row, column, rowIndex, columnIndex }) {
      if (!row.name) {
        return [1, 9];
      }
    },

    // 处理开方数据
    dealTableData() {
      let hasDoseNum = true; // 是否有剂数
      let hasData = true; // 是否有处方药品数据

      let children = this.$children.filter(item => {
        return item.name == "中药处方";
      });
      let data1 = children[0];
      this.totalTableD = data1.recipe_tabs[data1.recipe_tabs_c].totalTableD;
      this.tableData = data1.recipe_tabs[data1.recipe_tabs_c].tableData;
      this.tableData1 = data1.recipe_tabs[data1.recipe_tabs_c].tableData1;

      this.totalTableD.forEach(item1 => {
        if (!item1.dose && item1.name) {
          hasDoseNum = false;
        }
      });

      if (!hasDoseNum) {
        this.$message.error("请完善处方剂量信息");
        return false;
      }

      let zhongPrescriptionVo = [];

      this.totalTableD.forEach(item1 => {
        if (item1.name) {
          let obj1 = {
            allprice: item1.total,
            dose: Number(item1.dose),
            drugname: item1.name,
            drugid: item1.medid,
            matid: item1.matid, // 知识库id
            origin: item1.originname,
            seqn: item1.id,
            specification: item1.spec,
            unit: item1.unit,
            unitprice: item1.price,
            usagestr: item1.usage
          };

          zhongPrescriptionVo.push(obj1);
        }
      });

      return zhongPrescriptionVo;
    },
    // 赋值给处方数据
    assignTableData(data, type = "auto") {
      this.totalTableD = [];
      data.forEach((item1, index1) => {
        let obj1 = {
          drugList: [],
          page: 1,
          loadMore: true,
          usageList: this.useList,
          color: item1.color || '',
          id: item1.seqn || item1.id,
          name: item1.drugname || item1.name,
          spec: item1.specification || item1.spec, // 规格
          dose: item1.dose, // 剂量
          unit: item1.unit, // 单位
          usage: item1.usagestr || item1.usage, // 用法
          // usage: item1.usagestr,
          // price: item.unitprice,
          total: item1.price ? item1.dose * item1.price : 0,
          inventory: item1.instock || item1.inventory, // 库存
          key: "",
          search_i: index1,
          matid: item1.matid, // 药品id
          medid: item1.drugid || item1.medid, // 药品id
          originname: item1.origin || item1.originname // 产地名称
        };

        this.totalTableD.push(obj1);
      });
      this.totalTableD.push({
        drugList: [],
        page: 1,
        loadMore: true,
        usageList: [],
        id: Number(data[data.length - 1].seqn) + 1
      });

      this.totalTableD.filter((item3, index3) => {
        return (item3.id = index3 + 1);
      });

      this.tableData = this.totalTableD.filter(item2 => {
        return Number(item2.id) % 2 != 0;
      });
      this.tableData1 = this.totalTableD.filter(item2 => {
        return Number(item2.id) % 2 == 0;
      });

      setTimeout(() => {
        let children = this.$children.filter(item => {
          return item.name == "中药处方";
        });

        let data1 = children[0];

        data1.changePharmacy(
          data1.recipe_tabs[data1.recipe_tabs_c].lastType,
          type
        );
        data1.recipe_tabs[data1.recipe_tabs_c].totalTableD = this.totalTableD;
        data1.recipe_tabs[data1.recipe_tabs_c].tableData = this.tableData;
        data1.recipe_tabs[data1.recipe_tabs_c].tableData1 = this.tableData1;
      }, 1000);
    },

    // 获取共享至信息
    async getAccordShareList() {
      let res = await getAccordShareList();
      if (res.ResultCode == 0) {
        this.shareSelect = res.Data;
      }
    },
    // 获取下拉列表信息
    async getSelectType(data) {
      let res = await getSelectType(data);
      if (res.ResultCode == 0) {
        if (data == "剂型") {
          this.doseTypeList = res.Data;
        } else if (data == "处方用法") {
          this.recipeUseList = res.Data;
        } else if (data == "中药频次") {
          this.timesList = res.Data;
        } else if (data == "中药药品用法") {
          this.useList = res.Data;
        } else if (data == "中药服药时间") {
          this.useTimeList = res.Data;
        }
      }
    },
    // 获取中药类型
    async getChinesMedType(data) {
      let res = await getChinesMedType();
      if (res.ResultCode == 0) {
        this.cMedType = res.Data;
      }
    },
    // 获取药品
    async getTableDrug(key, page, index, load = true) {
      if (!load) return;
      let pharmacyName = "";
      let type = 0;
      this.pharmacyList.forEach(item => {
        if (item.pid == this.pharmacyID) {
          pharmacyName = item.pharmacyName;
        }
      });
      if (this.form.cMedType == 0) {
        if (pharmacyName.indexOf("饮片") != -1) {
          type = 0;
        } else if (pharmacyName.indexOf("颗粒") != -1) {
          type = 1;
        }
      } else {
        if (pharmacyName.indexOf("饮片") != -1) {
          type = 2;
        } else if (pharmacyName.indexOf("颗粒") != -1) {
          type = 3;
        }
      }
      let params = {
        key: key,
        limit: 5,
        page: page,
        type: type, //this.form.cMedType,
        pharmacyid: this.pharmacyID
      };
      let res = await getTableDrug(params);
      if (res.ResultCode == 0) {
        if (page <= res.Data.TotalPageCount) {
          if (page == 1) {
            this.totalTableD[index].drugList = res.Data.Items;
          } else {
            this.totalTableD[index].drugList = [
              ...this.totalTableD[index].drugList,
              ...res.Data.Items
            ];
            this.totalTableD[index].page += 1;
          }

          this.totalTableD.filter((item, index) => {
            return (item.id = index + 1);
          });
          this.tableData = this.totalTableD.filter((item, index) => {
            return item.id % 2 != 0;
          });
          this.tableData1 = this.totalTableD.filter((item, index) => {
            return item.id % 2 == 0;
          });
        } else {
          this.totalTableD[index].loadMore = false;
        }
      }
    },
    //添加协定方数据
    async addAccordData() {
      let children = this.$children.filter(item => {
        return item.name == "中药处方";
      });

      let data1 = children[0];
      let deploymentfree; // 特殊调配费
      let fryingfee; // 代煎费
      let markfree; // 制膏费
      let prescriptionDetailVos = this.dealTableData();

      let colorRed = false;
      this.totalTableD.forEach(item => {
        if (item.color == "red") {
          colorRed = true;
        }
      });

      if (colorRed) {
        this.$message({
          type: "error",
          message: "部分药品不存在,请重新选择",
          showClose: true
        });

        return;
      }

      if (prescriptionDetailVos === false) return;

      this.cMedType.forEach(item => {
        if (item.pharmacyId == this.form.cMedType) {
          deploymentfree = item.deploymentfree;
          fryingfee = item.fryingfee;
          markfree = item.markfree;
        }
      });
      let tcmdParams = this.$refs.tcmd.getParams();
      let params = {
        deploymentfree,
        fryingfee,
        markfree,
        curetype: this.form.doseType,
        density: this.form.nongjian,
        strongFried: this.form.nongjian, //浓煎
        effect: this.form.efficacy,
        provenance: this.showPurposeType ? this.form.provenance : '0',
        purposeType: this.form.purposeType,
        sectCategory: this.form.sectCategory,
        sectDept: this.form.sectDept,
        frequency: this.form.times,
        name: this.form.name,
        pinyincode: this.form.pinyin,
        pid: this.pid,
        prescriptiontype: this.form.cMedType,
        rangtype: this.form.share,
        type: this.form.type,
        usrage: this.form.recipeUse,
        wubicode: this.form.wubi,
        prescriptionDetailVos: prescriptionDetailVos,

        num: Number(this.form.doseNum),
        medicationtime: this.form.useTime,

        pharmacyid: data1.recipe_tabs[data1.recipe_tabs_c].pharmacyID, // 药房id 暂时写死
        drugtype: data1.recipe_tabs[data1.recipe_tabs_c].radio, // 药房类型

        diseasename: tcmdParams.namemedicine,
        diseaseid: tcmdParams.disCode, // 原 disid(病名id)，改为传 disCode(病名code)
        symptomid: tcmdParams.symptomid,
        symptomname: tcmdParams.syndrometypes,
        treatment: tcmdParams.treatment
      };
      if (this.isPurposeType) {
        params.prescriptionDetailVos = params.prescriptionDetailVos.map(item => (item.drugid = null, item));
        params.pharmacyid = null;
        params.drugtype = null;
      }
      const loading = this.$loading({
        lock: true,
        text: "正在提交",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });

      let res = await addAccordData(params).catch(err => {
        loading.close();
      });
      if (res.ResultCode == 0) {
        loading.close();
        this.$message({
          type: "success",
          message: "提交成功",
          showClose: true
        });
        if (this.isRecipe) {
          this.$emit("success", this.isNeedOpenRecipe);
          return;
        }
        if (!this.showBtn) {
          setTimeout(() => {
            this.$router.push({
              path: "/index/accord"
            });
          }, 1000);
        } else {
          setTimeout(() => {
            this.$router.back();
          }, 1000);
        }
      }
    },
    //获取详细信息
    async getAccordDetail() {
      let res = await getAccordDetail(this.$route.query.pid);
      if (res.ResultCode == 0) {
        this.form = {
          name: res.Data.name,
          type: res.Data.type, // 处方类型
          share:
            this.$route.query.type == "find"
              ? res.Data.rangTypeName
              : res.Data.rangtype,
          efficacy: res.Data.effect, // 功效
          provenance: res.Data.provenance, // 处方出处
          purposeType: res.Data.purposeType, // 用途类型 1 八病九方
          sectCategory: res.Data.sectCategory,
          sectDept: res.Data.sectDept,
          // wubi: res.Data.wubicode, // 五笔
          // pinyin: res.Data.pinyincode, // 拼音
          times: res.Data.frequency, // 频次
          recipeUse: res.Data.usrage, // 处方用法
          doseType: res.Data.curetype, //剂型
          // cMedType: res.Data.prescriptiontype, // 中药类型
          nongjian: res.Data.density, // 浓煎
          useTime: res.Data.medicationtime,
          doseNum: res.Data.num
        };
        let tcmd = this.$refs.tcmd;
        let data = {
          namemedicine: res.Data.diseasename,
          disCode: res.Data.diseaseid, // 后端 diseaseid 字段实际返回的是 code，回显赋给 disCode
          //   证型及id
          symptomid: res.Data.symptomid,
          syndrometypes: res.Data.symptomname,
          //   治法
          treatment: res.Data.treatment
        };
        tcmd.setParams(data);
        this.assignTableData(res.Data.prescriptionDetailVos, res.Data.pharmacyid+'@1');
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.accordEdit {
  display: flex;
  flex-direction: column;
  height: 100%;
  > div { flex: none; }
  > div.bottom { flex: auto; }
  
  .sticky {
    position: sticky;
    top: -6px;
    width: 100%;
    background-color: #fff;
    z-index: 11;
    padding-bottom: 5px;
    margin-bottom: 5px;
  }
}
</style>
<style lang="scss" scoped>
@import "../../style/common.scss";

.accordEdit {
  padding: 5px 5px;
  background: #ffffff;
  border-radius: 5px;
  box-sizing: border-box;
  .item {
    font-size: 14px;
    font-family: PingFang SC;
    font-weight: 400;
    color: #333;
    margin-right: 15px;
    margin-bottom: 10px;

    span {
      color: #ff3a3a;
    }

    .input {
      // width: 260px;
      max-width: 500px;
      flex: 1;
    }
  }

  .topForm {
    margin-top: 10px;
  }
}
</style>