<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="处方类型" prop="prescribeType">
        <el-select v-model="queryParams.prescribeType" placeholder="请选择处方类型" clearable size="small">
          <el-option
            v-for="dict in prescribeTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="诊断内容" prop="diagnose">
        <el-input
          v-model="queryParams.diagnose"
          placeholder="请输入诊断内容"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </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>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd(1)"
          v-if="hasPermission('prescribe:add')"
        >新建西药处方</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd(2)"
          v-if="hasPermission('prescribe:add')"
        >新建中药处方</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading"  border :data="prescribeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="处方类型" align="center" prop="prescribeType" width="100px">
        <template slot-scope="scope">
          <dict-tag :options="prescribeTypeOptions" :value="scope.row.prescribeType"/>
        </template>
      </el-table-column>
      <el-table-column label="诊断" align="center" prop="diagnose" />
      <el-table-column label="药品名称" align="center">
        <template slot-scope="scope">
          <span v-for="(size, index) in scope.row.drugs">
            {{ size.drugName }}
            <span v-if="index < scope.row.drugs.length - 1">, </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="药品种类数量" align="center">
        <template slot-scope="scope">
          {{ scope.row.drugs.length }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150px">
        <template slot-scope="scope">
          <el-button
            v-if="orderId!=null"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCreatePrescribe(scope.row)"
          >开处方</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="hasPermission('prescribe:edit')"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="hasPermission('prescribe:delete')"
          >删除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改处方对话框 -->
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="病情诊断" prop="diagnose">
          <el-input v-model="form.diagnose" placeholder="请输入病情诊断" :rows="10" type="textarea" />
        </el-form-item>
        <el-form-item label="药房" prop="storeId" >
          <el-select v-model="form.storeId" placeholder="选择药房" clearable size="small" filterable @change="changeStore">
            <el-option
              v-for="dict in storeOptions"
              :key="dict.storeId"
              :label="dict.storeName"
              :value="dict.storeId"/>
          </el-select>
          <div style="float: right;"><el-button plain  type="primary" icon="el-icon-plus" @click="handleAddProduct">添加商品</el-button></div>
          <div style="margin-top:10px;">
            <el-table border width="100%"   :data="drugList">
              <el-table-column label="药品图片" align="center" prop="drugImgUrl" width="120">
                <template slot-scope="scope">
                  <el-popover
                    placement="right"
                    title=""
                    trigger="hover"
                  >
                    <img slot="reference" :src="scope.row.drugImgUrl" width="100">
                    <img :src="scope.row.drugImgUrl" style="max-width: 150px;">
                  </el-popover>
                </template>
              </el-table-column>
              <el-table-column label="药品名称" align="center" prop="drugName" show-overflow-tooltip  width="150px"/>
              <el-table-column label="药品类型" align="center" prop="drugType" width="100px">
                <template slot-scope="scope">
                  <dict-tag :options="prescribeTypeOptions" :value="scope.row.drugType"/>
                </template>
              </el-table-column>
              <el-table-column label="药品规格" align="center" prop="drugSpec"  />
              <el-table-column label="药品单价" align="center" prop="drugPrice"  />
              <el-table-column label="药品数量" align="center"  prop="drugNum" width="150px" >
                <template slot-scope="scope">
                  <div>
                      <el-input-number v-model="scope.row.drugNum"    size="mini" :min="1"   ></el-input-number>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="用药频率" align="center"  prop="usageFrequencyUnit" width="150px" v-if="form.prescribeType==1" >
                <template slot-scope="scope">
                  <div>
                    <el-select v-model="scope.row.usageFrequencyUnit"  clearable size="small">
                      <el-option
                        v-for="dict in usageFrequencyUnits"
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="dict.dictValue"
                      />
                    </el-select>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="单次用量" align="center"  prop="usagePerUseCount" width="150px" v-if="form.prescribeType==1">
                <template slot-scope="scope">
                  <div>
                    <el-input size="mini" v-model="scope.row.usagePerUseCount"></el-input>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="用药方法" align="center"  prop="usageMethod" width="200px" v-if="form.prescribeType==1" >
                <template slot-scope="scope">
                  <div>
                    <el-select v-model="scope.row.usageMethod"  clearable size="small">
                      <el-option
                        v-for="dict in usageMethods"
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="dict.dictValue"
                      />
                    </el-select>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="备注" align="center"  prop="remark" width="150px" v-if="form.prescribeType==1">
                <template slot-scope="scope">
                  <div>
                    <el-input size="mini" v-model="scope.row.remark"></el-input>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="100px" fixed="right">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleProductDelete(scope.row,scope.$index)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

        </el-form-item>

        <div  v-if="form.prescribeType==2">
          <el-form-item label="用药数量"  >
            <el-input v-model="usageJson.counts" placeholder="请输入用药数量" />
          </el-form-item>
          <el-form-item label="用药频率"  >
            <el-select v-model="usageJson.usageFrequencyUnit" placeholder="请选择用药频率" clearable size="small" filterable>
                <el-option
                  v-for="dict in usageFrequencyUnits"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"/>
              </el-select>
          </el-form-item>
          <el-form-item label="单次用量"  >
            <el-input v-model="usageJson.usagePerUseCount" placeholder="请输入单次用量"  />
          </el-form-item>

          <el-form-item label="用药方法"  >
            <el-select v-model="usageJson.usageMethod" placeholder="请选择用药方法" clearable size="small" filterable>
                <el-option
                  v-for="dict in usageMethods"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"/>
              </el-select>
          </el-form-item>
          <el-form-item label="制作方式" prop="recipeType">
            <el-select v-model="form.recipeType" placeholder="请选择制作方式" clearable size="small" filterable>
                <el-option
                  v-for="dict in recipeTypes"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"/>
              </el-select>
          </el-form-item>
          <el-form-item label="合计" prop="price">
            {{totalAmount.toFixed(2)+'元'}}
          </el-form-item>
        </div>
        <el-form-item label="用药周期"  >
            <el-input-number v-model="form.cycle" :step="6" :min="6" :max="36"></el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
            <el-input v-model="usageJson.remark" placeholder="请输入备注" :rows="2" type="textarea" />
          </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-drawer
            :with-header="false"
            size="75%"
             :title="show.title" :visible.sync="show.open">
         <prescribeDetails  ref="Details" />
    </el-drawer>
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" :title="productShow.title" v-if="productShow.open"  :visible.sync="productShow.open" width="1000px" append-to-body>
        <store-product-attr-value-select  ref="storeProductAttrValueSelect"  @selectProduct="selectProduct" />
    </el-dialog>
  </div>
</template>

<script>
import { getDoctorPrescribeList,getDoctorPrescribe,addPrescribe,editPrescribe,delDoctorPrescribe,createPrescribe } from "@/api/prescribe";
import prescribeDetails from '@/views/components/myDrugStore/prescribeDetails.vue';
import storeProductAttrValueSelect from "@/views/components/myDrugStore/storeProductAttrValueSelect.vue";
import { getStoreList } from "@/api/store";
import { hasPermission } from '@/utils/auth'
export default {
  name: "myDrugStore1",
  components:{prescribeDetails,storeProductAttrValueSelect},
  data() {
    return {
      orderId:null,
      productShow:{
        open:false,
        title:"商品选择"
      },
      show:{
        title:"处方详情",
        open:false,
      },
      // 遮罩层
      loading: true,
      // 选中数组
      storeOptions:[],
      storeId:null,
      totalMoney:0.00,
      drugList:[],
      usageJson:{},
      usageFrequencyUnits:[
        { dictValue: '每日一次', dictLabel: '每日一次' },
        { dictValue: '每日二次', dictLabel: '每日二次' },
        { dictValue: '每日三次', dictLabel: '每日三次' },
        { dictValue: '每日四次', dictLabel: '每日四次' }
      ],
      usageMethods:[
        { dictValue: '口服', dictLabel: '口服' },
        { dictValue: '外敷', dictLabel: '外敷' },
        { dictValue: '注射', dictLabel: '注射' },
      ],
      recipeTypes:[
        { dictValue: 0, dictLabel: '颗粒' },
        { dictValue: 1, dictLabel: '膏方' },
        { dictValue: 2, dictLabel: '饮片' }
      ],
      show:{
        open:false,
      },
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 医生账单记录表格数据
      prescribeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 类型字典
      prescribeTypeOptions: [],
      createTime:null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      drug:{},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        diagnose: [
          { required: true, message: "病情诊断不能为空", trigger: "blur" }
        ],
        storeId: [
          { required: true, message: "药房不能为空", trigger: "blur" }
        ],
        counts: [
          { required: true, message: "用药数量不能为空", trigger: "blur" }
        ],
        usageFrequencyUnit: [
          { required: true, message: "用药频率不能为空", trigger: "blur" }
        ],
        drugNum: [
          { required: true, message: "药品数量不能为空", trigger: "blur" }
        ],
        usagePerUseCount: [
          { required: true, message: "单次用量不能为空", trigger: "blur" }
        ],
        usageMethod: [
          { required: true, message: "用药方法不能为空", trigger: "blur" }
        ],
        recipeType: [
          { required: true, message: "制作方式不能为空", trigger: "blur" }
        ],
      }
    };
  },
  computed: {
    totalAmount() {
      if (!this.drugList || !Array.isArray(this.drugList)) {
        return 0; // 返回默认值或者适当的错误处理
      }
      return this.drugList.reduce((total, item) => total + item.drugPrice * item.drugNum, 0);
    }
  },
  created() {
    getStoreList().then(response => {
      this.storeOptions = response.data;
    });
    this.getDicts("sys_prescribe_type").then(response => {
      this.prescribeTypeOptions = response.data;
    });
    this.getList();
  },
  methods: {
    hasPermission,
    openDrugStore(orderId){
      this.orderId=orderId;
    },
    getList() {
      this.loading = true;
      getDoctorPrescribeList(this.queryParams).then(response => {
        this.prescribeList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    changeStore(){
      this.drugList=[];
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.billId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleProductDelete(row,index){
       this.drugList.splice(index, 1)
    },
    handleAddProduct(){
      if(this.form.storeId==null||this.form.storeId==""){
        return  this.$message({
          message: '请选择店铺',
          type: 'warning'
        });
      }else {
        setTimeout(() => {
             this.$refs.storeProductAttrValueSelect.getDetails(this.form.storeId);
        }, 1);
        this.productShow.open=true;
      }
    },
    selectProduct(row){
      // if(this.form.prescribeType==row.productType){
        const drug = {};
        for(var i=0;i<this.drugList.length;i++){
          if(this.drugList[i].productAttrValueId==row.id){
            return;
          }
        }
        drug.productAttrValueId=row.id;
        drug.productId=row.productId;
        drug.drugName = row.productName;
        drug.drugName = row.productName;
        drug.drugImgUrl = row.image;
        drug.drugType = row.productType;
        drug.drugSpec = row.sku;
        drug.drugPrice = row.price;
        drug.drugNum = 1;
        drug.usageFrequencyUnit="每日三次";
        drug.usageMethod="口服";
        this.drugList.push(drug);
        this.$message({
          message: '添加成功',
          type: 'success'
        });
      // }else{
      //   return  this.$message({
      //     message: '请选择正确类型的药品',
      //     type: 'warning'
      //   });
      // }
    },
    /** 新增按钮操作 */
    handleAdd(type) {
      this.reset();
      this.storeId=null,
      this.drugList=null;
      this.open = true;
      this.form.prescribeType =type;
      this.form.cycle=6;
      if(type==1){
        this.title = "新建西药处方";
      }
      else if(type==2){
        this.title = "新建中药处方";
        this.usageJson={
          usageFrequencyUnit:"每日三次",
          usageMethod:"口服"
        };
        console.log(this.form)
      }

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.storeId=null,
      this.drugList=null;
      const prescribeId = row.prescribeId ;
      getDoctorPrescribe(prescribeId).then(response => {
        this.form = response.data.prescribe;
        if(this.form.cycle==null){
          this.form.cycle=6;
        }
        this.open = true;
        this.title = "编辑处方";
        this.drugList=response.data.drugs;
        if(this.form.usageJson!=null){
          this.usageJson = JSON.parse(response.data.prescribe.usageJson);
        }

      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.drugs = this.drugList;
          this.form.usageJson = JSON.stringify(this.usageJson);
          if (this.form.prescribeId != null) {
            editPrescribe(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPrescribe(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
      /** 删除按钮操作 */
    handleDelete(row) {
      const prescribeId = row.prescribeId ;
      var data={
        prescribeId:prescribeId
      }
      this.$confirm('是否确认删除当前处方的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          return delDoctorPrescribe(data);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    handleCreatePrescribe(row) {
      var data={
        prescribeId :row.prescribeId,
        orderId :this.orderId
      }
      this.$confirm('确认开方吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          return createPrescribe(data);
        }).then((res) => {
          if(res.code==200){
            this.msgSuccess("开方成功");
          }
          else{
            this.msgError(res.msg);
          }
        }).catch((res) => {

        });
    },

  }
};
</script>

