<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <div class="query-box">
        <div class="query-box__left">
          <el-form-item label="" prop="type">
            <el-select
              v-model="queryParams.type"
              placeholder="请选择处方类型"
              style="width: 160px"
            >
              <el-option
                v-for="item in typeArr"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="" prop="fyState">
            <el-select
              v-model="queryParams.fyState"
              placeholder="请选择发药状态"
              style="width: 160px"
            >
              <el-option
                v-for="item in stateArr"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="" prop="premzzy">
            <el-select
              v-model="queryParams.premzzy"
              placeholder="请选择门诊住院"
              style="width: 160px"
            >
              <el-option
                v-for="item in premzzyArr"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="" prop="takingMethod">
            <el-select
              v-model="queryParams.takingMethod"
              placeholder="请选择配送方式"
              style="width: 160px"
            >
              <el-option
                v-for="item in takingMethodArr"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="" prop="prescriptionTime">
            <el-date-picker
              clearable
              size="small"
              v-model="queryParams.prescriptionTime"
              type="daterange"
              value-format="yyyy-MM-dd"
              start-placeholder="选择处方时间"
              end-placeholder="选择处方时间"
              style="width: 240px"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="" prop="name">
            <el-input v-model="queryParams.name" placeholder="处方名/姓名"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </div>

        <!-- <div class="query-box__right">
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </div> -->
      </div>
    </el-form>

    <el-row :gutter="20" style="margin-top: 50px">
      <el-col :span="12">
        <el-table
          v-loading="loading"
          :data="prescriptionCoreList"
          @selection-change="handleSelectionChange"
          :row-class-name="tableRowClassName"
          @row-click="rowClick"
          class="el-table__row1"
          border
        >
          <el-table-column
            type="index"
            width="55"
            align="center"
            label="序号"
          />
          <el-table-column type="selection" width="55" align="center" />
          <!-- <el-table-column label="药品名称" align="center" prop="preNo" /> -->
          <el-table-column label="处方号" align="center" prop="preNo" />
          <el-table-column label="患者姓名" align="center" prop="name" />
          <el-table-column label="开方医生" align="center" prop="doctor" />
          <!-- <el-table-column label="药品名称" align="center" prop="matName"/> -->
          <el-table-column label="煎药方式" align="center" prop="oralPre">
            <template slot-scope="scope">
              {{ scope.row.oralPre && scope.row.oralPre.decoctingMethod }}
            </template>
          </el-table-column>
          <el-table-column label="取药方式" align="center" prop="takingMethod"></el-table-column>
          <el-table-column label="处方类型" align="center" prop="type">
            <template slot-scope="scope">
              {{ scope.row.type == 1 ? "中药处方" : "中药制剂" }}
            </template>
          </el-table-column>
          <el-table-column label="处方名" align="center" prop="preName" />
          <el-table-column label="剂数" align="center" prop="oralPre">
            <template slot-scope="scope">
              {{ scope.row.oralPre && scope.row.oralPre.number }}
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>

      <el-col :span="12">
        <!-- <el-table
          v-loading="loading"
          :data="fyList"
          border
          show-summary
          :summary-method="getSummaries"
        >
          <el-table-column type="index" width="55" align="center" />
          <el-table-column
            label="药品名称"
            align="center"
            :prop="oralPre && oralPre.oralPreItemList[0].matName"
          />
          <el-table-column
            label="药品规格"
            align="center"
            :prop="oralPre && oralPre.oralPreItemList[0].ypggCenter"
          />
          <el-table-column
            label="药品单位"
            align="center"
            :prop="oralPre && oralPre.oralPreItemList[0].matUnitName"
          />
          <el-table-column
            label="数量"
            align="center"
            :prop="oralPre && solidPre.solidPreList[0].matDose"
          />
          <el-table-column
            label="产地"
            align="center"
            :prop="oralPre && oralPre.oralPreItemList[0].matOrigin"
          />
          <el-table-column
            label="零售价"
            align="center"
            :prop="oralPre && oralPre.oralPreItemList[0].matXsj"
          />
          <el-table-column
            label="小计"
            align="center"
            :prop="oralPre && oralPre.oralPreItemList[0].subtotalMoney"
          />
          <el-table-column
            label="库存数量"
            align="center"
            :prop="solidPre && solidPre.solidPreList[0].matDose"
          />
        </el-table>
        <el-table
          v-loading="loading"
          :data="fyList"
          border
          show-summary
          :summary-method="getSummaries"
        > -->
        <el-table
          v-loading="loading"
          :data="fyList"
          border
          show-summary
          :summary-method="getSummaries"
        >
          <el-table-column type="index" width="55" align="center" />
          <el-table-column
            label="药品名称"
            align="center"
            prop="matName"
          />
          <el-table-column
            label="药品规格"
            align="center"
            prop="ypggCenter"
          />
          <el-table-column
            label="药品单位"
            align="center"
            prop="matUnitName"
          />
          <el-table-column
            label="数量"
            align="center"
            prop="matDose"
          />
          <el-table-column
            label="产地"
            align="center"
            prop="matOrigin"
          />
          <el-table-column
            label="零售价"
            align="center"
            prop="matXsj"
          />
          <el-table-column
            label="小计"
            align="center"
            prop="subtotalMoney"
          >
            <template slot-scope="scope">{{(scope.row.subtotalMoney).toFixed(4)}}</template>
          </el-table-column>
          <el-table-column
            label="库存数量"
            align="center"
            prop="stock"
          />
        </el-table>

        <pagination
          v-show="fyTotal > 0"
          :total="fyTotal"
          :page.sync="fyPageName"
          :limit="10"
          @pagination="getListFy(rowId)"
        />
      </el-col>
    </el-row>

    <el-button @click="stateBtn(1)">发药</el-button>
    <el-button @click="stateBtn(2)">取消发药</el-button>
  </div>
</template>

<script>
import {
  listPrescriptionCoreNew,
  getPrescriptionCore,
  delPrescriptionCore,
  addPrescriptionCore,
  updatePrescriptionCore,
  exportPrescriptionCore,
  check,
  listPrescriptionCoreFy,
  fyState,
} from "@/api/prescription/prescriptionCore";

import { listMedicalMechanism } from "@/api/medical/mechanism";

export default {
  name: "PrescriptionCore",
  data() {
    return {
      remarks: "",
      btnState: 1,
      rowId: null,
      detailData: {},
      activeName: "second",
      rowId: null,
      state: {
        1: "配药",
        2: "煎药",
        3: "发药",
        4: "配送",
      },
      typeArr: [
        { name: "中药处方", id: 1 },
        { name: "中药制剂", id: 2 },
      ],
      stateArr: [
        { name: "全部", id: '' },
        { name: "已发药", id: 1 },
        { name: "未发药", id: 0 },
      ],
      premzzyArr: [
        { name: "门诊", id: 1 },
        { name: "住院", id: 2 },
      ],
      takingMethodArr: [
        { name: "自提", id: '自提' },
        { name: "配送", id: '配送' },
      ],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      fyTotal: 0,
      fyPageName: 1,
      // 处方审核表格数据
      prescriptionCoreList: [],
      fyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        // thread: 170,
        pageNum: 1,
        pageSize: 10,
        //state: 3,
        checkState: 1,
        fyState: 0,
        premzzy: null,
        takingMethod: null,
        appId: null,
        yljgId: null,
        timeStamp: null,
        token: null,
        preNo: null,
        preName: null,
        department: null,
        doctor: null,
        prescriptionTime: [],
        disCode: null,
        disName: null,
        symCode: null,
        symName: null,
        westernDisease: null,
        westernCode: null,
        patientContent: null,
        nowDesc: null,
        pastDesc: null,
        fourDiagnosis: null,
        physical: null,
        auxiliaryExam: null,
        premzzy: null,
        extendedTxt: null,
        address: null,
        contactNumber: null,
        consignee: null,
        takingMethod: null,
        yfId: window.localStorage.getItem("pharmacyId"),
        type: null,
        name: ''
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      listMedicalMechanismArr: [],
    };
  },
  created() {
    var date = new Date()
    var date2 = Date.now() - 24 * 3600 * 1000
    this.queryParams.prescriptionTime = [this.getTime(date2), this.getTime(date)]
    this.getList();
    // this.getListMedicalMechanism();
  },
  methods: {
    /** 表单合计 **/
    /*getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计1";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (
          index === 4 ||
          index === 6 ||
          index === 7 ||
          index === 8
        ) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr * 1000;
            } else {
              return prev;
            }
          }, 0);
          sums[index] = (sums[index]/1000).toFixed(4);
        } else {
          sums[index] = "/";
        }
      })
    },*/
    getTime (val) {
      var t = new Date(val)
      var y = t.getFullYear(t)
      var m = t.getMonth() + 1
      var d = t.getDate()
      m = m < 10 ? '0' + m : m
      d = d < 10 ? '0' + d : d
      return y + '-' + m + '-' + d
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总价";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (index === 4 || index === 6 || index === 7 || index === 8) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr * 1000;
            } else {
              return prev;
            }
          }, 0);
          if (index == 6 || index == 7) {
            sums[index] = (sums[index] / 1000).toFixed(4)
          } else {
            sums[index] = sums[index] / 1000
          }
        } else {
          sums[index] = "/";
        }
      });
      return sums;
    },
    //发药状态更改
    stateBtn(num) {
      if (!this.ids.length) {
        return this.$message.warning('请先选择操作的数据')
      }
      let parms = {
        ids: this.ids,
        fyState: num,
      };
      fyState(parms).then((res) => {
        this.getList()
        this.msgSuccess("修改成功");
      });
    },
    handleClick(tab, event) {
      //console.log(tab, event);
    },
    tableRowClassName({ row, rowIndex }) {
      //把每一行的索引放进row
      row.index = rowIndex;
    },
    rowClick(row) {
      $(".el-table__row1 .el-table__row")
        .eq(row.index)
        .css("background", "#F5F7FA")
        .siblings()
        .css("background", "#fff");
      this.getListFy(row.id);
      //   this.firstId = row.id;
      //   this.drugsId = row.id;
      //   this.row = row;
      this.rowId = row.id;
    },
    /** 发药接口 **/
    getListFy(id) {
      listPrescriptionCoreFy({
        id,
        pageNum: this.fyPageName,
        pageSize: 10,
        //checkState: 1,
      }).then((res) => {
        //console.log(res);
        this.fyList = res.rows;
        this.fyList.forEach(v => {
          v.subtotalMoney = v.matDose * v.matXsj
          //v.subtotalMoney *= 1000
        })
        this.fyTotal = res.total;
      });
    },
    /** 查询处方审核列表 */
    getList() {
      this.loading = true;
      var form = Object.assign({}, this.queryParams)
      if (this.queryParams.prescriptionTime && this.queryParams.prescriptionTime.length) {
        form.startTime = this.queryParams.prescriptionTime[0]
        form.endTime = this.queryParams.prescriptionTime[1]
        delete form.prescriptionTime
      }
      if (form.fyState === '') {
        delete form.fyState
      }
      listPrescriptionCoreNew(form).then((response) => {
        this.prescriptionCoreList = response.rows
        this.total = response.total;
        if (this.prescriptionCoreList.length) {
          this.rowId = response.rows[0].id;
          this.getListFy(response.rows[0].id);
          this.$nextTick(() => {
            $(".el-table__row1 .el-table__row")
            .eq(0)
            .css("background", "#F5F7FA")
            .siblings()
            .css("background", "#fff");
          })
        } else {
          this.fyTotal = 0
          this.fyList = []
        }
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    //审核拒绝
    checkBtn(num) {
      //console.log(num);
      let params = {
        checkState: num,
        id: this.rowId,
        remarks: this.remarks,
      };
      check(params).then((res) => {
        //console.log(res);
        if (res.code) {
          this.msgSuccess("修改成功");
          this.open = false;
        }
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        remarks: null,
      };
      this.remarks = null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updatePrescriptionCore(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPrescriptionCore(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
  },
};
</script>
<style scoped>
h3 {
  margin: 0;
}
</style> 